Programs & Examples On #Multitargeting

Android: java.lang.SecurityException: Permission Denial: start Intent

I had this problem with this exact activity.

You can't start com.fsck.k9.activity.MessageList from an external activity.

I solved it with:

Intent LaunchK9 = getPackageManager().getLaunchIntentForPackage("com.fsck.k9"); this.startActivity(LaunchK9);

Using http://developer.android.com/reference/android/content/pm/PackageManager.html

CodeIgniter - accessing $config variable in view

Also, the Common function config_item() works pretty much everywhere throughout the CodeIgniter instance. Controllers, models, views, libraries, helpers, hooks, whatever.

Find IP address of directly connected device

Mmh ... there are many ways. I answer another network discovery question, and I write a little getting started.

Some tcpip stacks reply to icmp broadcasts. So you can try a PING to your network broadcast address.

For example, you have ip 192.168.1.1 and subnet 255.255.255.0

  1. ping 192.168.1.255
  2. stop the ping after 5 seconds
  3. watch the devices replies : arp -a

Note : on step 3. you get the lists of the MAC-to-IP cached entries, so there are also the hosts in your subnet you exchange data to in the last minutes, even if they don't reply to icmp_get.

Note (2) : now I am on linux. I am not sure, but it can be windows doesn't reply to icm_get via broadcast.

Is it the only one device attached to your pc ? Is it a router or another simple pc ?

How to submit a form using PhantomJS

Also, CasperJS provides a nice high-level interface for navigation in PhantomJS, including clicking on links and filling out forms.

CasperJS

Updated to add July 28, 2015 article comparing PhantomJS and CasperJS.

(Thanks to commenter Mr. M!)

How to present popover properly in iOS 8

Implement UIAdaptivePresentationControllerDelegate in your Viewcontroller. Then add :

func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle{
    return .none
}

Recommended SQL database design for tags or tagging

I would suggest following design : Item Table: Itemid, taglist1, taglist2
this will be fast and make easy saving and retrieving the data at item level.

In parallel build another table: Tags tag do not make tag unique identifier and if you run out of space in 2nd column which contains lets say 100 items create another row.

Now while searching for items for a tag it will be super fast.

Convert float to string with precision & number of decimal digits specified?

You can use C++20 std::format or the fmt::format function from the {fmt} library, std::format is based on:

#include <fmt/core.h>

int main()
  std::string s = fmt::format("{:.2f}", 3.14159265359); // s == "3.14"
}

where 2 is a precision.

WCF vs ASP.NET Web API

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

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


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

enter image description here


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

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


In the scenarios listed below you should go for WCF:

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

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

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

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

Android - Dynamically Add Views into View

Use the LayoutInflater to create a view based on your layout template, and then inject it into the view where you need it.

LayoutInflater vi = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = vi.inflate(R.layout.your_layout, null);

// fill in any details dynamically here
TextView textView = (TextView) v.findViewById(R.id.a_text_view);
textView.setText("your text");

// insert into main view
ViewGroup insertPoint = (ViewGroup) findViewById(R.id.insert_point);
insertPoint.addView(v, 0, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT));

You may have to adjust the index where you want to insert the view.

Additionally, set the LayoutParams according to how you would like it to fit in the parent view. e.g. with FILL_PARENT, or MATCH_PARENT, etc.

Word count from a txt file program

print("sorted counting values:-")
from collections import Counter

fname = open(filename)

fname = fname.read()

fsplit = fname.split()

user  = Counter(fsplit)

for i,v in sorted(user.items()):

   print((v,i))

How to save to local storage using Flutter?

If you need to store just simple values like API token or login data (not passwords!), here is what I used:

import 'package:shared_preferences/shared_preferences.dart';

asyncFunc() async { // Async func to handle Futures easier; or use Future.then
  SharedPreferences prefs = await SharedPreferences.getInstance();
}
...

// Set
prefs.setString('apiToken', token);

// Get
String token = prefs.getString('apiToken');

// Remove
prefs.remove('apiToken');

Don't forget to add shared_preferences dependency in your pubspec.yaml (preserve spacing format):

dependencies:

  shared_preferences: any

Change header text of columns in a GridView

You can do it with gridview's datarow bound event. try the following sample of code:

protected void grv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
e.Row.Cells[0].Text = "TiTle";
}
}

For more details about the row databound event study Thsi....

How can I force component to re-render with hooks in React?

One line solution:

const useForceUpdate = () => useState()[1];

useState returns a pair of values: the current state and a function that updates it - state and setter, here we are using only the setter in order to force re-render.

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

The boto3 is looking for the credentials in the folder like

C:\ProgramData\Anaconda3\envs\tensorflow\Lib\site-packages\botocore\.aws

You should save two files in this folder credentials and config.

You may want to check out the general order in which boto3 searches for credentials in this link. Look under the Configuring Credentials sub heading.

Typescript: How to define type for a function callback (as any function type, not universal any) used in a method parameter

The global type Function serves this purpose.

Additionally, if you intend to invoke this callback with 0 arguments and will ignore its return value, the type () => void matches all functions taking no arguments.


Update with details and improvements.

The answer and question here has way too many updoots not to mention the only-slightly more complex yet best-practice method:

Solution to your question

interface Easy_Fix_Solution {
    title: string;
    callback: Function;
}

NOTE: Please do not use Function as you most likely do not want any callback function. It's okay to be a little specific.

Improvement to that solution

interface Safer_Easy_Fix {
    title: string;
    callback: () => void;
}
interface Alternate_Syntax_4_Safer_Easy_Fix {
    title: string;
    callback(): void;
}

NOTE: The original author is correct, accepting no arguments and returning void is better.. it's much safer, it tells the consumer of your interface that you will not be doing anything with their return value, and that you will not be passing them any parameters.

And better yet Use generics. This interface would also work for the same () => void function types mentioned before.

interface Better_still_safe_but_way_more_flexible_fix {
    title: string;
    callback: <T = unknown, R = unknown>(args?: T) => R;
}
interface Alternate_Syntax_4_Better_still_safe_but_way_more_flexible_fix {
    title: string;
    callback<T = unknown, R = unknown>(args?: T): R;
}

NOTE: If you aren't 100% sure about the callback signature right now, please choose the void option above, or this generic option if you think you may extend functionality going forward. Callbacks usually receive some arguments of some sort, and sometimes the callback orchestrator even does something with the return value.

And a slightly more advanced usecase you shouldn't use unless you need it

This allows any number of arguments, of any type in T.

More details here.

interface Alternate_Syntax_4_Advanced {
    title: string;
    callback<T extends unknown[], R = unknown>(...args?: T): R;
}

Preventing an image from being draggable or selectable without using JS

You could probably just resort to

<img src="..." style="pointer-events: none;">

SQL Server: Is it possible to insert into two tables at the same time?

If you want the actions to be more or less atomic, I would make sure to wrap them in a transaction. That way you can be sure both happened or both didn't happen as needed.

Multiple conditions in WHILE loop

If your code, if the user enters 'X' (for instance), when you reach the while condition evaluation it will determine that 'X' is differente from 'n' (nChar != 'n') which will make your loop condition true and execute the code inside of your loop. The second condition is not even evaluated.

Make index.html default, but allow index.php to be visited if typed in

Hi,

Well, I have tried the methods mentioned above! it's working yes, but not exactly the way I wanted. I wanted to redirect the default page extension to the main domain with our further action.

Here how I do that...

# Accesible Index Page
<IfModule dir_module>
 DirectoryIndex index.php index.html
 RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /index\.(html|htm|php|php3|php5|shtml|phtml) [NC]
 RewriteRule ^index\.html|htm|php|php3|php5|shtml|phtml$ / [R=301,L]
</IfModule>

The above code simply captures any index.* and redirect it to the main domain.

Thank you

How to place a div below another div?

what about changing the position: relative on your #content #text div to position: absolute

#content #text {
   position:absolute;
   width:950px;
   height:215px;
   color:red;
}

http://jsfiddle.net/CaZY7/12/

then you can use the css properties left and top to position within the #content div

Get the selected option id with jQuery

Th easiest way to this is var id = $(this).val(); from inside an event like on change.

Removing double quotes from variables in batch file creates problems with CMD environment

The simple tilde syntax works only for removing quotation marks around the command line parameters being passed into the batch files

SET xyz=%~1

Above batch file code will set xyz to whatever value is being passed as first paramter stripping away the leading and trailing quotations (if present).

But, This simple tilde syntax will not work for other variables that were not passed in as parameters

For all other variable, you need to use expanded substitution syntax that requires you to specify leading and lagging characters to be removed. Effectively we are instructing to remove strip away the first and the last character without looking at what it actually is.

@SET SomeFileName="Some Quoted file name"
@echo %SomeFileName% %SomeFileName:~1,-1%

If we wanted to check what the first and last character was actually quotation before removing it, we will need some extra code as follows

@SET VAR="Some Very Long Quoted String"
If aa%VAR:~0,1%%VAR:~-1%aa == aa""aa SET UNQUOTEDVAR=%VAR:~1,-1%

Getting "method not valid without suitable object" error when trying to make a HTTP request in VBA?

I had to use Debug.print instead of Print, which works in the Immediate window.

Sub SendEmail()
    'Dim objHTTP As New MSXML2.XMLHTTP
    'Set objHTTP = New MSXML2.XMLHTTP60
    'Dim objHTTP As New MSXML2.XMLHTTP60
    Dim objHTTP As New WinHttp.WinHttpRequest
    'Set objHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
    'Set objHTTP = CreateObject("MSXML2.ServerXMLHTTP")
    URL = "http://localhost:8888/rest/mail/send"
    objHTTP.Open "POST", URL, False
    objHTTP.setRequestHeader "Content-Type", "application/json"
    objHTTP.send ("{""key"":null,""from"":""[email protected]"",""to"":null,""cc"":null,""bcc"":null,""date"":null,""subject"":""My Subject"",""body"":null,""attachments"":null}")
    Debug.Print objHTTP.Status
    Debug.Print objHTTP.ResponseText

End Sub

Interpreting "condition has length > 1" warning from `if` function

Use lapply function after creating your function normally.

lapply(x="your input", fun="insert your function name")

lapply gives a list so use unlist function to take them out of the function

unlist(lapply(a,w))

How To Save Canvas As An Image With canvas.toDataURL()?

This work for me: (Only google chrome)

<html>
<head>
    <script>
            function draw(){
                var canvas = document.getElementById("thecanvas");
                var ctx = canvas.getContext("2d");
                ctx.fillStyle = "rgba(125, 46, 138, 0.5)";
                ctx.fillRect(25,25,100,100);
                ctx.fillStyle = "rgba( 0, 146, 38, 0.5)";
                ctx.fillRect(58, 74, 125, 100);
            }

            function downloadImage()
            {
                var canvas = document.getElementById("thecanvas");
                var image = canvas.toDataURL();

                var aLink = document.createElement('a');
                var evt = document.createEvent("HTMLEvents");
                evt.initEvent("click");
                aLink.download = 'image.png';
                aLink.href = image;
                aLink.dispatchEvent(evt);
            }
    </script>
</head>
<body onload="draw()">
    <canvas width=200 height=200 id="thecanvas"></canvas>
    <div><button onclick="downloadImage()">Download</button></div>
    <image id="theimage"></image>
</body>
</html>

Create iOS Home Screen Shortcuts on Chrome for iOS

The is no API for adding a shortcut to the home screen in iOS, so no third-party browser is capable of providing that functionality.

Yes or No confirm box using jQuery

Have a look at this jQuery plugin: jquery.confirm.

<a href="home" class="confirm">Go to home</a>

and then:

$(".confirm").confirm();

This will show a confirmation popup before proceeding to following the link.

There's a demo here: http://myclabs.github.com/jquery.confirm/

Hidden features of Windows batch files

Find strings in files in a folder using the pipe '|' command:

dir /b *.* | findstr /f:/ "thepattern"

How to I say Is Not Null in VBA

Use Not IsNull(Fields!W_O_Count.Value)

Remove property for all objects in array

If you use underscore.js:

var strippedRows = _.map(rows, function (row) {
    return _.omit(row, ['bad', 'anotherbad']);
});

How to check whether input value is integer or float?

You can use Scanner Class to find whether a given number could be read as Int or Float type.

 import java.util.Scanner;
 public class Test {
     public static void main(String args[] ) throws Exception {

     Scanner sc=new Scanner(System.in);

     if(sc.hasNextInt())
         System.out.println("This input is  of type Integer");
     else if(sc.hasNextFloat())
         System.out.println("This input is  of type Float");
     else
         System.out.println("This is something else");
     }
}

Auto select file in Solution Explorer from its open tab

The best option now is to install the Microsoft Visual Studio add on called Productivity Power Tools.

With this comes "Solution Navigator" (alternative to Solution Explorer, with a lot of benefits) - which then you can use to filter the files to only show "Open". You can even filter files to show "Edited" and "Unsaved".

Windows could not start the SQL Server (MSSQLSERVER) on Local Computer... (error code 3417)

A few times now, I've experienced various instances MS SQL Server to fail with this error after a Windows update. Most of the quick fixes above did not work for me.

What did:

  • copy all production databases over to some safe place
  • remove everything SQL Server via add/remove programs
  • get the latest SQL Server Express or Dev & install it
  • move the databases over to their home and reattach them.

For me, this was the fastest solution. Trying to find the cause of the error and fixing it is an afternoon of googling misty error messages. But YMMV.

Bootstrap 3.0 Sliding Menu from left

Probably late but here is a plugin that can do the job : http://multi-level-push-menu.make.rs/

Also v2 can use mobile gesture such as swipe ;)

Killing a process using Java

If you start the process from with in your Java application (ex. by calling Runtime.exec() or ProcessBuilder.start()) then you have a valid Process reference to it, and you can invoke the destroy() method in Process class to kill that particular process.

But be aware that if the process that you invoke creates new sub-processes, those may not be terminated (see http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4770092).

On the other hand, if you want to kill external processes (which you did not spawn from your Java app), then one thing you can do is to call O/S utilities which allow you to do that. For example, you can try a Runtime.exec() on kill command under Unix / Linux and check for return values to ensure that the application was killed or not (0 means success, -1 means error). But that of course will make your application platform dependent.

Android button font size

Another approach:

declaring an int first with the default fontsize

int txtSize = 16;

           button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mTextView.setTextSize(txtSize++);
                }
            });

Vue Js - Loop via v-for X times (in a range)

I had to add parseInt() to tell v-for it was looking at a number.

<li v-for="n in parseInt(count)" :key="n">{{n}}</li>

How do I declare a global variable in VBA?

To use global variables, Insert New Module from VBA Project UI and declare variables using Global

Global iRaw As Integer
Global iColumn As Integer

How can I determine whether a 2D Point is within a Polygon?

For the completeness, here's the lua implementation of the algorithm provided by nirg and discussed by Mecki:

function pnpoly(area, test)
    local inside = false
    local tx, ty = table.unpack(test)
    local j = #area
    for i=1, #area do
        local vxi, vyi = table.unpack(area[i])
        local vxj, vyj = table.unpack(area[j])
        if (vyi > ty) ~= (vyj > ty)
        and tx < (vxj - vxi)*(ty - vyi)/(vyj - vyi) + vxi
        then
            inside = not inside
        end
        j = i
    end
    return inside
end

The variable area is a table of points which are in turn stored as 2D tables. Example:

> A = {{2, 1}, {1, 2}, {15, 3}, {3, 4}, {5, 3}, {4, 1.5}}
> T = {2, 1.1}
> pnpoly(A, T)
true

The link to GitHub Gist.

MySQL Query - Records between Today and Last 30 Days

SELECT
    *
FROM
    < table_name >
WHERE
    < date_field > BETWEEN DATE_SUB(NOW(), INTERVAL 30 DAY)
AND NOW();

Jquery validation plugin - TypeError: $(...).validate is not a function

You didn't include the base jQuery Validation library:

<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.js"></script>

Put that before the additional methods library. (BTW this is a hosted version, download your own if you want)

Convert month int to month name

var monthIndex = 1;
return month = DateTimeFormatInfo.CurrentInfo.GetAbbreviatedMonthName(monthIndex);

You can try this one as well

React-router v4 this.props.history.push(...) not working

So I came to this question hoping for an answer but to no avail. I have used

const { history } = this.props;
history.push("/thePath")

In the same project and it worked as expected. Upon further experimentation and some comparing and contrasting, I realized that this code will not run if it is called within the nested component. Therefore only the rendered page component can call this function for it to work properly.

Find Working Sandbox here

  • history: v4.7.2
  • react: v16.0.0
  • react-dom: v16.0.0
  • react-router-dom: v4.2.2

Prevent double submission of forms in jQuery

I solved a very similar issue using:

$("#my_form").submit(function(){
    $('input[type=submit]').click(function(event){
        event.preventDefault();
    });
});

Is there a null-coalescing (Elvis) operator or safe navigation operator in javascript?

This is more commonly known as a null-coalescing operator. Javascript does not have one.

How do I get video durations with YouTube API version 3?

I wrote the following class to get YouTube video duration using the YouTube API v3 (it returns thumbnails as well):

class Youtube
{
    static $api_key = '<API_KEY>';
    static $api_base = 'https://www.googleapis.com/youtube/v3/videos';
    static $thumbnail_base = 'https://i.ytimg.com/vi/';

    // $vid - video id in youtube
    // returns - video info
    public static function getVideoInfo($vid)
    {
        $params = array(
            'part' => 'contentDetails',
            'id' => $vid,
            'key' => self::$api_key,
        );

        $api_url = Youtube::$api_base . '?' . http_build_query($params);
        $result = json_decode(@file_get_contents($api_url), true);

        if(empty($result['items'][0]['contentDetails']))
            return null;
        $vinfo = $result['items'][0]['contentDetails'];

        $interval = new DateInterval($vinfo['duration']);
        $vinfo['duration_sec'] = $interval->h * 3600 + $interval->i * 60 + $interval->s;

        $vinfo['thumbnail']['default']       = self::$thumbnail_base . $vid . '/default.jpg';
        $vinfo['thumbnail']['mqDefault']     = self::$thumbnail_base . $vid . '/mqdefault.jpg';
        $vinfo['thumbnail']['hqDefault']     = self::$thumbnail_base . $vid . '/hqdefault.jpg';
        $vinfo['thumbnail']['sdDefault']     = self::$thumbnail_base . $vid . '/sddefault.jpg';
        $vinfo['thumbnail']['maxresDefault'] = self::$thumbnail_base . $vid . '/maxresdefault.jpg';

        return $vinfo;
    }
}

Please note that you'll need API_KEY to use the YouTube API:

  1. Create a new project here: https://console.developers.google.com/project
  2. Enable "YouTube Data API" under "APIs & auth" -> APIs
  3. Create a new server key under "APIs & auth" -> Credentials

setup.py examples?

Here is the utility I wrote to generate a simple setup.py file (template) with useful comments and links. I hope, it will be useful.

Installation

sudo pip install setup-py-cli

Usage

To generate setup.py file just type in the terminal.

setup-py

Now setup.py file should occur in the current directory.

Generated setup.py

from distutils.core import setup
from setuptools import find_packages
import os


# User-friendly description from README.md
current_directory = os.path.dirname(os.path.abspath(__file__))
try:
    with open(os.path.join(current_directory, 'README.md'), encoding='utf-8') as f:
        long_description = f.read()
except Exception:
    long_description = ''

setup(
    # Name of the package
    name=<name of current directory>,

    # Packages to include into the distribution
    packages=find_packages('.'), 

    # Start with a small number and increase it with every change you make
    # https://semver.org
    version='1.0.0',

    # Chose a license from here: https://help.github.com/articles/licensing-a-repository
    # For example: MIT
    license='',

    # Short description of your library
    description='',

    # Long description of your library
    long_description = long_description,
    long_description_context_type = 'text/markdown',

    # Your name
    author='', 

    # Your email
    author_email='',     

    # Either the link to your github or to your website
    url='',

    # Link from which the project can be downloaded
    download_url='',

    # List of keyword arguments
    keywords=[],

    # List of packages to install with this one
    install_requires=[],

    # https://pypi.org/classifiers/
    classifiers=[]  
)

Content of the generated setup.py:

  • automatically fulfilled package name based on the name of the current directory.
  • some basic fields to fulfill.
  • clarifying comments and links to useful resources.
  • automatically inserted description from README.md or an empty string if there is no README.md.

Here is the link to the repository. Fill free to enhance the solution.

Difference between innerText, innerHTML and value?

In simple words:

  1. innerText will show the value as is and ignores any HTML formatting which may be included.
  2. innerHTML will show the value and apply any HTML formatting.

"Failed to load platform plugin "xcb" " while launching qt5 app on linux without qt installed

I had this problem, and on a hunch I removed the Qt Configs from my environment. I.e.,

rm -rf ~/.config/Qt*

Then I started qtcreator and it reconfigured itself with the existing state of the machine. It no longer remembered where my projects were, but that just meant I had to browse to them "for the first time" again.

But more importantly it built itself a coherent set of library paths, so I could rebuild and run my project executables again without the xcb or qxcb libraries going missing.

Make file echo displaying "$PATH" string

The make uses the $ for its own variable expansions. E.g. single character variable $A or variable with a long name - ${VAR} and $(VAR).

To put the $ into a command, use the $$, for example:

all:
  @echo "Please execute next commands:"
  @echo 'setenv PATH /usr/local/greenhills/mips5/linux86:$$PATH'

Also note that to make the "" and '' (double and single quoting) do not play any role and they are passed verbatim to the shell. (Remove the @ sign to see what make sends to shell.) To prevent the shell from expanding $PATH, second line uses the ''.

Ruby: How to iterate over a range, but in set increments?

See http://ruby-doc.org/core/classes/Range.html#M000695 for the full API.

Basically you use the step() method. For example:

(10..100).step(10) do |n|
    # n = 10
    # n = 20
    # n = 30
    # ...
end

Drawable image on a canvas

also you can use this way. it will change your big drawble fit to your canvas:

Resources res = getResources();
Bitmap bitmap = BitmapFactory.decodeResource(res, yourDrawable);
yourCanvas.drawBitmap(bitmap, 0, 0, yourPaint);

Bootstrap 3 Glyphicons are not working

IIS will not server .woff files by default, so in IIS you'll need to add a <mimeMap> entry to your web.config file;

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <staticContent>
            <mimeMap fileExtension=".woff" mimeType="application/x-woff" />
        </staticContent>
    </system.webServer>
</configuration>

How can I detect if Flash is installed and if not, display a hidden div that informs the user?

I used Adobe's detection kit, originally suggested by justpassinby. Their system is nice because it detects the version number and compares it for you against your 'required version'

One bad thing is it does an alert showing the detected version of flash, which isn't very user friendly. All of a sudden a box pops up with some seemingly random numbers.

Some modifications you might want to consider:

  • remove the alert
  • change it so it returns an object (or array) --- first element is boolean true/false for "was the required version found on user's machine" --- second element is the actual version number found on user's machine

is the + operator less performant than StringBuffer.append()

Agreed with Michael Haren.

Also consider the use of arrays and join if performance is indeed an issue.

var buffer = ["<a href='", url, "'>click here</a>"];
buffer.push("More stuff");
alert(buffer.join(""));

How do I declare a 2d array in C++ using new?

This question was bugging me - it's a common enough problem that a good solution should already exist, something better than the vector of vectors or rolling your own array indexing.

When something ought to exist in C++ but doesn't, the first place to look is boost.org. There I found the Boost Multidimensional Array Library, multi_array. It even includes a multi_array_ref class that can be used to wrap your own one-dimensional array buffer.

Create an enum with string values

There a lot of answers, but I don't see any complete solutions. The problem with the accepted answer, as well as enum { this, one }, is that it disperses the string value you happen to be using through many files. I don't really like the "update" either, it's complex and doesn't leverage types as well. I think Michael Bromley's answer is most correct, but it's interface is a bit of a hassle and could do with a type.

I am using TypeScript 2.0.+ ... Here's what I would do

export type Greeting = "hello" | "world";
export const Greeting : { hello: Greeting , world: Greeting } = {
    hello: "hello",
    world: "world"
};

Then use like this:

let greet: Greeting = Greeting.hello

It also has much nicer type / hover-over information when using a helpful IDE. The draw back is you have to write the strings twice, but at least it's only in two places.

How to combine GROUP BY and ROW_NUMBER?

The deduplication (to select the max T1) and the aggregation need to be done as distinct steps. I've used a CTE since I think this makes it clearer:

;WITH sumCTE
AS
(
    SELECT  Rel.t2ID, SUM(Price) price
    FROM    @t1         AS T1
    JOIN    @relation   AS Rel 
    ON      Rel.t1ID=T1.ID
    GROUP 
    BY      Rel.t2ID
)
,maxCTE
AS
(
    SELECT  Rel.t2ID, Rel.t1ID, 
            ROW_NUMBER()OVER(Partition By Rel.t2ID Order By Price DESC)As PriceList
    FROM    @t1         AS T1
    JOIN    @relation   AS Rel 
    ON      Rel.t1ID=T1.ID
)
SELECT T2.ID AS T2ID
,T2.Name as T2Name
,T2.Orders
,T1.ID AS T1ID
,T1.Name As T1Name
,sumT1.Price
FROM    @t2 AS T2
JOIN    sumCTE AS sumT1
ON      sumT1.t2ID = t2.ID
JOIN    maxCTE AS maxT1
ON      maxT1.t2ID = t2.ID
JOIN    @t1 AS T1
ON      T1.ID = maxT1.t1ID
WHERE   maxT1.PriceList = 1

How to make a edittext box in a dialog

Wasim's answer lead me in the right direction but I had to make some changes to get it working for my current project. I am using this function in a fragment and calling it on button click.

fun showPostDialog(title: String) {
        val alert =  AlertDialog.Builder(activity)

        val edittext = EditText(activity)
        edittext.hint = "Enter Name"
        edittext.maxLines = 1

        var layout = activity?.let { FrameLayout(it) }

        //set padding in parent layout
//        layout.isPaddingRelative(45,15,45,0)
        layout?.setPadding(45,15,45,0)

        alert.setTitle(title)

        layout?.addView(edittext)

        alert.setView(layout)

        alert.setPositiveButton(getString(R.string.label_save), DialogInterface.OnClickListener {

                dialog, which ->
            run {

                val qName = edittext.text.toString()

                showToast("Posted to leaderboard successfully")

                view?.hideKeyboard()

            }

        })
        alert.setNegativeButton(getString(R.string.label_cancel), DialogInterface.OnClickListener {

                dialog, which ->
            run {
                dialog.dismiss()
            }

        })

        alert.show()
    }

    fun View.hideKeyboard() {
        val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(windowToken, 0)
    }

    fun showToast(message: String) {
        Toast.makeText(activity, message, Toast.LENGTH_LONG).show()
    }

I hope it helps someone else in the near future. Happy coding!

Left align and right align within div in Bootstrap

In Bootstrap 4 the correct answer is to use the text-xs-right class.

This works because xs denotes the smallest viewport size in BS. If you wanted to, you could apply the alignment only when the viewport is medium or larger by using text-md-right.

In the latest alpha, text-xs-right has been simplified to text-right.

<div class="row">
    <div class="col-md-6">Total cost</div>
    <div class="col-md-6 text-right">$42</div>
</div>

Counting the number of elements in array

Just use the length filter on the whole array. It works on more than just strings:

{{ notcount|length }}

Javascript to set hidden form value on drop down change

<form>
  <input type="hidden" name="selval">
  <select onchange="this.form.selval.value=this.selectedIndex">
    <option>val1</option>
    <option>val2</option>
  </select>
</form>

pure javascript from within a form

REST API 404: Bad URI, or Missing Resource?

For this scenario HTTP 404 is response code for the response from the REST API Like 400, 401, 404 , 422 unprocessable entity

use the Exception handling to check the full exception message.

try{
  // call the rest api
} catch(RestClientException e) {
     //process exception
     if(e instanceof HttpStatusCodeException){
        String responseText=((HttpStatusCodeException)e).getResponseBodyAsString();
         //now you have the response, construct json from it, and extract the errors
         System.out.println("Exception :" +responseText);
     }

}

This exception block give you the proper message thrown by the REST API

Permission denied (publickey) when SSH Access to Amazon EC2 instance

You need to do the following steps:

  1. Open your ssh client or terminal if you are using Linux.
  2. Locate your private key file and change your directory.
    cd <path to your .pem file>
  3. Execute below commands:
    chmod 400 <filename>.pem
    ssh -i <filename>.pem ubuntu@<ipaddress.com>

If ubuntu user is not working then try with ec2-user.

how we add or remove readonly attribute from textbox on clicking radion button in cakephp using jquery?

You could use prop as well. Check the following code below.

$(document).ready(function(){

   $('.staff_on_site').click(function(){

     var rBtnVal = $(this).val();

     if(rBtnVal == "yes"){
         $("#no_of_staff").prop("readonly", false); 
     }
     else{ 
         $("#no_of_staff").prop("readonly", true); 
     }
   });
});

Filter spark DataFrame on string contains

In pyspark,SparkSql syntax:

where column_n like 'xyz%'

might not work.

Use:

where column_n RLIKE '^xyz' 

This works perfectly fine.

How to download Google Play Services in an Android emulator?

This is how you make Android Google Maps API v2 work on your emulator.


Create a new emulator

  • for device choose "5.1'' WVGA (480 x 800: mdpi)"
  • for target choose "Android 4.1.2 - API level 16"
  • for "CPU/ABI" choose "ARM"
  • leave rest to defaults

these are the settings that are working for me. I don't know for different ones.


Start the emulator


install com.android.vending-1.apk and com.google.android.gms-1.apk via ADB install command


The longer answer is on my blog post about this issue https://medium.com/nemanja-kovacevic/how-to-make-android-google-maps-v2-work-in-android-emulator-e384f5423723

How to make ng-repeat filter out duplicate results

I had an array of strings, not objects and i used this approach:

ng-repeat="name in names | unique"

with this filter:

angular.module('app').filter('unique', unique);
function unique(){
return function(arry){
        Array.prototype.getUnique = function(){
        var u = {}, a = [];
        for(var i = 0, l = this.length; i < l; ++i){
           if(u.hasOwnProperty(this[i])) {
              continue;
           }
           a.push(this[i]);
           u[this[i]] = 1;
        }
        return a;
    };
    if(arry === undefined || arry.length === 0){
          return '';
    }
    else {
         return arry.getUnique(); 
    }

  };
}

Why does flexbox stretch my image rather than retaining aspect ratio?

I faced the same issue with a Foundation menu. align-self: center; didn't work for me.

My solution was to wrap the image with a <div style="display: inline-table;">...</div>

Is there a 'foreach' function in Python 3?

Other examples:

Python Foreach Loop:

array = ['a', 'b']
for value in array:
    print(value)
    # a
    # b

Python For Loop:

array = ['a', 'b']
for index in range(len(array)):
    print("index: %s | value: %s" % (index, array[index]))
    # index: 0 | value: a
    # index: 1 | value: b

ERROR Source option 1.5 is no longer supported. Use 1.6 or later

Make sure you have following configuration in your pom.xml file.

<properties>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
</properties>

Bootstrap full responsive navbar with logo or brand name text

The placeholder image you're including has a height of 50px. It is wrapped in an anchor (.navbar-brand) with a padding-top of 15px and a height of 50px. That's why the placeholder logo flows out of the bar. Try including a smaller image or play with the anchor's padding by assigning a class or an id to it wich you can reference in your css.

EDIT Or remove the static height: 50px from .navbar-brand. Your navbar will then take the height of its highest child.

h3 in bootstrap by default has a padding-top of 20px. Again, it is wrapped with that padding-top: 15px anchor. That's why it's not vertically centered like you want it. You could give the h3 a class or and id that resets the margin-top. And the same you could do with the padding of the anchor.

Here's something to play with: http://jsbin.com/jelec/1/edit?html,output

Check whether a cell contains a substring

For those who would like to do this using a single function inside the IF statement, I use

=IF(COUNTIF(A1,"*TEXT*"),TrueValue,FalseValue)

to see if the substring TEXT is in cell A1

[NOTE: TEXT needs to have asterisks around it]

command/usr/bin/codesign failed with exit code 1- code sign error

I had the same error on January 2018 with xcode 8.2.1

Before I try to open xcode I couldn't because the system was updating. I tried sometime later and it let me working on it, and then I got the same error.

I followed most of the solutions described in this article but they didn't work for me.

Then I remembered the message about the system updating and I tried to reboot the machine.

And that did the magic. It worked for me.

R Markdown - changing font size and font type in html output

You can change the font size in R Markdown with HTML code tags <font size="1"> your text </font> . This code is added to the R Markdown document and will alter the output of the HTML output.

For example:

_x000D_
_x000D_
 <font size="1"> This is my text number1</font> _x000D_
_x000D_
 <font size="2"> This is my text number 2 </font>_x000D_
 _x000D_
 <font size="3"> This is my text number 3</font> _x000D_
 _x000D_
 <font size="4"> This is my text number 4</font> _x000D_
 _x000D_
 <font size="5"> This is my text number 5</font> _x000D_
 _x000D_
 <font size="6"> This is my text number 6</font>
_x000D_
_x000D_
_x000D_

How to add a button dynamically in Android?

Try following code.

LinearLayout layout = (LinearLayout) findViewById(R.id.llayout); 
layout.setOrientation(LinearLayout.VERTICAL);

Button btn = new Button(this);
btn.setText("Button1");

layout.add(btn);

btn = new Button(this);
btn.setText(Button2);
layout.add(btn);

like this you add Buttons as per your requirements.

Access index of last element in data frame

It may be too late now, I use index method to retrieve last index of a DataFrame, then use [-1] to get the last values:

For example,

df = pd.DataFrame(np.zeros((4, 1)), columns=['A'])
print(f'df:\n{df}\n')

print(f'Index = {df.index}\n')
print(f'Last index = {df.index[-1]}')

The output is

df:
     A
0  0.0
1  0.0
2  0.0
3  0.0

Index = RangeIndex(start=0, stop=4, step=1)

Last index = 3

How do I reference tables in Excel using VBA?

Converting a range to a table as described in this answer:

Sub CreateTable()
    ActiveSheet.ListObjects.Add(xlSrcRange, Range("$B$1:$D$16"), , xlYes).Name = _
        "Table1"
        'No go in 2003
    ActiveSheet.ListObjects("Table1").TableStyle = "TableStyleLight2"
End Sub

Resize command prompt through commands

If you want to run a .bat file in full screen, right click on the "example.bat" and click create shortcut, then right click on the shortcut and click properties, then click layout, in layout you can adjust your file to the screen manually, however you can only run it this way if you use the shortcut. You can also change font size by clicking font instead of layout, select lucida and adjust the font size then click apply

Oracle PL/SQL : remove "space characters" from a string

To replace one or more white space characters by a single blank you should use {2,} instead of *, otherwise you would insert a blank between all non-blank characters.

REGEXP_REPLACE( my_value, '[[:space:]]{2,}', ' ' )

What is the proper way to display the full InnerException?

If you want information about all exceptions then use exception.ToString(). It will collect data from all inner exceptions.

If you want only the original exception then use exception.GetBaseException().ToString(). This will get you the first exception, e.g. the deepest inner exception or the current exception if there is no inner exception.

Example:

try {
    Exception ex1 = new Exception( "Original" );
    Exception ex2 = new Exception( "Second", ex1 );
    Exception ex3 = new Exception( "Third", ex2 );
    throw ex3;
} catch( Exception ex ) {
    // ex => ex3
    Exception baseEx = ex.GetBaseException(); // => ex1
}

Greater than less than, python

Check to make sure that both score and array[x] are numerical types. You might be comparing an integer to a string...which is heartbreakingly possible in Python 2.x.

>>> 2 < "2"
True
>>> 2 > "2"
False
>>> 2 == "2"
False

Edit

Further explanation: How does Python compare string and int?

How to darken an image on mouseover?

Create black png with lets say 50% transparency. Overlay this on mouseover.

NUnit Unit tests not showing in Test Explorer with Test Adapter installed

My test assembly is 64-bit. From the menu bar at the top of visual studio 2012, I was able to select 'Test' -> 'Test Settings' -> 'Default Processor Architecture' -> 'X64'. After a 'Rebuild Solution' from the 'Build' menu, I was able to see all of my tests in test explorer. Hopefully this helps someone else in the future =D.

URL string format for connecting to Oracle database with JDBC

There are two ways to set this up. If you have an SID, use this (older) format:

jdbc:oracle:thin:@[HOST][:PORT]:SID

If you have an Oracle service name, use this (newer) format:

jdbc:oracle:thin:@//[HOST][:PORT]/SERVICE

Source: this OraFAQ page

The call to getConnection() is correct.

Also, as duffymo said, make sure the actual driver code is present by including ojdbc6.jar in the classpath, where the number corresponds to the Java version you're using.

Bootstrap 3 modal responsive

I had the same issue I have resolved by adding a media query for @screen-xs-min in less version under Modals.less

@media (max-width: @screen-xs-min) {
  .modal-xs { width: @modal-sm; }
}

cannot load such file -- bundler/setup (LoadError)

Bundler Version maybe cause the issue.

Please install bundler with other version number.

For example,

gem install bundler -v 1.0.10

Finding out current index in EACH loop (Ruby)

X.each_with_index do |item, index|
  puts "current_index: #{index}"
end

Chrome:The website uses HSTS. Network errors...this page will probably work later

When you visited https://localhost previously at some point it not only visited this over a secure channel (https rather than http), it also told your browser, using a special HTTP header: Strict-Transport-Security (often abbreviated to HSTS), that it should ONLY use https for all future visits.

This is a security feature web servers can use to prevent people being downgraded to http (either intentionally or by some evil party).

However if you then then turn off your https server, and just want to browse http you can't (by design - that's the point of this security feature).

HSTS also does prevents you from accepting and skipping past certificate errors.

To reset this, so HSTS is no longer set for localhost, type the following in your Chrome address bar:

chrome://net-internals/#hsts

Where you will be able to delete this setting for "localhost".

You might also want to find out what was setting this to avoid this problem in future!

Note that for other sites (e.g. www.google.com) these are "preloaded" into the Chrome code and so cannot be removed. When you query them at chrome://net-internals/#hsts you will see them listed as static HSTS entries.

And finally note that Google has started preloading HSTS for the entire .dev domain: https://ma.ttias.be/chrome-force-dev-domains-https-via-preloaded-hsts/

Bootstrap table striped: How do I change the stripe background colour?

I came across this post while hunting down a solution for myself. By using chrome's inspector, I was able to determine that the striped color was being applied from the --bs-table-striped-color tag.

overriding that tag in your css:

<style scoped>
table {
--bs-table-striped-color: #85d1ee;
}
</style>

PHP GuzzleHttp. How to make a post request with params?

Try this

$client = new \GuzzleHttp\Client();
$client->post(
    'http://www.example.com/user/create',
    array(
        'form_params' => array(
            'email' => '[email protected]',
            'name' => 'Test user',
            'password' => 'testpassword'
        )
    )
);

How do I use a Boolean in Python?

Booleans in python are subclass of integer. Constructor of booleans is bool. bool class inherits from int class.

 issubclass(bool,int) // will return True
 isinstance(True,bool) , isinstance(False,bool) //they both True

True and False are singleton objects. they will retain same memory address throughout the lifetime of your app. When you type True, python memory manager will check its address and will pull the value '1'. for False its value is '0'.

Comparisons of any boolean expression to True or False can be performed using either is (identity) or == (equality) operator.

int(True) == 1
int(False) == 0

But note that True and '1' are not the same objects. You can check:

 id(True) == id(1) // will return False

you can also easily see that

  True > False // returns true cause 1>0

any integer operation can work with the booleans.

  True + True + True =3 

All objects in python have an associated truth value. Every object has True value except:

  • None

  • False

  • 0 in any numeric type (0,0.0,0+0j etc)

  • empty sequences (list, tuple, string)

  • empty mapping types (dictionary, set, etc)

  • custom classes that implement __bool__ or __len__ method that returns False or 0.

every class in python has truth values defined by a special instance method:

 __bool__(self)   OR
 __len__

When you call bool(x) python will actually execute

 x.__bool__() 

if instance x does not have this method, then it will execute

 x.__len__()

if this does not exist, by default value is True.

For Example for int class we can define bool as below:

  def __bool__(self):
      return self != 0

for bool(100), 100 !=0 will return True. So

bool(100) == True

you can easily check that bool(0) will be False. with this for instances of int class only 0 will return False.

another example= bool([1,2,3])

[1,2,3] has no __bool__() method defined but it has __len__() and since its length is greater than 0, it will return True. Now you can see why empty lists return False.

Notice: Array to string conversion in

Even simpler:

$get = @mysql_query("SELECT money FROM players WHERE username = '" . $_SESSION['username'] . "'");

note the quotes around username in the $_SESSION reference.

Python: printing a file to stdout

Sure. Assuming you have a string with the file's name called fname, the following does the trick.

with open(fname, 'r') as fin:
    print(fin.read())

Check if array is empty or null

You should check for '' (empty string) before pushing into your array. Your array has elements that are empty strings. Then your album_text.length === 0 will work just fine.

Tree data structure in C#

Yet another tree structure:

public class TreeNode<T> : IEnumerable<TreeNode<T>>
{

    public T Data { get; set; }
    public TreeNode<T> Parent { get; set; }
    public ICollection<TreeNode<T>> Children { get; set; }

    public TreeNode(T data)
    {
        this.Data = data;
        this.Children = new LinkedList<TreeNode<T>>();
    }

    public TreeNode<T> AddChild(T child)
    {
        TreeNode<T> childNode = new TreeNode<T>(child) { Parent = this };
        this.Children.Add(childNode);
        return childNode;
    }

    ... // for iterator details see below link
}

Sample usage:

TreeNode<string> root = new TreeNode<string>("root");
{
    TreeNode<string> node0 = root.AddChild("node0");
    TreeNode<string> node1 = root.AddChild("node1");
    TreeNode<string> node2 = root.AddChild("node2");
    {
        TreeNode<string> node20 = node2.AddChild(null);
        TreeNode<string> node21 = node2.AddChild("node21");
        {
            TreeNode<string> node210 = node21.AddChild("node210");
            TreeNode<string> node211 = node21.AddChild("node211");
        }
    }
    TreeNode<string> node3 = root.AddChild("node3");
    {
        TreeNode<string> node30 = node3.AddChild("node30");
    }
}

BONUS
See fully-fledged tree with:

  • iterator
  • searching
  • Java/C#

https://github.com/gt4dev/yet-another-tree-structure

How do I list all tables in a schema in Oracle SQL?

Name of the table and rows counter for all tables under OWNER schema:

SELECT table_name, num_rows counter from DBA_TABLES WHERE owner = 'OWNER'

How do I exit the results of 'git diff' in Git Bash on windows?

Using WIN + Q worked for me. Just q alone gave me "command not found" and eventually it jumped back into the git diff insanity.

Syntax for a single-line Bash infinite while loop

If you want the while loop to stop after some condition, and your foo command returns non-zero when this condition is met then you can get the loop to break like this:

while foo; do echo 'sleeping...'; sleep 5; done;

For example, if the foo command is deleting things in batches, and it returns 1 when there is nothing left to delete.

This works well if you have a custom script that needs to run a command many times until some condition. You write the script to exit with 1 when the condition is met and exit with 0 when it should be run again.

For example, say you have a python script batch_update.py which updates 100 rows in a database and returns 0 if there are more to update and 1 if there are no more. The the following command will allow you to update rows 100 at a time with sleeping for 5 seconds between updates:

while batch_update.py; do echo 'sleeping...'; sleep 5; done;

"An attempt was made to load a program with an incorrect format" even when the platforms are the same

In my case, I am using a tiny .exe that reloads the referenced DLLs via Reflection. So I just do these steps which saves my day:

From project properties on solution explorer, at build tab, I choose target platfrom x86

Java : Cannot format given Object as a Date

public static String showDate(){
    SimpleDateFormat df=new SimpleDateFormat("\nTime:yyyy-MM-dd HH:mm:ss");
    System.out.println(df.format(new Date()));
    String s=df.format(new Date());
    return s;
}

I think this code may solve your problem.

MacOS Xcode CoreSimulator folder very big. Is it ok to delete content?

That directory is part of your user data and you can delete any user data without affecting Xcode seriously. You can delete the whole CoreSimulator/ directory. Xcode will recreate fresh instances there for you when you do your next simulator run. If you can afford losing any previous simulator data of your apps this is the easy way to get space.

Update: A related useful app is "DevCleaner for Xcode" https://apps.apple.com/app/devcleaner-for-xcode/id1388020431

How to create a date object from string in javascript

The syntax is as follows:

new Date(year, month [, day, hour, minute, second, millisecond ])

so

Date d = new Date(2011,10,30);

is correct; day, hour, minute, second, millisecond are optional.

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date

MacOSX homebrew mysql root password

This worked for me for MAC https://flipdazed.github.io/blog/osx%20maintenance/set-up-mysql-osx

Start mysql by running

brew services start mysql

Run the installation script

mysql_secure_installation

You will be asked to set up a setup VALIDATE PASSWORD plugin. Enter y to do this.

Select the required password validation (Doesn’t really matter if it is just you using the database)

Now select y for all the remaining options: Remove anon. users; disallow remote root logins; remove test database; reload privileges tables. Now you should receive a message of

All done!

How to run python script on terminal (ubuntu)?

This error:

python: can't open file 'test.py': [Errno 2] No such file or directory

Means that the file "test.py" doesn't exist. (Or, it does, but it isn't in the current working directory.)

I must save the file in any specific folder to make it run on terminal?

No, it can be where ever you want. However, if you just say, "test.py", you'll need to be in the directory containing test.py.

Your terminal (actually, the shell in the terminal) has a concept of "Current working directory", which is what directory (folder) it is currently "in".

Thus, if you type something like:

python test.py

test.py needs to be in the current working directory. In Linux, you can change the current working directory with cd. You might want a tutorial if you're new. (Note that the first hit on that search for me is this YouTube video. The author in the video is using a Mac, but both Mac and Linux use bash for a shell, so it should apply to you.)

HTML5 Canvas: Zooming

Just try this out:

<!DOCTYPE HTML>
<html>
    <head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
        <style>
            body {
                margin: 0px;
                padding: 0px;
            }

            #wrapper {
                position: relative;
                border: 1px solid #9C9898;
                width: 578px;
                height: 200px;
            }

            #buttonWrapper {
                position: absolute;
                width: 30px;
                top: 2px;
                right: 2px;
            }

            input[type =
            "button"] {
                padding: 5px;
                width: 30px;
                margin: 0px 0px 2px 0px;
            }
        </style>
        <script>
            function draw(scale, translatePos){
                var canvas = document.getElementById("myCanvas");
                var context = canvas.getContext("2d");

                // clear canvas
                context.clearRect(0, 0, canvas.width, canvas.height);

                context.save();
                context.translate(translatePos.x, translatePos.y);
                context.scale(scale, scale);
                context.beginPath(); // begin custom shape
                context.moveTo(-119, -20);
                context.bezierCurveTo(-159, 0, -159, 50, -59, 50);
                context.bezierCurveTo(-39, 80, 31, 80, 51, 50);
                context.bezierCurveTo(131, 50, 131, 20, 101, 0);
                context.bezierCurveTo(141, -60, 81, -70, 51, -50);
                context.bezierCurveTo(31, -95, -39, -80, -39, -50);
                context.bezierCurveTo(-89, -95, -139, -80, -119, -20);
                context.closePath(); // complete custom shape
                var grd = context.createLinearGradient(-59, -100, 81, 100);
                grd.addColorStop(0, "#8ED6FF"); // light blue
                grd.addColorStop(1, "#004CB3"); // dark blue
                context.fillStyle = grd;
                context.fill();

                context.lineWidth = 5;
                context.strokeStyle = "#0000ff";
                context.stroke();
                context.restore();
            }

            window.onload = function(){
                var canvas = document.getElementById("myCanvas");

                var translatePos = {
                    x: canvas.width / 2,
                    y: canvas.height / 2
                };

                var scale = 1.0;
                var scaleMultiplier = 0.8;
                var startDragOffset = {};
                var mouseDown = false;

                // add button event listeners
                document.getElementById("plus").addEventListener("click", function(){
                    scale /= scaleMultiplier;
                    draw(scale, translatePos);
                }, false);

                document.getElementById("minus").addEventListener("click", function(){
                    scale *= scaleMultiplier;
                    draw(scale, translatePos);
                }, false);

                // add event listeners to handle screen drag
                canvas.addEventListener("mousedown", function(evt){
                    mouseDown = true;
                    startDragOffset.x = evt.clientX - translatePos.x;
                    startDragOffset.y = evt.clientY - translatePos.y;
                });

                canvas.addEventListener("mouseup", function(evt){
                    mouseDown = false;
                });

                canvas.addEventListener("mouseover", function(evt){
                    mouseDown = false;
                });

                canvas.addEventListener("mouseout", function(evt){
                    mouseDown = false;
                });

                canvas.addEventListener("mousemove", function(evt){
                    if (mouseDown) {
                        translatePos.x = evt.clientX - startDragOffset.x;
                        translatePos.y = evt.clientY - startDragOffset.y;
                        draw(scale, translatePos);
                    }
                });

                draw(scale, translatePos);
            };



            jQuery(document).ready(function(){
               $("#wrapper").mouseover(function(e){
                  $('#status').html(e.pageX +', '+ e.pageY);
               }); 
            })  
        </script>
    </head>
    <body onmousedown="return false;">
        <div id="wrapper">
            <canvas id="myCanvas" width="578" height="200">
            </canvas>
            <div id="buttonWrapper">
                <input type="button" id="plus" value="+"><input type="button" id="minus" value="-">
            </div>
        </div>
        <h2 id="status">
        0, 0
        </h2>
    </body>
</html>

Works perfect for me with zooming and mouse movement.. you can customize it to mouse wheel up & down Njoy!!!

Here is fiddle for this Fiddle

SSL_connect: SSL_ERROR_SYSCALL in connection to github.com:443

Same problem here, it turned out to be my incorrectly configured proxy settings, here's how to check and remove them.

First open your git config file.

vi ~/.gitconfig

and find out whether the [http] or [https] sections are set.

I used to set proxies for git due to slow access to Github in China, however, lately I changed my local proxy ports but I forgot my git settings.

If you have incorrect proxy settings and decide to remove it, simply execute:

git config --global --unset http.proxy
git config --global --unset https.proxy

Things will work just fine.

Generating statistics from Git repository

Beside GitStats (git history statistics generator) mentioned by xyld, written in Python and requiring Gnuplot for graphs, there is also

Getting the client's time zone (and offset) in JavaScript

function getLocalTimeZone() {
    var dd = new Date();
    var ddStr = dd.toString();
    var ddArr = ddStr.split(' ');
    var tmznSTr = ddArr[5];
    tmznSTr = tmznSTr.substring(3, tmznSTr.length);
    return tmznSTr;
}

Example : Thu Jun 21 2018 18:12:50 GMT+0530 (India Standard Time)

O/P : +0530

How do I center text horizontally and vertically in a TextView?

Use this for relative layout

android:layout_centerInParent="true"

and for other layout

android:gravity="center" 

How do you determine the size of a file in C?

If you're fine with using the std c library:

#include <sys/stat.h>
off_t fsize(char *file) {
    struct stat filestat;
    if (stat(file, &filestat) == 0) {
        return filestat.st_size;
    }
    return 0;
}

Delegates in swift?

DELEGATES IN SWIFT 2

I am explaining with example of Delegate with two viewControllers.In this case, SecondVC Object is sending data back to first View Controller.

Class with Protocol Declaration

protocol  getDataDelegate  {
    func getDataFromAnotherVC(temp: String)
}


import UIKit
class SecondVC: UIViewController {

    var delegateCustom : getDataDelegate?
    override func viewDidLoad() {
        super.viewDidLoad()
     }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    @IBAction func backToMainVC(sender: AnyObject) {
      //calling method defined in first View Controller with Object  
      self.delegateCustom?.getDataFromAnotherVC(temp: "I am sending data from second controller to first view controller.Its my first delegate example. I am done with custom delegates.")
        self.navigationController?.popViewControllerAnimated(true)
    }
    
}

In First ViewController Protocol conforming is done here:

class ViewController: UIViewController, getDataDelegate

Protocol method definition in First View Controller(ViewController)

func getDataFromAnotherVC(temp : String)
{
  // dataString from SecondVC
   lblForData.text = dataString
}

During push the SecondVC from First View Controller (ViewController)

let objectPush = SecondVC()
objectPush.delegateCustom = self
self.navigationController.pushViewController(objectPush, animated: true)

How to fix a locale setting warning from Perl

Following the accepted answer:

LANG=C ssh hunter2.

LC_ALL=C ssh hunter2

on the client side did the trick for me.

What is memoization and how can I use it in Python?

The other answers cover what it is quite well. I'm not repeating that. Just some points that might be useful to you.

Usually, memoisation is an operation you can apply on any function that computes something (expensive) and returns a value. Because of this, it's often implemented as a decorator. The implementation is straightforward and it would be something like this

memoised_function = memoise(actual_function)

or expressed as a decorator

@memoise
def actual_function(arg1, arg2):
   #body

Left align block of equations

Try this:

\begin{flalign*}
    &|\vec a| = \sqrt{3^{2}+1^{2}} = \sqrt{10} & \\
    &|\vec b| = \sqrt{1^{2}+23^{2}} = \sqrt{530} &\\ 
    &\cos v = \frac{26}{\sqrt{10} \cdot \sqrt{530}} &\\
    &v = \cos^{-1} \left(\frac{26}{\sqrt{10} \cdot \sqrt{530}}\right) &\\
\end{flalign*}

The & sign separates two columns, so an & at the beginning of a line means that the line starts with a blank column.

List file names based on a filename pattern and file content?

find /folder -type f -mtime -90 | grep -E "(.txt|.php|.inc|.root|.gif)" | xargs ls -l > WWWlastActivity.log

Undefined symbols for architecture i386

A bit late to the party but might be valuable to someone with this error..

I just straight copied a bunch of files into an Xcode project, if you forget to add them to your projects Build Phases you will get the error "Undefined symbols for architecture i386". So add your implementation files to Compile Sources, and Xib files to Copy Bundle Resources.

The error was telling me that there was no link to my classes simply because they weren't included in the Compile Sources, quite obvious really but may save someone a headache.

How to drop SQL default constraint without knowing its name?

Useful for some columns that had multiple default constraints or check constraints created:

Modified https://stackoverflow.com/a/16359095/206730 script

Note: this script is for sys.check_constraints

declare @table_name nvarchar(128)
declare @column_name nvarchar(128)
declare @constraint_name nvarchar(128)
declare @constraint_definition nvarchar(512)

declare @df_name nvarchar(128)
declare @cmd nvarchar(128) 

PRINT 'DROP CONSTRAINT [Roles2016.UsersCRM].Estado'

declare constraints cursor for 
 select t.name TableName, c.name ColumnName, d.name ConstraintName, d.definition ConstraintDefinition
 from sys.tables t   
 join sys.check_constraints d  on d.parent_object_id = t.object_id  
 join sys.columns c  on c.object_id = t.object_id      
 and c.column_id = d.parent_column_id
 where t.name = N'Roles2016.UsersCRM' and c.name = N'Estado'

open constraints
fetch next from constraints into @table_name , @column_name, @constraint_name, @constraint_definition
while @@fetch_status = 0
BEGIN
    print 'CONSTRAINT: ' + @constraint_name
    select @cmd = 'ALTER TABLE [' + @table_name +  '] DROP CONSTRAINT [' +  @constraint_name + ']'
    print @cmd
    EXEC sp_executeSQL @cmd;

  fetch next from constraints into @table_name , @column_name, @constraint_name, @constraint_definition
END

close constraints 
deallocate constraints

Is there a way to specify which pytest tests to run from a file?

My answer provides a ways to run a subset of test in different scenarios.

Run all tests in a project

pytest

Run tests in a Single Directory

To run all the tests from one directory, use the directory as a parameter to pytest:

pytest tests/my-directory

Run tests in a Single Test File/Module

To run a file full of tests, list the file with the relative path as a parameter to pytest:

pytest tests/my-directory/test_demo.py

Run a Single Test Function

To run a single test function, add :: and the test function name:

pytest -v tests/my-directory/test_demo.py::test_specific_function

-v is used so you can see which function was run.

Run a Single Test Class

To run just a class, do like we did with functions and add ::, then the class name to the file parameter:

pytest -v tests/my-directory/test_demo.py::TestClassName

Run a Single Test Method of a Test Class

If you don't want to run all of a test class, just one method, just add another :: and the method name:

pytest -v tests/my-directory/test_demo.py::TestClassName::test_specific_method

Run a Set of Tests Based on Test Name

The -k option enables you to pass in an expression to run tests that have certain names specified by the expression as a substring of the test name. It is possible to use and, or, and not to create complex expressions.

For example, to run all of the functions that have _raises in their name:

pytest -v -k _raises

Writing/outputting HTML strings unescaped

Apart from using @MvcHtmlString.Create(ViewBag.Stuff) as suggested by Dommer, I suggest you to also use AntiXSS library as suggested phill http://haacked.com/archive/2010/04/06/using-antixss-as-the-default-encoder-for-asp-net.aspx

It encodes almost all the possible XSS attack string.

Adding new column to existing DataFrame in Python pandas

If the column you are trying to add is a series variable then just :

df["new_columns_name"]=series_variable_name #this will do it for you

This works well even if you are replacing an existing column.just type the new_columns_name same as the column you want to replace.It will just overwrite the existing column data with the new series data.

How to reduce the image file size using PIL

The main image manager in PIL is PIL's Image module.

from PIL import Image
import math

foo = Image.open("path\\to\\image.jpg")
x, y = foo.size
x2, y2 = math.floor(x-50), math.floor(y-20)
foo = foo.resize((x2,y2),Image.ANTIALIAS)
foo.save("path\\to\\save\\image_scaled.jpg",quality=95)

You can add optimize=True to the arguments of you want to decrease the size even more, but optimize only works for JPEG's and PNG's. For other image extensions, you could decrease the quality of the new saved image. You could change the size of the new image by just deleting a bit of code and defining the image size and you can only figure out how to do this if you look at the code carefully. I defined this size:

x, y = foo.size
x2, y2 = math.floor(x-50), math.floor(y-20)

just to show you what is (almost) normally done with horizontal images. For vertical images you might do:

x, y = foo.size
x2, y2 = math.floor(x-20), math.floor(y-50)

. Remember, you can still delete that bit of code and define a new size.

How can I calculate the number of lines changed between two commits in Git?

You want the --stat option of git diff, or if you're looking to parse this in a script, the --numstat option.

git diff --stat <commit-ish> <commit-ish>

--stat produces the human-readable output you're used to seeing after merges; --numstat produces a nice table layout that scripts can easily interpret.

I somehow missed that you were looking to do this on multiple commits at the same time - that's a task for git log. Ron DeVera touches on this, but you can actually do a lot more than what he mentions. Since git log internally calls the diff machinery in order to print requested information, you can give it any of the diff stat options - not just --shortstat. What you likely want to use is:

git log --author="Your name" --stat <commit1>..<commit2>

but you can use --numstat or --shortstat as well. git log can also select commits in a variety other ways - have a look at the documentation. You might be interested in things like --since (rather than specifying commit ranges, just select commits since last week) and --no-merges (merge commits don't actually introduce changes), as well as the pretty output options (--pretty=oneline, short, medium, full...).

Here's a one-liner to get total changes instead of per-commit changes from git log (change the commit selection options as desired - this is commits by you, from commit1 to commit2):

git log --numstat --pretty="%H" --author="Your Name" commit1..commit2 | awk 'NF==3 {plus+=$1; minus+=$2} END {printf("+%d, -%d\n", plus, minus)}'

(you have to let git log print some identifying information about the commit; I arbitrarily chose the hash, then used awk to only pick out the lines with three fields, which are the ones with the stat information)

What do *args and **kwargs mean?

Putting *args and/or **kwargs as the last items in your function definition’s argument list allows that function to accept an arbitrary number of arguments and/or keyword arguments.

For example, if you wanted to write a function that returned the sum of all its arguments, no matter how many you supply, you could write it like this:

def my_sum(*args):
    return sum(args)

It’s probably more commonly used in object-oriented programming, when you’re overriding a function, and want to call the original function with whatever arguments the user passes in.

You don’t actually have to call them args and kwargs, that’s just a convention. It’s the * and ** that do the magic.

The official Python documentation has a more in-depth look.

Change text from "Submit" on input tag

<input name="submitBnt" type="submit" value="like"/>

name is useful when using $_POST in php and also in javascript as document.getElementByName('submitBnt'). Also you can use name as a CS selector like input[name="submitBnt"]; Hope this helps

How do you follow an HTTP Redirect in Node.js?

Possibly a little bit of a necromancing post here, but...

here's a function that follows up to 10 redirects, and detects infinite redirect loops. also parses result into JSON

Note - uses a callback helper (shown at the end of this post)

( TLDR; full working demo in context here or remixed-version here)

function getJSON(url,cb){

    var callback=errBack(cb);
    //var callback=errBack(cb,undefined,false);//replace previous line with this to turn off logging

    if (typeof url!=='string') {
        return callback.error("getJSON:expecting url as string");
    }

    if (typeof cb!=='function') {
        return callback.error("getJSON:expecting cb as function");
    }

    var redirs = [url],
    fetch = function(u){
        callback.info("hitting:"+u);
        https.get(u, function(res){
            var body = [];
            callback.info({statusCode:res.statusCode});
            if ([301,302].indexOf(res.statusCode)>=0) {
                if (redirs.length>10) {
                    return callback.error("excessive 301/302 redirects detected");
                } else {
                    if (redirs.indexOf(res.headers.location)<0) {
                        redirs.push(res.headers.location);
                        return fetch(res.headers.location);
                    } else {
                        return callback.error("301/302 redirect loop detected");
                    }
                }
            } else {
              res.on('data', function(chunk){
                  body.push(chunk);
                  callback.info({onData:{chunkSize:chunk.length,chunks:body.length}});
              });
              res.on('end', function(){
                  try {
                      // convert to a single buffer
                      var json = Buffer.concat(body);
                      console.info({onEnd:{chunks:body.length,bodyLength:body.length}});

                      // parse the buffer as json
                      return callback.result(JSON.parse(json),json);
                  } catch (err) {

                      console.error("exception in getJSON.fetch:",err.message||err);

                      if (json.length>32) {
                        console.error("json==>|"+json.toString('utf-8').substr(0,32)+"|<=== ... (+"+(json.length-32)+" more bytes of json)");
                      } else {
                          console.error("json==>|"+json.toString('utf-8')+"|<=== json");
                      }

                      return callback.error(err,undefined,json);
                  }
              });
            }
        });
    };
    fetch(url);   
}

Note - uses a callback helper (shown below)

you can paste this into the node console and it should run as is.

( or for full working demo in context see here )

var 

fs      = require('fs'),
https   = require('https');

function errBack (cb,THIS,logger) {

   var 
   self,
   EB=function(fn,r,e){
       if (logger===false) {
           fn.log=fn.info=fn.warn=fn.errlog=function(){};       
       } else {
           fn.log        = logger?logger.log   : console.log.bind(console);
           fn.info       = logger?logger.info  : console.info.bind(console);
           fn.warn       = logger?logger.warn  : console.warn.bind(console);
           fn.errlog     = logger?logger.error : console.error.bind(console);
       }
       fn.result=r;
       fn.error=e;
       return (self=fn);
   };


   if (typeof cb==='function') {
       return EB(

            logger===false // optimization when not logging - don't log errors
            ?   function(err){
                   if (err) {
                      cb (err);
                     return true;
                   }
                   return false;
               }

            :  function(err){
                   if (err) {
                      self.errlog(err);
                      cb (err);
                     return true;
                   }
                   return false;
               },

           function () {
               return cb.apply (THIS,Array.prototype.concat.apply([undefined],arguments));
           },
           function (err) {
               return cb.apply (THIS,Array.prototype.concat.apply([typeof err==='string'?new Error(err):err],arguments));
           }
       );
   } else {

       return EB(

           function(err){
               if (err) {
                   if (typeof err ==='object' && err instanceof Error) {
                       throw err;
                   } else {
                       throw new Error(err);
                   }
                   return true;//redundant due to throw, but anyway.
               }
               return false;
           },

           logger===false
              ? self.log //optimization :resolves to noop when logger==false
              : function () {
                   self.info("ignoring returned arguments:",Array.prototype.concat.apply([],arguments));
           },

           function (err) {
               throw typeof err==='string'?new Error(err):err;
           }
       );
   }
}

function getJSON(url,cb){

    var callback=errBack(cb);

    if (typeof url!=='string') {
        return callback.error("getJSON:expecting url as string");
    }

    if (typeof cb!=='function') {
        return callback.error("getJSON:expecting cb as function");
    }

    var redirs = [url],
    fetch = function(u){
        callback.info("hitting:"+u);
        https.get(u, function(res){
            var body = [];
            callback.info({statusCode:res.statusCode});
            if ([301,302].indexOf(res.statusCode)>=0) {
                if (redirs.length>10) {
                    return callback.error("excessive 302 redirects detected");
                } else {
                    if (redirs.indexOf(res.headers.location)<0) {
                        redirs.push(res.headers.location);
                        return fetch(res.headers.location);
                    } else {
                        return callback.error("302 redirect loop detected");
                    }
                }
            } else {
              res.on('data', function(chunk){
                  body.push(chunk);
                  console.info({onData:{chunkSize:chunk.length,chunks:body.length}});
              });
              res.on('end', function(){
                  try {
                      // convert to a single buffer
                      var json = Buffer.concat(body);
                      callback.info({onEnd:{chunks:body.length,bodyLength:body.length}});

                      // parse the buffer as json
                      return callback.result(JSON.parse(json),json);
                  } catch (err) {
                      // read with "bypass refetch" option
                      console.error("exception in getJSON.fetch:",err.message||err);

                      if (json.length>32) {
                        console.error("json==>|"+json.toString('utf-8').substr(0,32)+"|<=== ... (+"+(json.length-32)+" more bytes of json)");
                      } else {
                          console.error("json==>|"+json.toString('utf-8')+"|<=== json");
                      }

                      return callback.error(err,undefined,json);
                  }
              });
            }
        });
    };
    fetch(url);   
}

var TLDs,TLDs_fallback = "com.org.tech.net.biz.info.code.ac.ad.ae.af.ag.ai.al.am.ao.aq.ar.as.at.au.aw.ax.az.ba.bb.bd.be.bf.bg.bh.bi.bj.bm.bn.bo.br.bs.bt.bv.bw.by.bz.ca.cc.cd.cf.cg.ch.ci.ck.cl.cm.cn.co.cr.cu.cv.cw.cx.cy.cz.de.dj.dk.dm.do.dz.ec.ee.eg.er.es.et.eu.fi.fj.fk.fm.fo.fr.ga.gb.gd.ge.gf.gg.gh.gi.gl.gm.gn.gp.gq.gr.gs.gt.gu.gw.gy.hk.hm.hn.hr.ht.hu.id.ie.il.im.in.io.iq.ir.is.it.je.jm.jo.jp.ke.kg.kh.ki.km.kn.kp.kr.kw.ky.kz.la.lb.lc.li.lk.lr.ls.lt.lu.lv.ly.ma.mc.md.me.mg.mh.mk.ml.mm.mn.mo.mp.mq.mr.ms.mt.mu.mv.mw.mx.my.mz.na.nc.ne.nf.ng.ni.nl.no.np.nr.nu.nz.om.pa.pe.pf.pg.ph.pk.pl.pm.pn.pr.ps.pt.pw.py.qa.re.ro.rs.ru.rw.sa.sb.sc.sd.se.sg.sh.si.sj.sk.sl.sm.sn.so.sr.st.su.sv.sx.sy.sz.tc.td.tf.tg.th.tj.tk.tl.tm.tn.to.tr.tt.tv.tw.tz.ua.ug.uk.us.uy.uz.va.vc.ve.vg.vi.vn.vu.wf.ws.ye.yt.za.zm.zw".split(".");
var TLD_url = "https://gitcdn.xyz/repo/umpirsky/tld-list/master/data/en/tld.json";
var TLD_cache = "./tld.json";
var TLD_refresh_msec = 15 * 24 * 60 * 60 * 1000;
var TLD_last_msec;
var TLD_default_filter=function(dom){return dom.substr(0,3)!="xn-"};


function getTLDs(cb,filter_func){

    if (typeof cb!=='function') return TLDs;

    var 
    read,fetch,
    CB_WRAP=function(tlds){
        return cb(
            filter_func===false
            ? cb(tlds)
            : tlds.filter(
                typeof filter_func==='function'
                 ? filter_func
                 : TLD_default_filter)
            );
    },
    check_mtime = function(mtime) {
       if (Date.now()-mtime > TLD_refresh_msec) {
           return fetch();
       } 
       if (TLDs) return CB_WRAP (TLDs);
       return read();
    };

    fetch = function(){

        getJSON(TLD_url,function(err,data){
            if (err) {
                console.log("exception in getTLDs.fetch:",err.message||err);
                return read(true);      
            } else {
                TLDs=Object.keys(data);

                fs.writeFile(TLD_cache,JSON.stringify(TLDs),function(err){
                    if (err) {
                        // ignore save error, we have the data
                        CB_WRAP(TLDs);
                    } else {
                        // get mmtime for the file we just made
                        fs.stat(TLD_cache,function(err,stats){
                            if (!err && stats) {
                               TLD_last_msec = stats.mtimeMs; 
                            }
                            CB_WRAP(TLDs);    
                        });
                    }
                });
            }
        });
    };

    read=function(bypassFetch) {
        fs.readFile(TLD_cache,'utf-8',function(err,json){

            try {
                if (err) {

                    if (bypassFetch) {
                        // after a http errror, we fallback to hardcoded basic list of tlds
                        // if the disk file is not readable
                        console.log("exception in getTLDs.read.bypassFetch:",err.messsage||err);    

                        throw err;
                    }
                    // if the disk read failed, get the data from the CDN server instead
                    return fetch();
                }

                TLDs=JSON.parse(json);
                if (bypassFetch) {
                    // we need to update stats here as fetch called us directly
                    // instead of being called by check_mtime
                    return fs.stat(TLD_cache,function(err,stats){
                        if (err) return fetch();
                        TLD_last_msec =stats.mtimeMs;
                        return CB_WRAP(TLDs);
                    });
                }

            } catch (e){
                // after JSON error, if we aren't in an http fail situation, refetch from cdn server
                if (!bypassFetch) {
                    return fetch();
                }

                // after a http,disk,or json parse error, we fallback to hardcoded basic list of tlds

                console.log("exception in getTLDs.read:",err.messsage||err);    
                TLDs=TLDs_fallback;
            }

            return CB_WRAP(TLDs);
        });
    };

    if (TLD_last_msec) {
        return check_mtime(TLD_last_msec);
    } else {
        fs.stat(TLD_cache,function(err,stats){
            if (err) return fetch();
            TLD_last_msec =stats.mtimeMs;
            return check_mtime(TLD_last_msec);
        });
    }
}

getTLDs(console.log.bind(console));

How to change the MySQL root account password on CentOS7?

All,

Here a little bit twist with mysql-community-server 5.7 I share some steps, how to reset mysql5.7 root password or set password. it will work centos7 and RHEL7 as well.

step1. 1st stop your databases

service mysqld stop

step2. 2nd modify /etc/my.cnf file add "skip-grant-tables"

vi /etc/my.cnf

[mysqld] skip-grant-tables

step3. 3rd start mysql

service mysqld start

step4. select mysql default database

mysql -u root

mysql>use mysql;

step4. set a new password

mysql> update user set authentication_string=PASSWORD("yourpassword") where User='root';

step5 restart mysql database

service mysqld restart

 mysql -u root -p

enjoy :)

Call a function from another file?

You don't have to add file.py.

Just keep the file in the same location with the file from where you want to import it. Then just import your functions:

from file import a, b

Basic example for sharing text or image with UIActivityViewController in Swift

You may use the following functions which I wrote in one of my helper class in a project.

just call

showShareActivity(msg:"message", image: nil, url: nil, sourceRect: nil) 

and it will work for both iPhone and iPad. If you pass any view's CGRect value by sourceRect it will also shows a little arrow in iPad.

func topViewController()-> UIViewController{
    var topViewController:UIViewController = UIApplication.shared.keyWindow!.rootViewController!

    while ((topViewController.presentedViewController) != nil) {
        topViewController = topViewController.presentedViewController!;
    }

    return topViewController
}

func showShareActivity(msg:String?, image:UIImage?, url:String?, sourceRect:CGRect?){
    var objectsToShare = [AnyObject]()

    if let url = url {
        objectsToShare = [url as AnyObject]
    }

    if let image = image {
        objectsToShare = [image as AnyObject]
    }

    if let msg = msg {
        objectsToShare = [msg as AnyObject]
    }

    let activityVC = UIActivityViewController(activityItems: objectsToShare, applicationActivities: nil)
    activityVC.modalPresentationStyle = .popover
    activityVC.popoverPresentationController?.sourceView = topViewController().view
    if let sourceRect = sourceRect {
        activityVC.popoverPresentationController?.sourceRect = sourceRect
    }

    topViewController().present(activityVC, animated: true, completion: nil)
}

int value under 10 convert to string two digit number

I will start my answer saying that most of previous answers were perfectly good answers at the time of writing them. So, thank you to them who wrote them.

Now, you can also use String Interpolation for same solution.

Edit: Adding this explanation after receiving a perfectively valid constructive comment from Heretic Monkey. I have preferred to use .ToString whenever I had need to convert an integer to string and not add the result to any other string. And, I have preferred to use interpolation whenever I had need to combine string(s) and an integer, like in below examples.

String Interpolation

i.ToString("00")
01

i.ToString("000")
001

i.ToString("0000")
0001

$"Prefix_{i:00}"
Prefix_01

$"Prefix_{i:000}"
Prefix_001

$"Prefix_{i:0000}_Suffix"
Prefix_0001_Suffix

Convert array of strings into a string in Java

String array[]={"one","two"};
String s="";

for(int i=0;i<array.length;i++)
{
  s=s+array[i];
}

System.out.print(s);

Stop fixed position at footer

This worked for me -

HTML -

<div id="sideNote" class="col-sm-3" style="float:right;">

</div> 
<div class="footer-wrap">
        <div id="footer-div">
        </div>      
</div>

CSS -

#sideNote{right:0; margin-top:10px; position:fixed; bottom:0; margin-bottom:5px;}

#footer-div{margin:0 auto; text-align:center; min-height:300px; margin-top:100px; padding:100px 50px;}

JQuery -

function isVisible(elment) {
    var vpH = $(window).height(), // Viewport Height
        st = $(window).scrollTop(), // Scroll Top
        y = $(elment).offset().top;

    return y <= (vpH + st);
}

function setSideNotePos(){
    $(window).scroll(function() {
        if (isVisible($('.footer-wrap'))) {
            $('#sideNote').css('position','absolute');
            $('#sideNote').css('top',$('.footer-wrap').offset().top - $('#sideNote').outerHeight() - 100);
        } else {
            $('#sideNote').css('position','fixed');
            $('#sideNote').css('top','auto');
        }
    });
}

Now call this function like this -

$(document).ready(function() {
    setSideNotePos();
});

PS - The Jquery functions are copied from an answer to another similar question on stackoverflow, but it wasn't working for me fully. So I modified it to these functions, as they are shown here. I think the position etc attributes to your divs will depend on how the divs are structured, who their parents and siblings are.

The above function works when both sideNote and footer-wraps are direct siblings.

SQLAlchemy: print the actual query

This works in python 2 and 3 and is a bit cleaner than before, but requires SA>=1.0.

from sqlalchemy.engine.default import DefaultDialect
from sqlalchemy.sql.sqltypes import String, DateTime, NullType

# python2/3 compatible.
PY3 = str is not bytes
text = str if PY3 else unicode
int_type = int if PY3 else (int, long)
str_type = str if PY3 else (str, unicode)


class StringLiteral(String):
    """Teach SA how to literalize various things."""
    def literal_processor(self, dialect):
        super_processor = super(StringLiteral, self).literal_processor(dialect)

        def process(value):
            if isinstance(value, int_type):
                return text(value)
            if not isinstance(value, str_type):
                value = text(value)
            result = super_processor(value)
            if isinstance(result, bytes):
                result = result.decode(dialect.encoding)
            return result
        return process


class LiteralDialect(DefaultDialect):
    colspecs = {
        # prevent various encoding explosions
        String: StringLiteral,
        # teach SA about how to literalize a datetime
        DateTime: StringLiteral,
        # don't format py2 long integers to NULL
        NullType: StringLiteral,
    }


def literalquery(statement):
    """NOTE: This is entirely insecure. DO NOT execute the resulting strings."""
    import sqlalchemy.orm
    if isinstance(statement, sqlalchemy.orm.Query):
        statement = statement.statement
    return statement.compile(
        dialect=LiteralDialect(),
        compile_kwargs={'literal_binds': True},
    ).string

Demo:

# coding: UTF-8
from datetime import datetime
from decimal import Decimal

from literalquery import literalquery


def test():
    from sqlalchemy.sql import table, column, select

    mytable = table('mytable', column('mycol'))
    values = (
        5,
        u'snowman: ?',
        b'UTF-8 snowman: \xe2\x98\x83',
        datetime.now(),
        Decimal('3.14159'),
        10 ** 20,  # a long integer
    )

    statement = select([mytable]).where(mytable.c.mycol.in_(values)).limit(1)
    print(literalquery(statement))


if __name__ == '__main__':
    test()

Gives this output: (tested in python 2.7 and 3.4)

SELECT mytable.mycol
FROM mytable
WHERE mytable.mycol IN (5, 'snowman: ?', 'UTF-8 snowman: ?',
      '2015-06-24 18:09:29.042517', 3.14159, 100000000000000000000)
 LIMIT 1

Setting Authorization Header of HttpClient

So the way to do it is the following,

httpClient.DefaultRequestHeaders.Authorization =
    new AuthenticationHeaderValue("Bearer", "Your Oauth token");

How to convert from []byte to int in Go Programming

var bs []byte
value, _ := strconv.ParseInt(string(bs), 10, 64)

Getting the exception value in Python

If you don't know the type/origin of the error, you can try:

import sys
try:
    doSomethingWrongHere()
except:
    print('Error: {}'.format(sys.exc_info()[0]))

But be aware, you'll get pep8 warning:

[W] PEP 8 (E722): do not use bare except

How to DROP multiple columns with a single ALTER TABLE statement in SQL Server?

Select column to drop:

ALTER TABLE my_table
DROP column_to_be_deleted;

However, some databases (including SQLite) have limited support, and you may have to create a new table and migrate the data over:

https://www.sqlite.org/faq.html#q11

'this' is undefined in JavaScript class methods

JavaScript's OOP is a little funky (or a lot) and it takes some getting used to. This first thing you need to keep in mind is that there are no Classes and thinking in terms of classes can trip you up. And in order to use a method attached to a Constructor (the JavaScript equivalent of a Class definition) you need to instantiate your object. For example:

Ninja = function (name) {
    this.name = name;
};
aNinja = new Ninja('foxy');
aNinja.name; //-> 'foxy'

enemyNinja = new Ninja('boggis');
enemyNinja.name; //=> 'boggis'

Note that Ninja instances have the same properties but aNinja cannot access the properties of enemyNinja. (This part should be really easy/straightforward) Things get a bit different when you start adding stuff to the prototype:

Ninja.prototype.jump = function () {
   return this.name + ' jumped!';
};
Ninja.prototype.jump(); //-> Error.
aNinja.jump(); //-> 'foxy jumped!'
enemyNinja.jump(); //-> 'boggis jumped!'

Calling this directly will throw an error because this only points to the correct object (your "Class") when the Constructor is instantiated (otherwise it points to the global object, window in a browser)

Inserting data to table (mysqli insert)

Warning: Never ever refer to w3schools for learning purposes. They have so many mistakes in their tutorials.

According to the mysqli_query documentation, the first parameter must be a connection string:

$link = mysqli_connect("localhost","root","","web_table");

mysqli_query($link,"INSERT INTO web_formitem (`ID`, `formID`, `caption`, `key`, `sortorder`, `type`, `enabled`, `mandatory`, `data`)
VALUES (105, 7, 'Tip izdelka (6)', 'producttype_6', 42, 5, 1, 0, 0)") 
or die(mysqli_error($link));

Note: Add backticks ` for column names in your insert query as some of your column names are reserved words.

Connecting to SQL Server using windows authentication

This worked for me:

in web.config file;

<add name="connectionstring name " connectionstring="server=SQLserver name; database= databasename; integrated security = true"/>

How to change Oracle default data pump directory to import dumpfile?

use DIRECTORY option.

Documentation here: http://docs.oracle.com/cd/E11882_01/server.112/e22490/dp_import.htm#SUTIL907

  DIRECTORY

  Default: DATA_PUMP_DIR

  Purpose

  Specifies the default location in which the import job can find the dump file set and where it should create log and SQL files.

  Syntax and Description

  DIRECTORY=directory_object
  The directory_object is the name of a database directory object (not the file path of an actual directory). Upon installation, privileged users have access to a default directory object named DATA_PUMP_DIR. Users with access to the default DATA_PUMP_DIR directory object do not need to use the DIRECTORY parameter at all.

  A directory object specified on the DUMPFILE, LOGFILE, or SQLFILE parameter overrides any directory object that you specify for the DIRECTORY parameter. You must have Read access to the directory used for the dump file set and Write access to the directory used to create the log and SQL files.

  Example

  The following is an example of using the DIRECTORY parameter. You can create the expfull.dmp dump file used in this example by running the example provided for the Export FULL parameter. See "FULL".

  > impdp hr DIRECTORY=dpump_dir1 DUMPFILE=expfull.dmp 
  LOGFILE=dpump_dir2:expfull.log
  This command results in the import job looking for the expfull.dmp dump file in the directory pointed to by the dpump_dir1 directory object. The dpump_dir2 directory object specified on the LOGFILE parameter overrides the DIRECTORY parameter so that the log file is written to dpump_dir2.

How to create an empty file with Ansible?

In order to create a file in the remote machine with the ad-hoc command

ansible client -m file -a"dest=/tmp/file state=touch"

Please correct me if I am wrong

Return Index of an Element in an Array Excel VBA

Is this what you are looking for?

public function GetIndex(byref iaList() as integer, byval iInteger as integer) as integer

dim i as integer

 for i=lbound(ialist) to ubound(ialist)
  if iInteger=ialist(i) then
   GetIndex=i
   exit for
  end if
 next i

end function

Get the current cell in Excel VB

The keyword "Selection" is already a vba Range object so you can use it directly, and you don't have to select cells to copy, for example you can be on Sheet1 and issue these commands:

ThisWorkbook.worksheets("sheet2").Range("namedRange_or_address").Copy
ThisWorkbook.worksheets("sheet1").Range("namedRange_or_address").Paste

If it is a multiple selection you should use the Area object in a for loop:

Dim a as Range
For Each a in ActiveSheet.Selection.Areas
    a.Copy
    ThisWorkbook.worksheets("sheet2").Range("A1").Paste
Next

Regards

Thomas

T-SQL: Export to new Excel file

Use PowerShell:

$Server = "TestServer"
$Database = "TestDatabase"
$Query = "select * from TestTable"
$FilePath = "C:\OutputFile.csv"

# This will overwrite the file if it already exists.
Invoke-Sqlcmd -Query $Query -Database $Database -ServerInstance $Server | Export-Csv $FilePath

In my usual cases, all I really need is a CSV file that can be read by Excel. However, if you need an actual Excel file, then tack on some code to convert the CSV file to an Excel file. This answer gives a solution for this, but I've not tested it.

Excel VBA: AutoFill Multiple Cells with Formulas

Based on my Comment here is one way to get what you want done:

Start byt selecting any cell in your range and Press Ctrl + T

This will give you this pop up:

enter image description here

make sure the Where is your table text is correct and click ok you will now have:

enter image description here

Now If you add a column header in D it will automatically be added to the table all the way to the last row:

enter image description here

Now If you enter a formula into this column:

enter image description here

After you enter it, the formula will be auto filled all the way to last row:

enter image description here

Now if you add a new row at the next row under your table:

enter image description here

Once entered it will be resized to the width of your table and all columns with formulas will be added also:

enter image description here

Hope this solves your problem!

Regex to validate password strength

You can use zero-length positive look-aheads to specify each of your constraints separately:

(?=.{8,})(?=.*\p{Lu}.*\p{Lu})(?=.*[!@#$&*])(?=.*[0-9])(?=.*\p{Ll}.*\p{Ll})

If your regex engine doesn't support the \p notation and pure ASCII is enough, then you can replace \p{Lu} with [A-Z] and \p{Ll} with [a-z].

How do I delete everything in Redis?

With redis-cli:

  • FLUSHDB – Deletes all keys from the connection's current database.
  • FLUSHALL – Deletes all keys from all databases.

For example, in your shell:

redis-cli flushall

creating custom tableview cells in swift

[1] First Design your tableview cell in StoryBoard.

[2] Put below table view delegate method

//MARK: - Tableview Delegate Methods

func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
    return 1
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{

    return <“Your Array”>
}


func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
{

    var totalHeight : CGFloat = <cell name>.<label name>.frame.origin.y    

    totalHeight +=   UpdateRowHeight(<cell name>.<label name>, textToAdd: <your array>[indexPath.row])    

    return totalHeight
}


func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{


    var cell : <cell name>! = tableView.dequeueReusableCellWithIdentifier(“<cell identifire>”, forIndexPath: indexPath) as! CCell_VideoCall

    if(cell == nil)
    {
        cell = NSBundle.mainBundle().loadNibNamed("<cell identifire>", owner: self, options: nil)[0] as! <cell name>;
    }


    <cell name>.<label name>.text = <your array>[indexPath.row] as? String



    return cell as <cell name>
}

//MARK: - Custom Methods

func UpdateRowHeight ( ViewToAdd : UILabel , textToAdd : AnyObject  ) -> CGFloat{


    var actualHeight : CGFloat = ViewToAdd.frame.size.height

    if let strName : String? = (textToAdd as? String)
        where !strName!.isEmpty
    {

        actualHeight = heightForView1(strName!, font: ViewToAdd.font, width: ViewToAdd.frame.size.width, DesignTimeHeight: actualHeight )

    }
    return actualHeight
}

How do I link to a library with Code::Blocks?

The gdi32 library is already installed on your computer, few programs will run without it. Your compiler will (if installed properly) normally come with an import library, which is what the linker uses to make a binding between your program and the file in the system. (In the unlikely case that your compiler does not come with import libraries for the system libs, you will need to download the Microsoft Windows Platform SDK.)

To link with gdi32:

enter image description here

This will reliably work with MinGW-gcc for all system libraries (it should work if you use any other compiler too, but I can't talk about things I've not tried). You can also write the library's full name, but writing libgdi32.a has no advantage over gdi32 other than being more type work.
If it does not work for some reason, you may have to provide a different name (for example the library is named gdi32.lib for MSVC).

For libraries in some odd locations or project subfolders, you will need to provide a proper pathname (click on the "..." button for a file select dialog).

How to convert ASCII code (0-255) to its corresponding character?

    for (int i = 0; i < 256; i++) {
        System.out.println(i + " -> " + (char) i);
    }

    char lowercase = 'f';
    int offset = (int) 'a' - (int) 'A';
    char uppercase = (char) ((int) lowercase - offset);
    System.out.println("The uppercase letter is " + uppercase);

    String numberString = JOptionPane.showInputDialog(null,
            "Enter an ASCII code:",
            "ASCII conversion", JOptionPane.QUESTION_MESSAGE);

    int code = (int) numberString.charAt(0);
    System.out.println("The character for ASCII code "
            + code + " is " + (char) code);

Loading existing .html file with android WebView

The debug compilation is different from the release one, so:

Consider your Project file structure like that [this case if for a Debug assemble]:

src
  |
  debug
      |
      assets
           |
           index.html

You should call index.html into your WebView like:

web.loadUrl("file:///android_asset/index.html");

So forth, for the Release assemble, it should be like:

src
  |
  release
        |
        assets
             |
             index.html

The bellow structure also works, for both compilations [debug and release]:

src
  |
  main
     |
     assets
          |
          index.html

Where is localhost folder located in Mac or Mac OS X?

For posterity

I never use PHP so I completely forgot where apache was installed on my mac as it was running on port 8080 mocking me, installed in a non-standard path. After giving up on the internet, I tried this...

httpd -t -D DUMP_INCLUDES

Because httpd was running it produced the httpd.config path and then the clouds parted and the sun shown brightly on my face. Victory! as within it lies the path to localhost.

ServerRoot "/your/path"

Creating a SearchView that looks like the material design guidelines

The first screenshot in your question is not a public widget. The support SearchView (android.support.v7.widget.SearchView) mimics Android 5.0 Lollipop's SearchView (android.widget.SearchView). Your second screenshot is used by other material designed apps like Google Play.

The SearchView in your first screenshot is used in Drive, YouTube and other closed source Google Apps. Fortunately, it is also used in the Android 5.0 Dialer. You can try to backport the view, but it uses some 5.0 APIs.

The classes which you will want to look at are:

SearchEditTextLayout, AnimUtils, and DialtactsActivity to understand how to use the View. You will also need resources from ContactsCommon.

Best of luck.

Why use HttpClient for Synchronous Connection

public static class AsyncHelper  
{
    private static readonly TaskFactory _taskFactory = new
        TaskFactory(CancellationToken.None,
                    TaskCreationOptions.None,
                    TaskContinuationOptions.None,
                    TaskScheduler.Default);

    public static TResult RunSync<TResult>(Func<Task<TResult>> func)
        => _taskFactory
            .StartNew(func)
            .Unwrap()
            .GetAwaiter()
            .GetResult();

    public static void RunSync(Func<Task> func)
        => _taskFactory
            .StartNew(func)
            .Unwrap()
            .GetAwaiter()
            .GetResult();
}

Then

AsyncHelper.RunSync(() => DoAsyncStuff());

if you use that class pass your async method as parameter you can call the async methods from sync methods in a safe way.

it's explained here : https://cpratt.co/async-tips-tricks/

PNG transparency issue in IE8

My scenario:

  • I had a background image that had a 24bit alpha png that was set to an anchor link.
  • The anchor was being faded in on hover using Jquery.

eg.

a.button { background-image: url(this.png; }

I found that applying the mark-up provided by Dan Tello didn't work.

However, by placing a span within the anchor element, and setting the background-image to that element I was able to achieve a good result using Dan Tello's markup.

eg.

a.button span { background-image: url(this.png; }

WebApi's {"message":"an error has occurred"} on IIS7, not in IIS Express

Basically:

Use IncludeErrorDetailPolicy instead if CustomErrors doesn't solve it for you (e.g. if you're ASP.NET stack is >2012):

GlobalConfiguration.Configuration.IncludeErrorDetailPolicy 
= IncludeErrorDetailPolicy.Always;

Note: Be careful returning detailed error info can reveal sensitive information to 'hackers'. See Simon's comment on this answer below.

TL;DR version

For me CustomErrors didn't really help. It was already set to Off, but I still only got a measly an error has occurred message. I guess the accepted answer is from 3 years ago which is a long time in the web word nowadays. I'm using Web API 2 and ASP.NET 5 (MVC 5) and Microsoft has moved away from an IIS-only strategy, while CustomErrors is old skool IIS ;).

Anyway, I had an issue on production that I didn't have locally. And then found I couldn't see the errors in Chrome's Network tab like I could on my dev machine. In the end I managed to solve it by installing Chrome on my production server and then browsing to the app there on the server itself (e.g. on 'localhost'). Then more detailed errors appeared with stack traces and all.

Only afterwards I found this article from Jimmy Bogard (Note: Jimmy is mr. AutoMapper!). The funny thing is that his article is also from 2012, but in it he already explains that CustomErrors doesn't help for this anymore, but that you CAN change the 'Error detail' by setting a different IncludeErrorDetailPolicy in the global WebApi configuration (e.g. WebApiConfig.cs):

GlobalConfiguration.Configuration.IncludeErrorDetailPolicy 
= IncludeErrorDetailPolicy.Always;

Luckily he also explains how to set it up that webapi (2) DOES listen to your CustomErrors settings. That's a pretty sensible approach, and this allows you to go back to 2012 :P.

Note: The default value is 'LocalOnly', which explains why I was able to solve the problem the way I described, before finding this post. But I understand that not everybody can just remote to production and startup a browser (I know I mostly couldn't until I decided to go freelance AND DevOps).

How to parse JSON string in Typescript

There is a great library for it ts-json-object

In your case you would need to run the following code:

import {JSONObject, required} from 'ts-json-object'

class Response extends JSONObject {
    @required
    name: string;

    @required
    error: boolean;
}

let resp = new Response({"name": "Bob", "error": false});

This library will validate the json before parsing

css background image in a different folder from css

body

{

background-image: url('../images/bg.jpeg');

}

Should operator<< be implemented as a friend or as a member function?

It should be implemented as a free, non-friend functions, especially if, like most things these days, the output is mainly used for diagnostics and logging. Add const accessors for all the things that need to go into the output, and then have the outputter just call those and do formatting.

I've actually taken to collecting all of these ostream output free functions in an "ostreamhelpers" header and implementation file, it keeps that secondary functionality far away from the real purpose of the classes.

HorizontalScrollView within ScrollView Touch Handling

Thank you Joel for giving me a clue on how to resolve this problem.

I have simplified the code(without need for a GestureDetector) to achieve the same effect:

public class VerticalScrollView extends ScrollView {
    private float xDistance, yDistance, lastX, lastY;

    public VerticalScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                xDistance = yDistance = 0f;
                lastX = ev.getX();
                lastY = ev.getY();
                break;
            case MotionEvent.ACTION_MOVE:
                final float curX = ev.getX();
                final float curY = ev.getY();
                xDistance += Math.abs(curX - lastX);
                yDistance += Math.abs(curY - lastY);
                lastX = curX;
                lastY = curY;
                if(xDistance > yDistance)
                    return false;
        }

        return super.onInterceptTouchEvent(ev);
    }
}

Psexec "run as (remote) admin"

Simply add a -h after adding your credentials using a -u -p, and it will run with elevated privileges.

Tkinter understanding mainloop

tk.mainloop() blocks. It means that execution of your Python commands halts there. You can see that by writing:

while 1:
    ball.draw()
    tk.mainloop()
    print("hello")   #NEW CODE
    time.sleep(0.01)

You will never see the output from the print statement. Because there is no loop, the ball doesn't move.

On the other hand, the methods update_idletasks() and update() here:

while True:
    ball.draw()
    tk.update_idletasks()
    tk.update()

...do not block; after those methods finish, execution will continue, so the while loop will execute over and over, which makes the ball move.

An infinite loop containing the method calls update_idletasks() and update() can act as a substitute for calling tk.mainloop(). Note that the whole while loop can be said to block just like tk.mainloop() because nothing after the while loop will execute.

However, tk.mainloop() is not a substitute for just the lines:

tk.update_idletasks()
tk.update()

Rather, tk.mainloop() is a substitute for the whole while loop:

while True:
    tk.update_idletasks()
    tk.update()

Response to comment:

Here is what the tcl docs say:

Update idletasks

This subcommand of update flushes all currently-scheduled idle events from Tcl's event queue. Idle events are used to postpone processing until “there is nothing else to do”, with the typical use case for them being Tk's redrawing and geometry recalculations. By postponing these until Tk is idle, expensive redraw operations are not done until everything from a cluster of events (e.g., button release, change of current window, etc.) are processed at the script level. This makes Tk seem much faster, but if you're in the middle of doing some long running processing, it can also mean that no idle events are processed for a long time. By calling update idletasks, redraws due to internal changes of state are processed immediately. (Redraws due to system events, e.g., being deiconified by the user, need a full update to be processed.)

APN As described in Update considered harmful, use of update to handle redraws not handled by update idletasks has many issues. Joe English in a comp.lang.tcl posting describes an alternative:

So update_idletasks() causes some subset of events to be processed that update() causes to be processed.

From the update docs:

update ?idletasks?

The update command is used to bring the application “up to date” by entering the Tcl event loop repeatedly until all pending events (including idle callbacks) have been processed.

If the idletasks keyword is specified as an argument to the command, then no new events or errors are processed; only idle callbacks are invoked. This causes operations that are normally deferred, such as display updates and window layout calculations, to be performed immediately.

KBK (12 February 2000) -- My personal opinion is that the [update] command is not one of the best practices, and a programmer is well advised to avoid it. I have seldom if ever seen a use of [update] that could not be more effectively programmed by another means, generally appropriate use of event callbacks. By the way, this caution applies to all the Tcl commands (vwait and tkwait are the other common culprits) that enter the event loop recursively, with the exception of using a single [vwait] at global level to launch the event loop inside a shell that doesn't launch it automatically.

The commonest purposes for which I've seen [update] recommended are:

  1. Keeping the GUI alive while some long-running calculation is executing. See Countdown program for an alternative. 2) Waiting for a window to be configured before doing things like geometry management on it. The alternative is to bind on events such as that notify the process of a window's geometry. See Centering a window for an alternative.

What's wrong with update? There are several answers. First, it tends to complicate the code of the surrounding GUI. If you work the exercises in the Countdown program, you'll get a feel for how much easier it can be when each event is processed on its own callback. Second, it's a source of insidious bugs. The general problem is that executing [update] has nearly unconstrained side effects; on return from [update], a script can easily discover that the rug has been pulled out from under it. There's further discussion of this phenomenon over at Update considered harmful.

.....

Is there any chance I can make my program work without the while loop?

Yes, but things get a little tricky. You might think something like the following would work:

class Ball:
    def __init__(self, canvas, color):
        self.canvas = canvas
        self.id = canvas.create_oval(10, 10, 25, 25, fill=color)
        self.canvas.move(self.id, 245, 100)

    def draw(self):
        while True:
           self.canvas.move(self.id, 0, -1)

ball = Ball(canvas, "red")
ball.draw()
tk.mainloop()

The problem is that ball.draw() will cause execution to enter an infinite loop in the draw() method, so tk.mainloop() will never execute, and your widgets will never display. In gui programming, infinite loops have to be avoided at all costs in order to keep the widgets responsive to user input, e.g. mouse clicks.

So, the question is: how do you execute something over and over again without actually creating an infinite loop? Tkinter has an answer for that problem: a widget's after() method:

from Tkinter import *
import random
import time

tk = Tk()
tk.title = "Game"
tk.resizable(0,0)
tk.wm_attributes("-topmost", 1)

canvas = Canvas(tk, width=500, height=400, bd=0, highlightthickness=0)
canvas.pack()

class Ball:
    def __init__(self, canvas, color):
        self.canvas = canvas
        self.id = canvas.create_oval(10, 10, 25, 25, fill=color)
        self.canvas.move(self.id, 245, 100)

    def draw(self):
        self.canvas.move(self.id, 0, -1)
        self.canvas.after(1, self.draw)  #(time_delay, method_to_execute)


       

ball = Ball(canvas, "red")
ball.draw()  #Changed per Bryan Oakley's comment
tk.mainloop()

The after() method doesn't block (it actually creates another thread of execution), so execution continues on in your python program after after() is called, which means tk.mainloop() executes next, so your widgets get configured and displayed. The after() method also allows your widgets to remain responsive to other user input. Try running the following program, and then click your mouse on different spots on the canvas:

from Tkinter import *
import random
import time

root = Tk()
root.title = "Game"
root.resizable(0,0)
root.wm_attributes("-topmost", 1)

canvas = Canvas(root, width=500, height=400, bd=0, highlightthickness=0)
canvas.pack()

class Ball:
    def __init__(self, canvas, color):
        self.canvas = canvas
        self.id = canvas.create_oval(10, 10, 25, 25, fill=color)
        self.canvas.move(self.id, 245, 100)

        self.canvas.bind("<Button-1>", self.canvas_onclick)
        self.text_id = self.canvas.create_text(300, 200, anchor='se')
        self.canvas.itemconfig(self.text_id, text='hello')

    def canvas_onclick(self, event):
        self.canvas.itemconfig(
            self.text_id, 
            text="You clicked at ({}, {})".format(event.x, event.y)
        )

    def draw(self):
        self.canvas.move(self.id, 0, -1)
        self.canvas.after(50, self.draw)


       

ball = Ball(canvas, "red")
ball.draw()  #Changed per Bryan Oakley's comment.
root.mainloop()

How to fix Terminal not loading ~/.bashrc on OS X Lion

Terminal opens a login shell. This means, ~/.bash_profile will get executed, ~/.bashrc not.

The solution on most systems is to "require" the ~/.bashrc in the ~/.bash_profile: just put this snippet in your ~/.bash_profile:

[[ -s ~/.bashrc ]] && source ~/.bashrc

How to get HTTP Response Code using Selenium WebDriver

It is not possible to get HTTP Response code by using Selenium WebDriver directly. The code can be got by using Java code and that can be used in Selenium WebDriver.

To get HTTP Response code by java:

public static int getResponseCode(String urlString) throws MalformedURLException, IOException{
    URL url = new URL(urlString);
    HttpURLConnection huc = (HttpURLConnection)url.openConnection();
    huc.setRequestMethod("GET");
    huc.connect();
    return huc.getResponseCode();
}

Now you can write your Selenium WebDriver code as below:

private static int statusCode;
public static void main(String... args) throws IOException{
    WebDriver driver = new FirefoxDriver();
    driver.manage().window().maximize();
    driver.get("https://www.google.com/");
    driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

    List<WebElement> links = driver.findElements(By.tagName("a"));
    for(int i = 0; i < links.size(); i++){
        if(!(links.get(i).getAttribute("href") == null) && !(links.get(i).getAttribute("href").equals(""))){
            if(links.get(i).getAttribute("href").contains("http")){
                statusCode= getResponseCode(links.get(i).getAttribute("href").trim());
                if(statusCode == 403){
                    System.out.println("HTTP 403 Forbidden # " + i + " " + links.get(i).getAttribute("href"));
                }
            }
        }   
    }   
}

How to check if a column exists in Pandas

This will work:

if 'A' in df:

But for clarity, I'd probably write it as:

if 'A' in df.columns:

iPhone 6 Plus resolution confusion: Xcode or Apple's website? for development

Check out this infographic: http://www.paintcodeapp.com/news/iphone-6-screens-demystified

It explains the differences between old iPhones, iPhone 6 and iPhone 6 Plus. You can see comparison of screen sizes in points, rendered pixels and physical pixels. You will also find answer to your question there:

iPhone 6 Plus - with Retina display HD. Scaling factor is 3 and the image is afterwards downscaled from rendered 2208 × 1242 pixels to 1920 × 1080 pixels.

The downscaling ratio is 1920 / 2208 = 1080 / 1242 = 20 / 23. That means every 23 pixels from the original render have to be mapped to 20 physical pixels. In other words the image is scaled down to approximately 87% of its original size.

Update:

There is an updated version of infographic mentioned above. It contains more detailed info about screen resolution differences and it covers all iPhone models so far, including 4 inch devices.

http://www.paintcodeapp.com/news/ultimate-guide-to-iphone-resolutions

Command not found error in Bash variable assignment

In the interactive mode everything looks fine:

$ str="Hello World"
$ echo $str
Hello World

Obviously(!) as Johannes said, no space around =. In case there is any space around = then in the interactive mode it gives errors as

No command 'str' found

How to finish current activity in Android

I tried using this example but it failed miserably. Every time I use to invoke finish()/ finishactivity() inside a handler, I end up with this menacing java.lang.IllegalAccess Exception. i'm not sure how did it work for the one who posed the question.

Instead the solution I found was that create a method in your activity such as

void kill_activity()
{ 
    finish();
}

Invoke this method from inside the run method of the handler. This worked like a charm for me. Hope this helps anyone struggling with "how to close an activity from a different thread?".

Why would you use Expression<Func<T>> rather than Func<T>?

You would use an expression when you want to treat your function as data and not as code. You can do this if you want to manipulate the code (as data). Most of the time if you don't see a need for expressions then you probably don't need to use one.

Bash scripting missing ']'

Change

if [ -s "p1"];  #line 13

into

if [ -s "p1" ];  #line 13

note the space.

Regular Expression Validation For Indian Phone Number and Mobile number

You Can Use Regex Like This:

   ^[0-9\-\(\)\, ]+$

JavaScript seconds to time string with format hh:mm:ss

I like the first answer. There some optimisations:

  • source data is a Number. additional calculations is not needed.

  • much excess computing

Result code:

Number.prototype.toHHMMSS = function () {
    var seconds = Math.floor(this),
        hours = Math.floor(seconds / 3600);
    seconds -= hours*3600;
    var minutes = Math.floor(seconds / 60);
    seconds -= minutes*60;

    if (hours   < 10) {hours   = "0"+hours;}
    if (minutes < 10) {minutes = "0"+minutes;}
    if (seconds < 10) {seconds = "0"+seconds;}
    return hours+':'+minutes+':'+seconds;
}

avrdude: stk500v2_ReceiveMessage(): timeout

My aurdino mega 2560 returned same error. It seems the problem exists in unofficial clones. The issue solved by pressing reset button just before uploading starts, as advertised in following video.

https://www.youtube.com/watch?v=tAzjO4v7oF4&list=LLDn5ewJDzz53IiwWmZTgQnQ&index=1

hide/show a image in jquery

I had to do something like this just now. I ended up doing:

function newWaitImg(id) {
    var img = {
       "id" : id,
       "state" : "on",
       "hide" : function () {
           $(this.id).hide();
           this.state = "off";
       },
       "show" : function () {
           $(this.id).show();
           this.state = "on";
       },
       "toggle" : function () {
           if (this.state == "on") {
               this.hide();
           } else {
               this.show();
           }
       }
    };
};

.
.
.

var waitImg = newWaitImg("#myImg");
.
.
.
waitImg.hide(); / waitImg.show(); / waitImg.toggle();

Input group - two inputs close to each other

My solution requires no additional css and works with any combination of input-addon, input-btn and form-control. It just uses pre-existing bootstrap classes

_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>_x000D_
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" type="text/css" rel="stylesheet" />_x000D_
<form style="padding:10px; margin:10px" action="" class=" form-inline">_x000D_
  <div class="form-group">_x000D_
    <div class="input-group">_x000D_
    <div class="form-group">_x000D_
        <div class="input-group">_x000D_
          <input type="text" class="form-control" placeholder="MinVal">_x000D_
        </div>_x000D_
      </div>_x000D_
      <div class="form-group">_x000D_
        <div class="input-group">_x000D_
          <input type="text" class="form-control" placeholder="MaxVal">_x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
</form>
_x000D_
_x000D_
_x000D_

This will be inline if there is space and wrap for smaller screens.

Full Example ( input-addon, input-btn and form-control. )

jsfiddle

_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>_x000D_
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" type="text/css" rel="stylesheet" />_x000D_
<form style="padding:10px; margin:10px" action="" class=" form-inline">_x000D_
  <div class="form-group">_x000D_
    <div class="input-group">_x000D_
      <div class="form-group">_x000D_
        <div class="input-group">_x000D_
          <span class="input-group-addon" id="basic-addon1">@</span>_x000D_
          <input type="text" class="form-control" placeholder="Username" aria-describedby="basic-addon1">_x000D_
          <span></span>_x000D_
        </div>_x000D_
      </div>_x000D_
      <div class="form-group">_x000D_
        <div class="input-group">_x000D_
          <span></span>_x000D_
          <span class="input-group-addon" id="basic-addon1">@</span>_x000D_
          <input type="text" class="form-control" placeholder="Username" aria-describedby="basic-addon1">_x000D_
          <span></span>_x000D_
        </div>_x000D_
      </div>_x000D_
      <div class="form-group">_x000D_
        <div class="input-group">_x000D_
          <span></span>_x000D_
          <span class="input-group-addon" id="basic-addon1">@</span>_x000D_
          <input type="text" class="form-control" placeholder="Username" aria-describedby="basic-addon1">_x000D_
          <span></span>_x000D_
        </div>_x000D_
      </div>_x000D_
      <br>_x000D_
_x000D_
      <div class="form-group">_x000D_
        <div class="input-group">_x000D_
          <input type="text" class="form-control" placeholder="Username" aria-describedby="basic-addon1">_x000D_
          <span></span>_x000D_
        </div>_x000D_
      </div>_x000D_
      <div class="form-group">_x000D_
        <div class="input-group">_x000D_
          <span></span>_x000D_
          <input type="text" class="form-control" placeholder="Username" aria-describedby="basic-addon1">_x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
</form>
_x000D_
_x000D_
_x000D_

JavaScript backslash (\) in variables is causing an error

The backslash (\) is an escape character in Javascript (along with a lot of other C-like languages). This means that when Javascript encounters a backslash, it tries to escape the following character. For instance, \n is a newline character (rather than a backslash followed by the letter n).

In order to output a literal backslash, you need to escape it. That means \\ will output a single backslash (and \\\\ will output two, and so on). The reason "aa ///\" doesn't work is because the backslash escapes the " (which will print a literal quote), and thus your string is not properly terminated. Similarly, "aa ///\\\" won't work, because the last backslash again escapes the quote.

Just remember, for each backslash you want to output, you need to give Javascript two.

Can I get Unix's pthread.h to compile in Windows?

There are, as i recall, two distributions of the gnu toolchain for windows: mingw and cygwin.

I'd expect cygwin work - a lot of effort has been made to make that a "stadard" posix environment.

The mingw toolchain uses msvcrt.dll for its runtime and thus will probably expose msvcrt's "thread" api: _beginthread which is defined in <process.h>

Angular 2: Get Values of Multiple Checked Checkboxes

I have find a solution thanks to Gunter! Here is my whole code if it could help anyone:

<div class="form-group">
            <label for="options">Options :</label>
            <div *ngFor="#option of options; #i = index">
                <label>
                    <input type="checkbox"
                           name="options"
                           value="{{option}}"
                           [checked]="options.indexOf(option) >= 0"
                           (change)="updateCheckedOptions(option, $event)"/>
                    {{option}}
                </label>
            </div>
        </div>

Here are the 3 objects I'm using:

options = ['OptionA', 'OptionB', 'OptionC'];
optionsMap = {
        OptionA: false,
        OptionB: false,
        OptionC: false,
};
optionsChecked = [];

And there are 3 useful methods:

1. To initiate optionsMap:

initOptionsMap() {
    for (var x = 0; x<this.order.options.length; x++) {
        this.optionsMap[this.options[x]] = true;
    }
}

2. to update the optionsMap:

updateCheckedOptions(option, event) {
   this.optionsMap[option] = event.target.checked;
}

3. to convert optionsMap into optionsChecked and store it in options before sending the POST request:

updateOptions() {
    for(var x in this.optionsMap) {
        if(this.optionsMap[x]) {
            this.optionsChecked.push(x);
        }
    }
    this.options = this.optionsChecked;
    this.optionsChecked = [];
}

How can I get the baseurl of site?

Please use the below code                           

string.Format("{0}://{1}", Request.url.Scheme, Request.url.Host);

c# foreach (property in object)... Is there a simple way of doing this?

I couldn't get any of the above ways to work, but this worked. The username and password for DirectoryEntry are optional.

   private List<string> getAnyDirectoryEntryPropertyValue(string userPrincipalName, string propertyToSearchFor)
    {
        List<string> returnValue = new List<string>();
        try
        {
            int index = userPrincipalName.IndexOf("@");
            string originatingServer = userPrincipalName.Remove(0, index + 1);
            string path = "LDAP://" + originatingServer; //+ @"/" + distinguishedName;
            DirectoryEntry objRootDSE = new DirectoryEntry(path, PSUsername, PSPassword);
            var objSearcher = new System.DirectoryServices.DirectorySearcher(objRootDSE);
            objSearcher.Filter = string.Format("(&(UserPrincipalName={0}))", userPrincipalName);
            SearchResultCollection properties = objSearcher.FindAll();

            ResultPropertyValueCollection resPropertyCollection = properties[0].Properties[propertyToSearchFor];
            foreach (string resProperty in resPropertyCollection)
            {
                returnValue.Add(resProperty);
            }
        }
        catch (Exception ex)
        {
            returnValue.Add(ex.Message);
            throw;
        }

        return returnValue;
    }

Tri-state Check box in HTML?

Like @Franz answer you can also do it with a select. For example:

<select>
  <option></option>
  <option value="Yes">Yes</option>
  <option value="No">No</option>
</select>

With this you can also give a concrete value that will be send with the form, I think that with javascript indeterminate version of checkbox, it will send the underline value of the checkbox.

At least, you can use it as a callback when javascript is disabled. For example, give it an id and in the load event change it to the javascript version of the checkbox with indeterminate status.

What is "pass-through authentication" in IIS 7?

Normally, IIS would use the process identity (the user account it is running the worker process as) to access protected resources like file system or network.

With passthrough authentication, IIS will attempt to use the actual identity of the user when accessing protected resources.

If the user is not authenticated, IIS will use the application pool identity instead. If pool identity is set to NetworkService or LocalSystem, the actual Windows account used is the computer account.

The IIS warning you see is not an error, it's just a warning. The actual check will be performed at execution time, and if it fails, it'll show up in the log.

How to connect from windows command prompt to mysql command line

C:\Program Files\MySQL\MySQL Server 5.7\bin> mysql -u username -p

Then it will ask for the password. Enter the password you set for the username during installation while adding db Users. In the given image depp is my username

How to increase font size in a plot in R?

Notice that "cex" does change things when the plot is made with text. For example, the plot of an agglomerative hierarchical clustering:

library(cluster)
data(votes.repub)
agn1 <- agnes(votes.repub, metric = "manhattan", stand = TRUE)
plot(agn1, which.plots=2)

will produce a plot with normal sized text:

enter image description here

and plot(agn1, which.plots=2, cex=0.5) will produce this one:

enter image description here

Is Java RegEx case-insensitive?

RegexBuddy is telling me if you want to include it at the beginning, this is the correct syntax:

"(?i)\\b(\\w+)\\b(\\s+\\1)+\\b"

PHP shell_exec() vs exec()

A couple of distinctions that weren't touched on here:

  • With exec(), you can pass an optional param variable which will receive an array of output lines. In some cases this might save time, especially if the output of the commands is already tabular.

Compare:

exec('ls', $out);
var_dump($out);
// Look an array

$out = shell_exec('ls');
var_dump($out);
// Look -- a string with newlines in it

Conversely, if the output of the command is xml or json, then having each line as part of an array is not what you want, as you'll need to post-process the input into some other form, so in that case use shell_exec.

It's also worth pointing out that shell_exec is an alias for the backtic operator, for those used to *nix.

$out = `ls`;
var_dump($out);

exec also supports an additional parameter that will provide the return code from the executed command:

exec('ls', $out, $status);
if (0 === $status) {
    var_dump($out);
} else {
    echo "Command failed with status: $status";
}

As noted in the shell_exec manual page, when you actually require a return code from the command being executed, you have no choice but to use exec.

JavaScript check if variable exists (is defined/initialized)

My preference is typeof(elem) != 'undefined' && elem != null.

However you choose, consider putting the check in a function like so

function existy (x) {
    return typeof (x) != 'undefined' && x != null;
}

If you don't know the variable is declared then continue with typeof (x) != 'undefined' && x != null;

Where you know the variable is declared but may not be existy, you could use

existy(elem) && doSomething(elem);

The variable you are checking may be a nested property sometimes. You can use prop || {} to go down the line checking existance to the property in question:

var exists = ((((existy(myObj).prop1||{}).prop2||{}).prop3||{})[1]||{}).prop4;

After each property use (...' || {}').nextProp so that a missing property won't throw an error.

Or you could use existy like existy(o) && existy(o.p) && existy(o.p.q) && doSomething(o.p.q)

How do getters and setters work?

1. The best getters / setters are smart.

Here's a javascript example from mozilla:

var o = { a:0 } // `o` is now a basic object

Object.defineProperty(o, "b", { 
    get: function () { 
        return this.a + 1; 
    } 
});

console.log(o.b) // Runs the getter, which yields a + 1 (which is 1)

I've used these A LOT because they are awesome. I would use it when getting fancy with my coding + animation. For example, make a setter that deals with an Number which displays that number on your webpage. When the setter is used it animates the old number to the new number using a tweener. If the initial number is 0 and you set it to 10 then you would see the numbers flip quickly from 0 to 10 over, let's say, half a second. Users love this stuff and it's fun to create.

2. Getters / setters in php

Example from sof

<?php
class MyClass {
  private $firstField;
  private $secondField;

  public function __get($property) {
    if (property_exists($this, $property)) {
      return $this->$property;
    }
  }

  public function __set($property, $value) {
    if (property_exists($this, $property)) {
      $this->$property = $value;
    }

    return $this;
  }
}
?>

citings:

How can I get the current date and time in the terminal and set a custom command in the terminal for it?

The command is date

To customise the output there are a myriad of options available, see date --help for a list.

For example, date '+%A %W %Y %X' gives Tuesday 34 2013 08:04:22 which is the name of the day of the week, the week number, the year and the time.

Google Maps: Set Center, Set Center Point and Set more points

Try using this code for v3:

gMap = new google.maps.Map(document.getElementById('map')); 
gMap.setZoom(13);      // This will trigger a zoom_changed on the map
gMap.setCenter(new google.maps.LatLng(37.4419, -122.1419));
gMap.setMapTypeId(google.maps.MapTypeId.ROADMAP);

How to rename a table in SQL Server?

Table Name

sp_rename 'db_name.old_table_name', 'new_table_name'

Column

sp_rename 'db_name.old_table_name.name' 'userName', 'COLUMN'

Index

sp_rename 'db_name.old_table_name.id', 'product_ID', 'INDEX'

also available for statics and datatypes

How to style readonly attribute with CSS?

There are a few ways to do this.

The first is the most widely used. It works on all major browsers.

input[readonly] {
 background-color: #dddddd;
}

While the one above will select all inputs with readonly attached, this one below will select only what you desire. Make sure to replace demo with whatever input type you want.

input[type="demo"]:read-only {
 background-color: #dddddd;
}

This is an alternate to the first, but it's not used a whole lot:

input:read-only {
 background-color: #dddddd;
}

The :read-only selector is supported in Chrome, Opera, and Safari. Firefox uses :-moz-read-only. IE doesn't support the :read-only selector.

You can also use input[readonly="readonly"], but this is pretty much the same as input[readonly], from my experience.

No input file specified

It worked for me..add on top of .htaccess file. It would disable FastCGI on godaddy shared hosting account.

Options +ExecCGI

addhandler x-httpd-php5-cgi .php

How to use JavaScript variables in jQuery selectors?

$("input").click(function(){
        var name = $(this).attr("name");
        $('input[name="' + name + '"]').hide();    
    });   

Also works with ID:

var id = $(this).attr("id");
$('input[id="' + id + '"]').hide();

when, (sometimes)

$('input#' + id).hide();

does not work, as it should.

You can even do both:

$('input[name="' + name + '"][id="' + id + '"]').hide();

Where are static variables stored in C and C++?

I don't believe there will be a collision. Using static at the file level (outside functions) marks the variable as local to the current compilation unit (file). It's never visible outside the current file so never has to have a name that can be used externally.

Using static inside a function is different - the variable is only visible to the function (whether static or not), it's just its value is preserved across calls to that function.

In effect, static does two different things depending on where it is. In both cases however, the variable visibility is limited in such a way that you can easily prevent namespace clashes when linking.

Having said that, I believe it would be stored in the DATA section, which tends to have variables that are initialized to values other than zero. This is, of course, an implementation detail, not something mandated by the standard - it only cares about behaviour, not how things are done under the covers.

throwing exceptions out of a destructor

Martin Ba (above) is on the right track- you architect differently for RELEASE and COMMIT logic.

For Release:

You should eat any errors. You're freeing memory, closing connections, etc. Nobody else in the system should ever SEE those things again, and you're handing back resources to the OS. If it looks like you need real error handling here, its likely a consequence of design flaws in your object model.

For Commit:

This is where you want the same kind of RAII wrapper objects that things like std::lock_guard are providing for mutexes. With those you don't put the commit logic in the dtor AT ALL. You have a dedicated API for it, then wrapper objects that will RAII commit it in THEIR dtors and handle the errors there. Remember, you can CATCH exceptions in a destructor just fine; its issuing them that's deadly. This also lets you implement policy and different error handling just by building a different wrapper (e.g. std::unique_lock vs. std::lock_guard), and ensures you won't forget to call the commit logic- which is the only half-way decent justification for putting it in a dtor in the 1st place.