Programs & Examples On #Wingdings

Tick symbol in HTML/XHTML

I run into the same problem and none of the suggestions worked (Firefox on Windows XP).

So I found a possible workaround using image data to display a little checkmark:

span:before {

Of course you can create your own checkmark image and use a converter to add it as data:image/gif. Hope this helps.

Filtering a data frame by values in a column

Try this:

subset(studentdata, Drink=='water')

that should do it.

MYSQL order by both Ascending and Descending sorting

You can do that in this way:

ORDER BY `products`.`product_category_id` DESC ,`naam` ASC

Have a look at ORDER BY Optimization

How to select current date in Hive SQL

To extract the year from current date


IBM Netezza

extract(year from now())



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

The easiest and fastest way, (but not the best), is to add a TextView with empty text attribute, like this


the background color must be the same at the LinearLayout, then you could use the padding property, like this


or whatever you need. Here is an example.

OpenCV - Saving images to a particular folder of choice

FOR MAC USERS if you are working with open cv

import cv2


Angular 2 How to redirect to 404 or other path if the path does not exist

As Angular moved on with the release, I faced this same issue. As per version 2.1.0 the Route interface looks like:

export interface Route {
    path?: string;
    pathMatch?: string;
    component?: Type<any>;
    redirectTo?: string;
    outlet?: string;
    canActivate?: any[];
    canActivateChild?: any[];
    canDeactivate?: any[];
    canLoad?: any[];
    data?: Data;
    resolve?: ResolveData;
    children?: Route[];
    loadChildren?: LoadChildren;

So my solutions was the following:

const routes: Routes = [
    { path: '', component: HomeComponent },
    { path: '404', component: NotFoundComponent },
    { path: '**', redirectTo: '404' }

Wait on the Database Engine recovery handle failed. Check the SQL server error log for potential causes

Root cause: Corrupted user profile of user account used to start database

The main thread here seems to be a corrupted user account profile for the account that is used to start the DB engine. This is the account that was specified for the "SQL Server Database" engine during installation. In the setup event log, it's also indicated by the following entry:


According to the link provided by @royki:

The root cause of this issue, in most cases, is that the profile of the user being used for the service account (in my case it was local system) is corrupted.

This would explain why other respondents had success after changing to different accounts:

  • bmjjr suggests changing to "NT AUTHORITY\NETWORK SERVICE"
  • comments to @bmjjr indicate different accounts "I used NT AUTHORITY\LOCAL SERVICE. That helped too"
  • @Julio Nobre had success with "NT Authority\System "

Fix: reset the corrupt user profile

To fix the user profile that's causing the error, follow the steps listed KB947215.

The main steps from KB947215 are summarized as follows:-

  1. Open regedit
  2. Navigate to HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList
  3. Navigate to the SID for the corrupted profile

    To find the SID, click on each SID GUID, review the value for the ProfileImagePath value, and see if it's the correct account. For system accounts, there's a different way to know the SID for the account that failed:

The main system account SIDs of interest are:

SID          Name               Also Known As
S-1-5-18     Local System       NT AUTHORITY\SYSTEM
S-1-5-19     LocalService       NT AUTHORITY\LOCAL SERVICE
S-1-5-20     NetworkService     NT AUTHORITY\NETWORK SERVICE

For information on additional SIDs, see Well-known security identifiers in Windows operating systems.

  1. If there are two entries (e.g. with a .bak) at the end for the SID in question, or the SID in question ends in .bak, ensure to follow carefully the steps in the KB947215 article.
  2. Reset the values for RefCount and State to be 0.
  3. Reboot.
  4. Retry the SQL Server installation.

What is a good practice to check if an environmental variable exists or not?

In case you want to check if multiple env variables are not set, you can do the following:

import os


    if var not in os.environ:
        raise EnvironmentError("Failed because {} is not set.".format(var))

VBA for filtering columns

Here's a different approach. The heart of it was created by turning on the Macro Recorder and filtering the columns per your specifications. Then there's a bit of code to copy the results. It will run faster than looping through each row and column:

Sub FilterAndCopy()
Dim LastRow As Long

With Worksheets("Sheet1")
    .Range("$A:$E").AutoFilter field:=1, Criteria1:="#N/A"
    .Range("$A:$E").AutoFilter field:=2, Criteria1:="=String1", Operator:=xlOr, Criteria2:="=string2"
    .Range("$A:$E").AutoFilter field:=3, Criteria1:=">0"
    .Range("$A:$E").AutoFilter field:=5, Criteria1:="Number"
    LastRow = .Range("A" & .Rows.Count).End(xlUp).Row
    .Range("A1:A" & LastRow).SpecialCells(xlCellTypeVisible).EntireRow.Copy _
End With
End Sub

As a side note, your code has more loops and counter variables than necessary. You wouldn't need to loop through the columns, just through the rows. You'd then check the various cells of interest in that row, much like you did.

python multithreading wait till all threads finished

Put the threads in a list and then use the Join method

 threads = []

 t = Thread(...)

 ...repeat as often as necessary...

 # Start all threads
 for x in threads:

 # Wait for all of them to finish
 for x in threads:

Why doesn't list have safe "get" method like dictionary?

Probably because it just didn't make much sense for list semantics. However, you can easily create your own by subclassing.

class safelist(list):
    def get(self, index, default=None):
            return self.__getitem__(index)
        except IndexError:
            return default

def _test():
    l = safelist(range(10))
    print l.get(20, "oops")

if __name__ == "__main__":

How to fix a header on scroll

Just building on Rich's answer, which uses offset.

I modified this as follows:

  • There was no need for the var $sticky in Rich's example, it wasn't doing anything
  • I've moved the offset check into a separate function, and called it on document ready as well as on scroll so if the page refreshes with the scroll half-way down the page, it resizes straight-away without having to wait for a scroll trigger

        var offset = $( "#header" ).offset();
        $(window).scroll(function() {
        function checkOffset() {
            if ( $(document).scrollTop() >{
            } else {

Use String.split() with multiple delimiters

I think you need to include the regex OR operator:

String[]tokens = pdfName.split("-|\\.");

What you have will match:
[DASH followed by DOT together] -.
[DASH or DOT any of them] - or .

OpenCV in Android Studio

This worked for me and was as easy as adding a gradle dependancy:

The one caveat being that I had to use a hardware debugging device as arm emulators were running too slow for me (as AVD Manager says they will), and, as described at the repo README, this version does not include x86 or x86_64 support.

It seems to build and the suggested test:

static {

spits out a bunch of output that looks about right to me.

Slide right to left Android Animations

You can do Your own Animation style as an xml file like this(put it in anim folder):

left to right:

  <set xmlns:android=""
        <translate android:fromXDelta="-100%" android:toXDelta="0%"
         android:fromYDelta="0%" android:toYDelta="0%"

right to left:

    <set xmlns:android=""
        android:fromXDelta="0%" android:toXDelta="100%"
        android:fromYDelta="0%" android:toYDelta="0%"
        android:duration="500" />

here You can set Your own values at duration, maybe it depends on the phone model how the animation will look like, try some values out if it looks not good.

and then You can call it in Your activity:

     Intent animActivity = new Intent(this,YourStartAfterAnimActivity.class);

      overridePendingTransition(R.anim.your_left_to_right, R.anim.your_right_to_left);

Conditional Binding: if let error – Initializer for conditional binding must have Optional type

if let/if var optional binding only works when the result of the right side of the expression is an optional. If the result of the right side is not an optional, you can not use this optional binding. The point of this optional binding is to check for nil and only use the variable if it's non-nil.

In your case, the tableView parameter is declared as the non-optional type UITableView. It is guaranteed to never be nil. So optional binding here is unnecessary.

func tableView(tableView: UITableView, commitEditingStyle editingStyle:UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
    if editingStyle == .Delete {
        // Delete the row from the data source
        tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)

All we have to do is get rid of the if let and change any occurrences of tv within it to just tableView.

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

(reposting this answer)

You can use encoding/binary's ByteOrder to do this for 16, 32, 64 bit types


package main

import "fmt"
import "encoding/binary"

func main() {
    var mySlice = []byte{244, 244, 244, 244, 244, 244, 244, 244}
    data := binary.BigEndian.Uint64(mySlice)

expand/collapse table rows with JQuery

The easiest way to achieve this, without changing the HTML table-based structure, is to use a class-name on the tr elements containing a header, such as .header, to give:

<table border="0">
  <tr class="header">
    <td colspan="2">Header</td>
  <tr class="header">
    <td colspan="2">Header</td>

And the jQuery:

// bind a click-handler to the 'tr' elements with the 'header' class-name:
    /* get all the subsequent 'tr' elements until the next 'tr.header',
       set the 'display' property to 'none' (if they're visible), to 'table-row'
       if they're not: */
    $(this).nextUntil('tr.header').css('display', function(i,v){
        return === 'table-row' ? 'none' : 'table-row';

JS Fiddle demo.

In the linked demo I've used CSS to hide the tr elements that don't have the header class-name; in practice though (despite the relative rarity of users with JavaScript disabled) I'd suggest using JavaScript to add the relevant class-names, hiding and showing as appropriate:

// hide all 'tr' elements, then filter them to find...
$('tr').hide().filter(function () {
    // only those 'tr' elements that have 'td' elements with a 'colspan' attribute:
    return $(this).find('td[colspan]').length;
    // add the 'header' class to those found 'tr' elements
    // set the display of those elements to 'table-row':
  .css('display', 'table-row')
    // bind the click-handler (as above)
  .click(function () {
    $(this).nextUntil('tr.header').css('display', function (i, v) {
        return === 'table-row' ? 'none' : 'table-row';

JS Fiddle demo.


How do you change video src using jQuery?

The easiest way is using autoplay.

<video autoplay></video>

When you change src through javascript you don't need to mention load().

How to restart tomcat 6 in ubuntu

if you are using extracted tomcat then, and are two script located in TOMCAT/bin/ to start and shutdown tomcat, You could use that

if tomcat is installed then

/etc/init.d/tomcat5.5 start
/etc/init.d/tomcat5.5 stop
/etc/init.d/tomcat5.5 restart

How to write :hover condition for a:before and a:after?

Write a:hover::before instead of a::before:hover: example.

Catch multiple exceptions in one line (except block)

How do I catch multiple exceptions in one line (except block)

Do this:

except (SpecificErrorOne, SpecificErrorTwo) as error:
    handle(error) # might log or have some other default behavior...

The parentheses are required due to older syntax that used the commas to assign the error object to a name. The as keyword is used for the assignment. You can use any name for the error object, I prefer error personally.

Best Practice

To do this in a manner currently and forward compatible with Python, you need to separate the Exceptions with commas and wrap them with parentheses to differentiate from earlier syntax that assigned the exception instance to a variable name by following the Exception type to be caught with a comma.

Here's an example of simple usage:

import sys

except (KeyboardInterrupt, EOFError): # the parens are necessary

I'm specifying only these exceptions to avoid hiding bugs, which if I encounter I expect the full stack trace from.

This is documented here:

You can assign the exception to a variable, (e is common, but you might prefer a more verbose variable if you have long exception handling or your IDE only highlights selections larger than that, as mine does.) The instance has an args attribute. Here is an example:

import sys

except (KeyboardInterrupt, EOFError) as err: 

Note that in Python 3, the err object falls out of scope when the except block is concluded.


You may see code that assigns the error with a comma. This usage, the only form available in Python 2.5 and earlier, is deprecated, and if you wish your code to be forward compatible in Python 3, you should update the syntax to use the new form:

import sys

except (KeyboardInterrupt, EOFError), err: # don't do this in Python 2.6+
    print err
    print err.args

If you see the comma name assignment in your codebase, and you're using Python 2.5 or higher, switch to the new way of doing it so your code remains compatible when you upgrade.

The suppress context manager

The accepted answer is really 4 lines of code, minimum:

except (IDontLikeYouException, YouAreBeingMeanException) as e:

The try, except, pass lines can be handled in a single line with the suppress context manager, available in Python 3.4:

from contextlib import suppress

with suppress(IDontLikeYouException, YouAreBeingMeanException):

So when you want to pass on certain exceptions, use suppress.

Running .sh scripts in Git Bash

I had a similar problem, but I was getting an error message

cannot execute binary file

I discovered that the filename contained non-ASCII characters. When those were fixed, the script ran fine with ./

List vs tuple, when to use each?

The first thing you need to decide is whether the data structure needs to be mutable or not. As has been mentioned, lists are mutable, tuples are not. This also means that tuples can be used for dictionary keys, wheres lists cannot.

In my experience, tuples are generally used where order and position is meaningful and consistant. For example, in creating a data structure for a choose your own adventure game, I chose to use tuples instead of lists because the position in the tuple was meaningful. Here is one example from that data structure:

pages = {'foyer': {'text' : "some text", 
          'choices' : [('open the door', 'rainbow'),
                     ('go left into the kitchen', 'bottomless pit'),
                     ('stay put','foyer2')]},}

The first position in the tuple is the choice displayed to the user when they play the game and the second position is the key of the page that choice goes to and this is consistent for all pages.

Tuples are also more memory efficient than lists, though I'm not sure when that benefit becomes apparent.

Also check out the chapters on lists and tuples in Think Python.

How to use patterns in a case statement?

I don't think you can use braces.

According to the Bash manual about case in Conditional Constructs.

Each pattern undergoes tilde expansion, parameter expansion, command substitution, and arithmetic expansion.

Nothing about Brace Expansion unfortunately.

So you'd have to do something like this:

case $1 in
        # You should have a default one too.

How to select first parent DIV using jQuery?

two of the best options are



and of course you can find the class attr by



how to set the query timeout from SQL connection string

Only from code:

namespace xxx.DsXxxTableAdapters {_x000D_
    partial class ZzzTableAdapter_x000D_
        public void SetTimeout(int timeout)_x000D_
            if (this.Adapter.DeleteCommand != null) { this.Adapter.DeleteCommand.CommandTimeout = timeout; }_x000D_
            if (this.Adapter.InsertCommand != null) { this.Adapter.InsertCommand.CommandTimeout = timeout; }_x000D_
            if (this.Adapter.UpdateCommand != null) { this.Adapter.UpdateCommand.CommandTimeout = timeout; }_x000D_
            if (this._commandCollection == null) { this.InitCommandCollection(); }_x000D_
            if (this._commandCollection != null)_x000D_
                foreach (System.Data.SqlClient.SqlCommand item in this._commandCollection)_x000D_
                    if (item != null)_x000D_
                    { item.CommandTimeout = timeout; }_x000D_

How do you remove columns from a data.frame?


# exclude variables v1, v2, v3
myvars <- names(mydata) %in% c("v1", "v2", "v3") 
newdata <- mydata[!myvars]

# exclude 3rd and 5th variable 
newdata <- mydata[c(-3,-5)]

# delete variables v3 and v5
mydata$v3 <- mydata$v5 <- NULL

Thought it was really clever make a list of "not to include"

Create an empty data.frame

I keep this function handy for whenever I need it, and change the column names and classes to suit the use case:

make_df <- function() { data.frame(name=character(),
                     stringsAsFactors = F)

[1] name       profile    sector     type       year_range link      
<0 rows> (or 0-length row.names)

HTML-encoding lost when attribute read from input field

FWIW, the encoding is not being lost. The encoding is used by the markup parser (browser) during the page load. Once the source is read and parsed and the browser has the DOM loaded into memory, the encoding has been parsed into what it represents. So by the time your JS is execute to read anything in memory, the char it gets is what the encoding represented.

I may be operating strictly on semantics here, but I wanted you to understand the purpose of encoding. The word "lost" makes it sound like something isn't working like it should.

What integer hash function are good that accepts an integer hash key?

This page lists some simple hash functions that tend to decently in general, but any simple hash has pathological cases where it doesn't work well.

Filter Excel pivot table using VBA

Configure the pivot table so that it is like this:

enter image description here

Your code can simply work on range("B1") now and the pivot table will be filtered to you required SavedFamilyCode

Sub FilterPivotTable()
Application.ScreenUpdating = False
    ActiveSheet.Range("B1") = "K123224"
Application.ScreenUpdating = True
End Sub

Plotting with C#

There is OxyPlot which I recommend. It has packages for WPF, Metro, Silverlight, Windows Forms, Avalonia UI, XWT. Besides graphics it can export to SVG, PDF, Open XML, etc. And it even supports Mono and Xamarin for Android and iOS. It is actively developed too.

There is also a new (at least for me) open source .NET plotting library called Live-Charts. The plots are pretty interactive. Library suports WPF, WinForms and UWP. Xamarin is planned. The design is made towards MV* patterns. But @Pawel Audionysos suggests not such a good performance of Live-Charts WPF.

How to change the datetime format in pandas

You can try this it'll convert the date format to DD-MM-YYYY:

df['DOB'] = pd.to_datetime(df['DOB'], dayfirst = True)

Http Get using Android HttpURLConnection

I have created with callBack(delegate) response to Activity class.

public class WebService extends AsyncTask<String, Void, String> {

    private Context mContext;
    private OnTaskDoneListener onTaskDoneListener;
    private String urlStr = "";

    public WebService(Context context, String url, OnTaskDoneListener onTaskDoneListener) {
        this.mContext = context;
        this.urlStr = url;
        this.onTaskDoneListener = onTaskDoneListener;

    protected String doInBackground(String... params) {
        try {

            URL mUrl = new URL(urlStr);
            HttpURLConnection httpConnection = (HttpURLConnection) mUrl.openConnection();
            httpConnection.setRequestProperty("Content-length", "0");


            int responseCode = httpConnection.getResponseCode();

            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader br = new BufferedReader(new InputStreamReader(httpConnection.getInputStream()));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = br.readLine()) != null) {
                    sb.append(line + "\n");
                return sb.toString();
        } catch (IOException e) {
        } catch (Exception ex) {
        return null;

    protected void onPostExecute(String s) {

        if (onTaskDoneListener != null && s != null) {
        } else


public interface OnTaskDoneListener {
    void onTaskDone(String responseData);

    void onError();

You can modify according to your needs. It's for get

Excel Define a range based on a cell value

You can also use OFFSET:


It moves the range $A$10 up by $B$1-1 (becomes $A$6 ($A$5)) and then resizes the range to $B$1 rows (becomes $A$6:$A$10 ($A$5:$A$10))

in_array() and multidimensional array

Great function, but it didnt work for me until i added the if($found) { break; } to the elseif

function in_array_r($needle, $haystack) {
    $found = false;
    foreach ($haystack as $item) {
    if ($item === $needle) { 
            $found = true; 
        } elseif (is_array($item)) {
            $found = in_array_r($needle, $item); 
            if($found) { 
    return $found;

Is there a way to retrieve the view definition from a SQL Server using plain ADO?

SELECT definition, uses_ansi_nulls, uses_quoted_identifier, is_schema_bound  
FROM sys.sql_modules  
WHERE object_id = OBJECT_ID('your View Name');  

Best way to Format a Double value to 2 Decimal places

No, there is no better way.

Actually you have an error in your pattern. What you want is:

DecimalFormat df = new DecimalFormat("#.00"); 

Note the "00", meaning exactly two decimal places.

If you use "#.##" (# means "optional" digit), it will drop trailing zeroes - ie new DecimalFormat("#.##").format(3.0d); prints just "3", not "3.00".

Does VBScript have a substring() function?

Yes, Mid.

Dim sub_str
sub_str = Mid(source_str, 10, 5)

The first parameter is the source string, the second is the start index, and the third is the length.

@bobobobo: Note that VBScript strings are 1-based, not 0-based. Passing 0 as an argument to Mid results in "invalid procedure call or argument Mid".

How to Refresh a Component in Angular

Other way to refresh (hard way) a page in angular 2 like this it's look like f5

import { Location } from '@angular/common';

constructor(private location: Location) {}

pageRefresh() {

The target principal name is incorrect. Cannot generate SSPI context

Login to both your SQL Box and your client and type:

ipconfig /flushdns
nbtstat -R

If that doesn't work, renew your DHCP on your client machine... This work for 2 PCs in our office.

Set The Window Position of an application via command line

I just found this question while on a quest to do the same thing.

After some experimenting I came across an answer that works the way the OQ would want and is simple as heck, but not very general purpose.

Create a shortcut on your desktop or elsewhere (you can use the create-shortcut helper from the right-click menu), set it to run the program "cmd.exe" and run it. When the window opens, position it where you want your window to be. To save that position, bring up the properties menu and hit "Save".

Now if you want you can also set other properties like colors and I highly recommend changing the buffer to be a width of 120-240 and the height to 9999 and enable quick edit mode (why aren't these the defaults!?!)

Now you have a shortcut that will work. Make one of these for each CMD window you want opened at a different location.

Now for the trick, the windows CMD START command can run shortcuts. You can't programmatically reposition the windows before launch, but at least it comes up where you want and you can launch it (and others) from a batch file or another program.

Using a shortcut with cmd /c you can create one shortcut that can launch ALL your links at once by using a command that looks like this:

cmd /c "start cmd_link1 && start cmd_link2 && start cmd_link3"

This will open up all your command windows to your favorite positions and individually set properties like foreground color, background color, font, administrator mode, quick-edit mode, etc... with a single click. Now move that one "link" into your startup folder and you've got an auto-state restore with no external programs at all.

This is a pretty straight-forward solution. It's not general purpose, but I believe it will solve the problem that most people reading this question are trying to solve.

I did this recently so I'll post my cmd file here:

cd /d C:\shortucts
for %%f in (*.lnk *.rdp *.url) do start %%f

Late EDIT: I didn't mention that if the original cmd /c command is run elevated then every one of your windows can (if elevation was selected) start elevated without individually re-prompting you. This has been really handy as I start 3 cmd windows and 3 other apps all elevated every time I start my computer.

How to replace specific values in a oracle database column?

If you need to update the value in a particular table:



  TABLE-NAME         - The name of the table being updated
  COLUMN-NAME        - The name of the column being updated
  STRING-TO-REPLACE  - The value to replace
  REPLACEMENT-STRING - The replacement

How to launch an application from a browser?

You can't really "launch an application" in the true sense. You can as you indicated ask the user to open a document (ie a PDF) and windows will attempt to use the default app for that file type. Many applications have a way to do this.

For example you can save RDP connections as a .rdp file. Putting a link on your site to something like this should allow the user to launch right into an RDP session:

<a href="MyServer1.rdp">Server 1</a>

Android charting libraries

  • Achartengine: I have used this. Although for real time graph this might not give good performance if you do not tweak properly.

How can I change the text inside my <span> with jQuery?


  • return the element's text content: $(selector).text()
  • set the element's text content to content: $(selector).text(content)
  • set the element's text content using a callback function: $(selector).text(function(index, curContent))

JQuery - Change the text of a span element

How to remove default mouse-over effect on WPF buttons?

You need to create your own custom button template to have full control over the appearance in all states. Here's a tutorial.

Where does Anaconda Python install on Windows?

With Anaconda prompt python is available, but on any other command window, python is an unknown program. Apparently Anaconda installation does not update the path for python executable.

What is the simplest way to write the contents of a StringBuilder to a text file in .NET 1.1?

No need for a StringBuilder:

string path = @"c:\hereIAm.txt";
if (!File.Exists(path)) 
    // Create a file to write to.
    using (StreamWriter sw = File.CreateText(path)) 

But of course you can use the StringBuilder to create all lines and write them to the file at once.


StreamWriter.Write Method (String) (.NET Framework 1.1)

Writing Text to a File (.NET Framework 1.1)

Sending images using Http Post

The loopj library can be used straight-forward for this purpose:

SyncHttpClient client = new SyncHttpClient();
RequestParams params = new RequestParams();
params.put("text", "some string");
params.put("image", new File(imagePath));"", params, new TextHttpResponseHandler() {
  public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
    // error handling

  public void onSuccess(int statusCode, Header[] headers, String responseString) {
    // success

Html.HiddenFor value property not getting set

I believe there is a simpler solution. You must use Html.Hidden instead of Html.HiddenFor. Look:

@Html.Hidden("CRN", ViewData["crn"]);

This will create an INPUT tag of type="hidden", with id="CRN" and name="CRN", and the correct value inside the value attribute.

Hope it helps!

Javascript Confirm popup Yes, No button instead of OK and Cancel

The featured (but small and simple) library you can use is JSDialog:

Here is a sample for creating a dialog with Yes and No buttons:

    "Save document before it will be closed?\nIf you press `No` all unsaved changes will be lost.",
    function(result) {
        // check result here

JS Dialog demo screenshot

Setting up Gradle for api 26 (Android)

You could add google() to repositories block

allprojects {
    repositories {
        maven {
            url ''

        maven {
            url ""

How can I send an email by Java application using GMail, Yahoo, or Hotmail?

Something like this (sounds like you just need to change your SMTP server):

String host = "";
String from = "user name";
Properties props = System.getProperties();
props.put("", host);
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", "asdfgh");
props.put("mail.smtp.port", "587"); // 587 is the port number of yahoo mail
props.put("mail.smtp.auth", "true");

Session session = Session.getDefaultInstance(props, null);
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));

InternetAddress[] to_address = new InternetAddress[to.length];
int i = 0;
// To get the array of addresses
while (to[i] != null) {
    to_address[i] = new InternetAddress(to[i]);
i = 0;
while (to_address[i] != null) {

    message.addRecipient(Message.RecipientType.TO, to_address[i]);
message.setSubject("sending in a group");
message.setText("Welcome to JavaMail");
// alternately, to send HTML mail:
// message.setContent("<p>Welcome to JavaMail</p>", "text/html");
Transport transport = session.getTransport("smtp");
transport.connect("", "user name", "asdfgh");
transport.sendMessage(message, message.getAllRecipients());

How to mark a method as obsolete or deprecated?

The shortest way is by adding the ObsoleteAttribute as an attribute to the method. Make sure to include an appropriate explanation:

[Obsolete("Method1 is deprecated, please use Method2 instead.")]
public void Method1()
{ … }

You can also cause the compilation to fail, treating the usage of the method as an error instead of warning, if the method is called from somewhere in code like this:

[Obsolete("Method1 is deprecated, please use Method2 instead.", true)]

Open a link in browser with java button?

A solution without the Desktop environment is BrowserLauncher2. This solution is more general as on Linux, Desktop is not always available.

The lenghty answer is posted at

Assign output of a program to a variable using a MS batch file

You could use a batch macro for simple capturing of command outputs, a bit like the behaviour of the bash shell.

The usage of the macro is simple and looks like

%$set% VAR=application arg1 arg2

And it works even with pipes

%$set% allDrives="wmic logicaldisk get name /value | findstr "Name""

The macro uses the variable like an array and stores each line in a separate index.
In the sample of %$set% allDrives="wmic logicaldisk there will the following variables created:

allDrives=<contains the complete text with line feeds>

To use it, it's not important to understand how the macro itself works.

The full example

@echo off

call :initMacro

%$set% ipOutput="ipconfig"
call :ShowVariable ipOutput
echo First line is %ipOutput[0]%

%$set% driveNames="wmic logicaldisk get name /value | findstr "Name""
call :ShowVariable driveNames

exit /b

setlocal EnableDelayedExpansion
for /L %%n in (0 1 !%~1.max!) do (
    echo %%n: !%~1[%%n]!
exit /b

if "!!"=="" (
    echo ERROR: Delayed Expansion must be disabled while defining macros
    (goto) 2>nul
    (goto) 2>nul
(set LF=^
(set \n=^^^

set $set=FOR /L %%N in (1 1 2) dO IF %%N==2 ( %\n%
    setlocal EnableDelayedExpansion                                 %\n%
    for /f "tokens=1,* delims== " %%1 in ("!argv!") do (            %\n%
        endlocal                                                    %\n%
        endlocal                                                    %\n%
        set "%%~1.Len=0"                                            %\n%
        set "%%~1="                                                 %\n%
        if "!!"=="" (                                               %\n%
            %= Used if delayed expansion is enabled =%              %\n%
                setlocal DisableDelayedExpansion                    %\n%
                for /F "delims=" %%O in ('"%%~2 | findstr /N ^^"') do ( %\n%
                if "!!" NEQ "" (                                    %\n%
                    endlocal                                        %\n%
                    )                                               %\n%
                setlocal DisableDelayedExpansion                    %\n%
                set "line=%%O"                                      %\n%
                setlocal EnableDelayedExpansion                     %\n%
                set pathExt=:                                       %\n%
                set path=;                                          %\n%
                set "line=!line:^=^^!"                              %\n%
                set "line=!line:"=q"^""!"                           %\n%
                call set "line=%%line:^!=q""^!%%"                   %\n%
                set "line=!line:q""=^!"                             %\n%
                set "line="!line:*:=!""                             %\n%
                for /F %%C in ("!%%~1.Len!") do (                   %\n%
                    FOR /F "delims=" %%L in ("!line!") Do (         %\n%
                        endlocal                                    %\n%
                        endlocal                                    %\n%
                        set "%%~1[%%C]=%%~L" !                      %\n%
                        if %%C == 0 (                               %\n%
                            set "%%~1=%%~L" !                       %\n%
                        ) ELSE (                                    %\n%
                            set "%%~1=!%%~1!!LF!%%~L" !             %\n%
                        )                                           %\n%
                    )                                               %\n%
                    set /a %%~1.Len+=1                              %\n%
                )                                                   %\n%
            )                                                       %\n%
        ) ELSE (                                                    %\n%
            %= Used if delayed expansion is disabled =%             %\n%
            for /F "delims=" %%O in ('"%%~2 | findstr /N ^^"') do ( %\n%
                setlocal DisableDelayedExpansion                    %\n%
                set "line=%%O"                                      %\n%
                setlocal EnableDelayedExpansion                     %\n%
                set "line="!line:*:=!""                             %\n%
                for /F %%C in ("!%%~1.Len!") DO (                   %\n%
                    FOR /F "delims=" %%L in ("!line!") DO (         %\n%
                        endlocal                                    %\n%
                        endlocal                                    %\n%
                        set "%%~1[%%C]=%%~L"                        %\n%
                    )                                               %\n%
                    set /a %%~1.Len+=1                              %\n%
                )                                                   %\n%
            )                                                       %\n%
        )                                                           %\n%
        set /a %%~1.Max=%%~1.Len-1                                  %\n%
)                                                                   %\n%
    ) else setlocal DisableDelayedExpansion^&set argv=

goto :eof

How to get Spinner selected item value to string?

By implementing the SpinnerAdapter for your adapter object i use interested.getItem(i).toString()

how to put image in center of html page?


X is image width,
Y is image height,


img {
    position: absolute;
    top: 50%;
    left: 50%;
    margin-left: -(X/2)px;
    margin-top: -(Y/2)px;

But keep in mind this solution is valid only if the only element on your site will be this image. I suppose that's the case here.

Using this method gives you the benefit of fluidity. It won't matter how big (or small) someone's screen is. The image will always stay in the middle.

Radio Buttons ng-checked with ng-model

[Personal Option] Avoiding using $scope, based on John Papa Angular Style Guide

so my idea is take advantage of the current model:

  'use strict';_x000D_
   var app = angular.module('way', [])_x000D_
   app.controller('Decision', Decision);_x000D_
   Decision.$inject = [];     _x000D_
   function Decision(){_x000D_
     var vm = this;_x000D_
     vm.checkItOut = _register;_x000D_
     function _register(newOption){_x000D_
       console.log('should I stay or should I go');_x000D_
       console.log(newOption);  _x000D_
<script src=""></script>_x000D_
<script src=""></script>_x000D_
<div ng-app="way">_x000D_
  <div ng-controller="Decision as vm">_x000D_
    <form name="myCheckboxTest" ng-submit="vm.checkItOut(decision)">_x000D_
 <label class="radio-inline">_x000D_
  <input type="radio" name="option" ng-model="decision.myWay"_x000D_
                           ng-value="false" ng-checked="!decision.myWay"> Should I stay?_x000D_
                <label class="radio-inline">_x000D_
                    <input type="radio" name="option" ng-value="true"_x000D_
                           ng-model="decision.myWay" > Should I go?_x000D_

I hope I could help ;)

Is there a difference between `continue` and `pass` in a for loop in python?

pass could be used in scenarios when you need some empty functions, classes or loops for future implementations, and there's no requirement of executing any code.
continue is used in scenarios when no when some condition has met within a loop and you need to skip the current iteration and move to the next one.

How to increment a number by 2 in a PHP For Loop

Another simple solution with +=:

$y = 1;

for ($x = $y; $x <= 15; $y++) {
  printf("The number of first paragraph is: $y <br>");
  printf("The number of second paragraph is: $x+=2 <br>");

Sites not accepting wget user agent header

It seems Yahoo server does some heuristic based on User-Agent in a case Accept header is set to */*.

Accept: text/html

did the trick for me.


wget  --header="Accept: text/html" --user-agent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:21.0) Gecko/20100101 Firefox/21.0"

Note: if you don't declare Accept header then wget automatically adds Accept:*/* which means give me anything you have.

Permission denied (publickey,keyboard-interactive)

The server first tries to authenticate you by public key. That doesn't work (I guess you haven't set one up), so it then falls back to 'keyboard-interactive'. It should then ask you for a password, which presumably you're not getting right. Did you see a password prompt?

How does a hash table work?

Usage and Lingo:

  1. Hash tables are used to quickly store and retrieve data (or records).
  2. Records are stored in buckets using hash keys
  3. Hash keys are calculated by applying a hashing algorithm to a chosen value (the key value) contained within the record. This chosen value must be a common value to all the records.
  4. Each bucket can have multiple records which are organized in a particular order.

Real World Example:

Hash & Co., founded in 1803 and lacking any computer technology had a total of 300 filing cabinets to keep the detailed information (the records) for their approximately 30,000 clients. Each file folder were clearly identified with its client number, a unique number from 0 to 29,999.

The filing clerks of that time had to quickly fetch and store client records for the working staff. The staff had decided that it would be more efficient to use a hashing methodology to store and retrieve their records.

To file a client record, filing clerks would use the unique client number written on the folder. Using this client number, they would modulate the hash key by 300 in order to identify the filing cabinet it is contained in. When they opened the filing cabinet they would discover that it contained many folders ordered by client number. After identifying the correct location, they would simply slip it in.

To retrieve a client record, filing clerks would be given a client number on a slip of paper. Using this unique client number (the hash key), they would modulate it by 300 in order to determine which filing cabinet had the clients folder. When they opened the filing cabinet they would discover that it contained many folders ordered by client number. Searching through the records they would quickly find the client folder and retrieve it.

In our real-world example, our buckets are filing cabinets and our records are file folders.

An important thing to remember is that computers (and their algorithms) deal with numbers better than with strings. So accessing a large array using an index is significantly much faster than accessing sequentially.

As Simon has mentioned which I believe to be very important is that the hashing part is to transform a large space (of arbitrary length, usually strings, etc) and mapping it to a small space (of known size, usually numbers) for indexing. This if very important to remember!

So in the example above, the 30,000 possible clients or so are mapped to a smaller space.

The main idea in this is to divide your entire data set into segments as to speed up the actual searching which is usually time consuming. In our example above, each of the 300 filing cabinet would (statistically) contain about 100 records. Searching (regardless the order) through 100 records is much faster than having to deal with 30,000.

You may have noticed that some actually already do this. But instead of devising a hashing methodology to generate a hash key, they will in most cases simply use the first letter of the last name. So if you have 26 filing cabinets each containing a letter from A to Z, you in theory have just segmented your data and enhanced the filing and retrieval process.

Hope this helps,


C# Encoding a text string with line breaks

Yes - it means you're using \n as the line break instead of \r\n. Notepad only understands the latter.

(Note that Environment.NewLine suggested by others is fine if you want the platform default - but if you're serving from Mono and definitely want \r\n, you should specify it explicitly.)

How to calculate moving average without keeping the count and data-total?

You can simply do:

double approxRollingAverage (double avg, double new_sample) {

    avg -= avg / N;
    avg += new_sample / N;

    return avg;

Where N is the number of samples where you want to average over. Note that this approximation is equivalent to an exponential moving average. See: Calculate rolling / moving average in C++

What is Teredo Tunneling Pseudo-Interface?

Unless you have some kind of really weird problem, keep it. The number of IPv6 sites is very small, but there are some and it will let you get to them even if you're at an IPv4 only location.

If it is causing you a problem, it's best to fix it. I've seen a number of people recommending removing it to solve problems. However, they're not actually solving the root cause of the issue. In all the cases I've seen, removing Teredo just happens to cause a side-effect that fixes their problem... :)

How can I debug my JavaScript code?

If you are using Visual Studio, just put debugger; above the code you want to debug. During execution the control will pause at that place, and you can debug step by step from there on.

EXEC sp_executesql with multiple parameters

maybe this help :

@statement AS NVARCHAR(MAX)
,@text1 varchar(50)='hello'
,@text2 varchar(50)='world'

set @statement = '
select '''+@text1+''' + '' beautifull '' + ''' + @text2 + ''' 
exec sp_executesql @statement;

this is same as below :

select @text1 + ' beautifull ' + @text2

Multiple arguments to function called by pthread_create()?

I have the same question as the original poster, Michael.

However I have tried to apply the answers submitted for the original code without success

After some trial and error, here is my version of the code that works (or at least works for me!). And if you look closely, you will note that it is different to the earlier solutions posted.

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

struct arg_struct
   int arg1;
   int arg2;
} *args;

void *print_the_arguments(void *arguments)
   struct arg_struct *args = arguments;
   printf("%d\n", args->arg1);
   printf("%d\n", args->arg2);
   return NULL;

int main()
   pthread_t some_thread;
   args = malloc(sizeof(struct arg_struct) * 1);

   args->arg1 = 5;
   args->arg2 = 7;

   printf("%d\n", args->arg1);
   printf("%d\n", args->arg2);

   if (pthread_create(&some_thread, NULL, &print_the_arguments, args) != 0)
      return -1;

   return pthread_join(some_thread, NULL); /* Wait until thread is finished */

Two Divs on the same row and center align both of them

Could this do for you? Check my JSFiddle

And the code:


<div class="container">
    <div class="div1">Div 1</div>
    <div class="div2">Div 2</div>


div.container {
    background-color: #FF0000;
    margin: auto;   
    width: 304px;

div.div1 {
    border: 1px solid #000;
    float: left;
    width: 150px;

div.div2 {
    border: 1px solid red;
    float: left;
    width: 150px;

How do I remove/delete a folder that is not empty?

You can use os.system command for simplicity:

import os
os.system("rm -rf dirname")

As obvious, it actually invokes system terminal to accomplish this task.

RedirectToAction with parameter

You can pass the id as part of the routeValues parameter of the RedirectToAction() method.

return RedirectToAction("Action", new { id = 99 });

This will cause a redirect to Site/Controller/Action/99. No need for temp or any kind of view data.

batch file Copy files with certain extensions from multiple directories into one directory

Brandon, short and sweet. Also flexible.

set dSource=C:\Main directory\sub directory
set dTarget=D:\Documents
set fType=*.doc
for /f "delims=" %%f in ('dir /a-d /b /s "%dSource%\%fType%"') do (
    copy /V "%%f" "%dTarget%\" 2>nul

Hope this helps.

I would add some checks after the copy (using '||') but i'm not sure how "copy /v" reacts when it encounters an error.

you may want to try this:

copy /V "%%f" "%dTarget%\" 2>nul|| echo En error occured copying "%%F".&& exit /b 1

As the copy line. let me know if you get something out of it (in no position to test a copy failure atm..)

CSS3 Transparency + Gradient

Yes. You can use rgba in both webkit and moz gradient declarations:

/* webkit example */
background-image: -webkit-gradient(
  linear, left top, left bottom, from(rgba(50,50,50,0.8)),
  to(rgba(80,80,80,0.2)), color-stop(.5,#333333)


/* mozilla example - FF3.6+ */
background-image: -moz-linear-gradient(
  rgba(255, 255, 255, 0.7) 0%, rgba(255, 255, 255, 0) 95%


Apparently you can even do this in IE, using an odd "extended hex" syntax. The first pair (in the example 55) refers to the level of opacity:

/* approximately a 33% opacity on blue */
filter: progid:DXImageTransform.Microsoft.gradient(
  startColorstr=#550000FF, endColorstr=#550000FF

/* IE8 uses -ms-filter for whatever reason... */
-ms-filter: progid:DXImageTransform.Microsoft.gradient(
  startColorstr=#550000FF, endColorstr=#550000FF


Java - Abstract class to contain variables?

I would have thought that something like this would be much better, since you're adding a variable, so why not restrict access and make it cleaner? Your getter/setters should do what they say on the tin.

public abstract class ExternalScript extends Script {

    private String source;

    public void setSource(String file) {
        source = file;

    public String getSource() {
        return source;

Bringing this back to the question, do you ever bother looking at where the getter/setter code is when reading it? If they all do getting and setting then you don't need to worry about what the function 'does' when reading the code. There are a few other reasons to think about too:

  • If source was protected (so accessible by subclasses) then code gets messy: who's changing the variables? When it's an object it then becomes hard when you need to refactor, whereas a method tends to make this step easier.
  • If your getter/setter methods aren't getting and setting, then describe them as something else.

Always think whether your class is really a different thing or not, and that should help decide whether you need anything more.

How to convert string to boolean php

A simple way is to check against an array of values that you consider true.

$wannabebool = "false";
$isTrue = ["true",1,"yes","ok","wahr"];
$bool = in_array(strtolower($wannabebool),$isTrue);

What is the difference between Swing and AWT?

Swing vs AWT. Basically AWT came first and is a set of heavyweight UI components (meaning they are wrappers for operating system objects) whereas Swing built on top of AWT with a richer set of lightweight components.

Any serious Java UI work is done in Swing not AWT, which was primarily used for applets.

Adding quotes to a string in VBScript

You can escape by doubling the quotes

g="abcd """ & a & """"

or write an explicit chr() call

g="abcd " & chr(34) & a & chr(34)

Convert an integer to a byte array

Sorry, this might be a bit late. But I think I found a better implementation on the go docs.

buf := new(bytes.Buffer)
var num uint16 = 1234
err := binary.Write(buf, binary.LittleEndian, num)
if err != nil {
    fmt.Println("binary.Write failed:", err)
fmt.Printf("% x", buf.Bytes())

PostgreSQL return result set as JSON array?

Also if you want selected field from table and aggregated then as array .

SELECT json_agg(json_build_object('data_a',a,
))  from t;

The result will come .


How to prevent column break within an element?

This works for me in 2015 :

li {_x000D_
  -webkit-column-break-inside: avoid;_x000D_
  /* Chrome, Safari, Opera */_x000D_
  page-break-inside: avoid;_x000D_
  /* Firefox */_x000D_
  break-inside: avoid;_x000D_
  /* IE 10+ */_x000D_
.x {_x000D_
  -moz-column-count: 3;_x000D_
  column-count: 3;_x000D_
  width: 30em;_x000D_
<div class='x'>_x000D_
    <li>Number one</li>_x000D_
    <li>Number two</li>_x000D_
    <li>Number three</li>_x000D_
    <li>Number four is a bit longer</li>_x000D_
    <li>Number five</li>_x000D_

hadoop No FileSystem for scheme: file

I faced the same problem. I found two solutions: (1) Editing the jar file manually:

Open the jar file with WinRar (or similar tools). Go to Meta-info > services , and edit "org.apache.hadoop.fs.FileSystem" by appending:


(2) Changing the order of my dependencies as follow






How do I tell a Python script to use a particular version

You can't do this within the Python program, because the shell decides which version to use if you a shebang line.

If you aren't using a shell with a shebang line and just type python it uses the default version unless you decide specifically which Python version when you type pythonXXX which version to use.

Once your Python program is running you have already decided which Python executable to use to get the program running.

virtualenv is for segregating python versions and environments, it specifically exists to eliminate conflicts.

Rewrite URL after redirecting 404 error htaccess

In your .htaccess file , if you are using apache you can try with

Rule for Error Page - 404

ErrorDocument 404

Query EC2 tags from within instance

The following bash script returns the Name of your current ec2 instance (the value of the "Name" tag). Modify TAG_NAME to your specific case.

INSTANCE_ID="`wget -qO- http://instance-data/latest/meta-data/instance-id`"
REGION="`wget -qO- http://instance-data/latest/meta-data/placement/availability-zone | sed -e 's:\([0-9][0-9]*\)[a-z]*\$:\\1:'`"
TAG_VALUE="`aws ec2 describe-tags --filters "Name=resource-id,Values=$INSTANCE_ID" "Name=key,Values=$TAG_NAME" --region $REGION --output=text | cut -f5`"

To install the aws cli

sudo apt-get install python-pip -y
sudo pip install awscli

In case you use IAM instead of explicit credentials, use these IAM permissions:

  "Version": "2012-10-17",
  "Statement": [
      "Effect": "Allow",
      "Action": [ "ec2:DescribeTags"],
      "Resource": ["*"]

A generic error occurred in GDI+, JPEG Image to MemoryStream

I have strange solution for this problem. I was fased to this during coding. I thought that Bitmap is struct and wrap around it with method. In my imagination Bitmap will be copies inside method and returned out of method. But later I checked that it's class, and i have no idea why is it helped me, but it Works! Maybe someone have time and have fun to look at IL code of this ;) Not sure maybe it's working cause this method is static inside static method, I don't know.

        public SomeClass
            public byte[] _screenShotByte;
            public Bitmap _screenShotByte;
            public Bitmap ScreenShot 
                    if (_screenShot == null)
                        _screenShotByte = ScreenShot();
                        using (var ms = new MemoryStream(_screenShotByte))
                            _screenShot = (Bitmap)Image.FromStream(ms);
                        ImageUtils.GetBitmap(_screenShot).Save(Path.Combine(AppDomain.CurrentDomain.BaseDirectory) ,$"{DateTime.Now.ToFileTimeUtc()}.png"));
                    return ImageUtils.GetBitmap(_screenShot);
            public byte[] ScreenShot()
                ///....return byte array for image in my case implementedd like selenium screen shot 
        public static ImageUtils
            public static Bitmap GetBitmap(Bitmap image)
                return Bitmap;

p.s. It's not trolling this solution solved problem of keep using bitmap after saving in another places.

Event listener for when element becomes visible?

There is at least one way, but it's not a very good one. You could just poll the element for changes like this:

var previous_style,
    poll = window.setInterval(function()
    var current_style = document.getElementById('target').style.display;
    if (previous_style != current_style) {
        alert('style changed');
    } else {
        previous_style = current_style;
}, 100);

The DOM standard also specifies mutation events, but I've never had the chance to use them, and I'm not sure how well they're supported. You'd use them like this:

target.addEventListener('DOMAttrModified', function()
    if (e.attrName == 'style') {
        alert('style changed');
}, false);

This code is off the top of my head, so I'm not sure if it'd work.

The best and easiest solution would be to have a callback in the function displaying your target.

Simple calculations for working with lat/lon and km distance?

The approximate conversions are:

  • Latitude: 1 deg = 110.574 km
  • Longitude: 1 deg = 111.320*cos(latitude) km

This doesn't fully correct for the Earth's polar flattening - for that you'd probably want a more complicated formula using the WGS84 reference ellipsoid (the model used for GPS). But the error is probably negligible for your purposes.


Caution: Be aware that latlong coordinates are expressed in degrees, while the cos function in most (all?) languages typically accepts radians, therefore a degree to radians conversion is needed.

Spring JSON request getting 406 (not Acceptable)


Could not find folder 'tools' inside SDK

In my case i was using Ubuntu. Where the was two directories one was /android-sdks and /android-sdk-linux. I used the second one it works for me :)

What does this GCC error "... relocation truncated to fit..." mean?

I ran into this problem while building a program that requires a huge amount of stack space (over 2 GiB). The solution was to add the flag -mcmodel=medium, which is supported by both GCC and Intel compilers.

How do you tell if caps lock is on using JavaScript?

try to use this code.

$('selectorOnTheInputTextBox').keypress(function (e) {
        var charCode = - 1)
        var capsOn = 
            e.keyCode && 
            !e.shiftKey &&
            !e.ctrlKey &&
            charCode >= 65 && 
            charCode <= 90;

            if (capsOn) 
               //action if true
               //action if false

Good Luck :)

Node.js console.log() not logging anything

In a node.js server console.log outputs to the terminal window, not to the browser's console window.

How are you running your server? You should see the output directly after you start it.

Find in Files: Search all code in Team Foundation Server

If you install TFS 2008 PowerTools you will get a "Find in Source Control" action in the Team Explorer right click menu.

TFS2008 Power Tools

Getting 404 Not Found error while trying to use ErrorDocument

The ErrorDocument directive, when supplied a local URL path, expects the path to be fully qualified from the DocumentRoot. In your case, this means that the actual path to the ErrorDocument is

ErrorDocument 404 /hellothere/error/404page.html

Transparent ARGB hex value

Here is the table of % to hex values:

Example: For 85% white, you would use #D9FFFFFF. Here 85% = "D9" & White = "FFFFFF"

100% — FF
95% — F2
90% — E6

85% — D9

80% — CC
75% — BF
70% — B3
65% — A6
60% — 99
55% — 8C
50% — 80
45% — 73
40% — 66
35% — 59
30% — 4D
25% — 40
20% — 33
15% — 26
10% — 1A
5% — 0D
0% — 00

How is it calculated?

FF is number written in hex mode. That number represent 255 in decimal. For example, if you want 42% to calculate you need to find 42% of numbeer 255 and convert that number to hex. 255 * 0.42 ~= 107 107 to hex is "6B – maleta

Submit Button Image

<input type="image" src="path to image" name="submit" />


For button states, you can use type="submit" and then add a class to it

<input type="submit" name="submit" class="states" />

Then in css, use background images for:

background-image:url(path to url);



Set variable with multiple values and use IN

Ideally you shouldn't be splitting strings in T-SQL at all.

Barring that change, on older versions before SQL Server 2016, create a split function:

CREATE FUNCTION dbo.SplitStrings
    @List      nvarchar(max), 
    @Delimiter nvarchar(2)
      SELECT CONVERT(xml, N'<root><i>' 
        + REPLACE(@List, @Delimiter, N'</i><i>') 
        + N'</i></root>')
    SELECT Item = LTRIM(RTRIM(i.i.value(N'.',N'nvarchar(max)')))
      FROM x CROSS APPLY x.nodes(N'//root/i') AS i(i)

Now you can say:

DECLARE @Values varchar(1000);

SET @Values = 'A, B, C';

  INNER JOIN dbo.SplitStrings(@Values, ',') AS s
    ON s.Item = foo.myField;

On SQL Server 2016 or above (or Azure SQL Database), it is much simpler and more efficient, however you do have to manually apply LTRIM() to take away any leading spaces:

DECLARE @Values varchar(1000) = 'A, B, C';

    ON LTRIM(s.value) = foo.myField;

How can you print a variable name in python?

Will something like this work for you?

>>> def namestr(**kwargs):
...     for k,v in kwargs.items():
...       print "%s = %s" % (k, repr(v))
>>> namestr(a=1, b=2)
a = 1
b = 2

And in your example:

>>> choice = {'key': 24; 'data': None}
>>> namestr(choice=choice)
choice = {'data': None, 'key': 24}
>>> printvars(**globals())
__builtins__ = <module '__builtin__' (built-in)>
__name__ = '__main__'
__doc__ = None
namestr = <function namestr at 0xb7d8ec34>
choice = {'data': None, 'key': 24}

How to capture and save an image using custom camera in Android?

Following Snippet will help you

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android=""
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="15" />
    <uses-permission android:name="android.permission.CAMERA"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

        android:label="@string/app_name" >
            android:label="@string/app_name" >
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />



<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android=""
    android:layout_height="match_parent" >

        android:text="Make Photo" />


package org.sample;

import java.text.SimpleDateFormat;
import java.util.Date;

import android.content.Context;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;

public class PhotoHandler implements PictureCallback {

    private final Context context;

    public PhotoHandler(Context context) {
        this.context = context;

    public void onPictureTaken(byte[] data, Camera camera) {

        File pictureFileDir = getDir();

        if (!pictureFileDir.exists() && !pictureFileDir.mkdirs()) {

            Log.d(Constants.DEBUG_TAG, "Can't create directory to save image.");
            Toast.makeText(context, "Can't create directory to save image.",


        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyymmddhhmmss");
        String date = dateFormat.format(new Date());
        String photoFile = "Picture_" + date + ".jpg";

        String filename = pictureFileDir.getPath() + File.separator + photoFile;

        File pictureFile = new File(filename);

        try {
            FileOutputStream fos = new FileOutputStream(pictureFile);
            Toast.makeText(context, "New Image saved:" + photoFile,
        } catch (Exception error) {
            Log.d(Constants.DEBUG_TAG, "File" + filename + "not saved: "
                    + error.getMessage());
            Toast.makeText(context, "Image could not be saved.",

    private File getDir() {
        File sdDir = Environment
        return new File(sdDir, "CameraAPIDemo");

package org.sample;

import android.hardware.Camera;
import android.hardware.Camera.CameraInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import de.vogella.cameara.api.R;

public class MakePhotoActivity extends Activity {
    private final static String DEBUG_TAG = "MakePhotoActivity";
    private Camera camera;
    private int cameraId = 0;

    public void onCreate(Bundle savedInstanceState) {

        // do we have a camera?
        if (!getPackageManager()
                .hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
            Toast.makeText(this, "No camera on this device", Toast.LENGTH_LONG)
        } else {
            cameraId = findFrontFacingCamera();
            camera =;
            if (cameraId < 0) {
                Toast.makeText(this, "No front facing camera found.",

    public void onClick(View view) {
        camera.takePicture(null, null,
                new PhotoHandler(getApplicationContext()));

    private int findFrontFacingCamera() {
        int cameraId = -1;
        // Search for the front facing camera
        int numberOfCameras = Camera.getNumberOfCameras();
        for (int i = 0; i < numberOfCameras; i++) {
            CameraInfo info = new CameraInfo();
            Camera.getCameraInfo(i, info);
            if (info.facing == CameraInfo.CAMERA_FACING_FRONT) {
                Log.d(DEBUG_TAG, "Camera found");
                cameraId = i;
        return cameraId;

    protected void onPause() {
        if (camera != null) {
            camera = null;


Is there a <meta> tag to turn off caching in all browsers?

It doesn't work in IE5, but that's not a big issue.

However, cacheing headers are unreliable in meta elements; for one, any web proxies between the site and the user will completely ignore them. You should always use a real HTTP header for headers such as Cache-Control and Pragma.

mysql update multiple columns with same now()

You can store the value of a now() in a variable before running the update query and then use that variable to update both the fields last_update and last_monitor.

This will ensure the now() is executed only once and same value is updated on both columns you need.

How to sum all values in a column in Jaspersoft iReport Designer?

iReports Custom Fields for columns (sum, average, etc)

  1. Right-Click on Variables and click Create Variable

  2. Click on the new variable

    a. Notice the properties on the right

  3. Rename the variable accordingly

  4. Change the Value Class Name to the correct Data Type

    a. You can search by clicking the 3 dots

  5. Select the correct type of calculation

  6. Change the Expression

    a. Click the little icon

    b. Select the column you are looking to do the calculation for

    c. Click finish

  7. Set Initial Value Expression to 0

  8. Set the increment type to none

  9. Leave Incrementer Factory Class Name blank
  10. Set the Reset Type (usually report)

  11. Drag a new Text Field to stage (Usually in Last Page Footer, or Column Footer)

  12. Double Click the new Text Field
  13. Clear the expression “Text Field”
  14. Select the new variable

  15. Click finish

  16. Put the new text in a desirable position ?

Setting Icon for wpf application (VS 08)

Assuming you use VS Express and C#. The icon is set in the project properties page. To open it right click on the project name in the solution explorer. in the page that opens, there is an Application tab, in this tab you can set the icon.

Use of for_each on map elements

C++14 brings generic lambdas. Meaning we can use std::for_each very easily:

std::map<int, int> myMap{{1, 2}, {3, 4}, {5, 6}, {7, 8}};

std::for_each(myMap.begin(), myMap.end(), [](const auto &myMapPair) {
    std::cout << "first " << myMapPair.first << " second "
              << myMapPair.second << std::endl;

I think std::for_each is sometimes better suited than a simple range based for loop. For example when you only want to loop through a subset of a map.

How can I detect window size with jQuery?

You make one div somewhere on the page and put this code:

<div id="winSize"></div>
    var WindowsSize=function(){
        var h=$(window).height(),
        $("#winSize").html("<p>Width: "+w+"<br>Height: "+h+"</p>");

Here is a snippet:

var WindowsSize=function(){_x000D_
     var h=$(window).height(),_x000D_
     $("#winSize").html("<p>Width: "+w+"<br>Height:"+h+"</p>");_x000D_
 $(document).ready(WindowsSize); _x000D_
  border:rgba(0,0,0,0.8) 3px solid;_x000D_
  padding:5px 10px;_x000D_
  text-shadow:#000 1px 1px 1px,#000 -1px 1px 1px;_x000D_
<script src=""></script>_x000D_
<div id="winSize"></div>

Of course, adapt it to fit your needs! ;)

What is the T-SQL To grant read and write access to tables in a database in SQL Server?

In SQL Server 2012, 2014:

USE mydb


In SQL Server 2008:

use mydb

exec sp_addrolemember db_datareader, MYUSER 
exec sp_addrolemember db_datawriter, MYUSER 

To also assign the ability to execute all Stored Procedures for a Database:


To assign the ability to execute specific stored procedures:

GRANT EXECUTE ON dbo.sp_mystoredprocedure TO MYUSER;

ContractFilter mismatch at the EndpointDispatcher exception

For a Java client calling a .net endpoint. This was caused by mismatching Soap Action header.

Content-Type: application/soap+xml;charset=UTF-8;action=""

The above HTTP header or following XML tag needs to match the action/method your are trying to invoke.

   <soap:Envelope xmlns:soap="" xmlns:tem="" xmlns:gen="">
   <soap:Header xmlns:wsa="">

How to Exit a Method without Exiting the Program?

@John, Earlz and Nathan. The way I learned it at uni is: functions return values, methods don't. In some languages the syntax is/was actually different. Example (no specific language):

Method SetY(int y) ...
Function CalculateY(int x) As Integer ...

Most languages now use the same syntax for both versions, using void as a return type to say there actually isn't a return type. I assume it's because the syntax is more consistent and easier to change from method to function, and vice versa.

How do I generate a constructor from class fields using Visual Studio (and/or ReSharper)?

ReSharper offers a Generate Constructor tool where you can select any field/properties that you want initialized. I use the Alt + Ins hot-key to access this.

How to get the location of the DLL currently executing?

In my case (dealing with my assemblies loaded [as file] into Outlook):


Note the use of CodeBase (not Location) on the Assembly. Others have pointed out alternative methods of locating the assembly.

How to change a PG column to NULLABLE TRUE?

From the fine manual:


There's no need to specify the type when you're just changing the nullability.

PostgreSQL: export resulting data from SQL query to Excel/CSV

This worked for me:

    TO E'C:\\Program Files (x86)\\PostgreSQL\\8.4\\data\\try.csv';

In my case the problem was with the writing permission to a special folder (though I work as administrator), after changing the path to the original data folder under PostgreSQL I had success.

boto3 client NoRegionError: You must specify a region error only sometimes

For those using CloudFormation template. You can set AWS_DEFAULT_REGION environment variable using UserData and AWS::Region. For example,

    Type: AWS::EC2::Instance                
        ImageId: ami-04b9e92b5572fa0d1 #ubuntu
        InstanceType: t2.micro
            Fn::Base64: !Sub |
                    #!/bin/bash -x

                    echo "export AWS_DEFAULT_REGION=${AWS::Region}" >> /etc/profile

How to merge every two lines into one from the command line?

A slight variation on glenn jackman's answer using paste: if the value for the -d delimiter option contains more than one character, paste cycles through the characters one by one, and combined with the -s options keeps doing that while processing the same input file.

This means that we can use whatever we want to have as the separator plus the escape sequence \n to merge two lines at a time.

Using a comma:

$ paste -s -d ',\n' infile
KEY 4048:1736 string,3
KEY 0:1772 string,1
KEY 4192:1349 string,1
KEY 7329:2407 string,2
KEY 0:1774 string,1

and the dollar sign:

$ paste -s -d '$\n' infile
KEY 4048:1736 string$3
KEY 0:1772 string$1
KEY 4192:1349 string$1
KEY 7329:2407 string$2
KEY 0:1774 string$1

What this cannot do is use a separator consisting of multiple characters.

As a bonus, if the paste is POSIX compliant, this won't modify the newline of the last line in the file, so for an input file with an odd number of lines like

KEY 4048:1736 string
KEY 0:1772 string

paste won't tack on the separation character on the last line:

$ paste -s -d ',\n' infile
KEY 4048:1736 string,3
KEY 0:1772 string

Maven 3 warnings about build.plugins.plugin.version

It's great answer in here. And I want to add 'Why Add a element in Maven3'.
In Maven 3.x Compatibility Notes

Plugin Metaversion Resolution
Internally, Maven 2.x used the special version markers RELEASE and LATEST to support automatic plugin version resolution. These metaversions were also recognized in the element for a declaration. For the sake of reproducible builds, Maven 3.x no longer supports usage of these metaversions in the POM. As a result, users will need to replace occurrences of these metaversions with a concrete version.

And I also find in maven-compiler-plugin - usage

Note: Maven 3.0 will issue warnings if you do not specify the version of a plugin.

How to resolve "git pull,fatal: unable to access '\': Empty reply from server"

Try, this

git config --global --unset http.proxy

git config --global --unset https.proxy

How to store decimal values in SQL Server?

In MySQL DB decimal(4,2) allows entering only a total of 4 digits. As you see in decimal(4,2), it means you can enter a total of 4 digits out of which two digits are meant for keeping after the decimal point.

So, if you enter 100.0 in MySQL database, it will show an error like "Out of Range Value for column".

So, you can enter in this range only: from 00.00 to 99.99.

What is the use of join() in Python threading?

Thanks for this thread -- it helped me a lot too.

I learned something about .join() today.

These threads run in parallel:


and these run sequentially (not what I wanted):


In particular, I was trying to clever and tidy:

class Kiki(threading.Thread):
    def __init__(self, time):
        super(Kiki, self).__init__()
        self.time = time

This works! But it runs sequentially. I can put the self.start() in __ init __, but not the self.join(). That has to be done after every thread has been started.

join() is what causes the main thread to wait for your thread to finish. Otherwise, your thread runs all by itself.

So one way to think of join() as a "hold" on the main thread -- it sort of de-threads your thread and executes sequentially in the main thread, before the main thread can continue. It assures that your thread is complete before the main thread moves forward. Note that this means it's ok if your thread is already finished before you call the join() -- the main thread is simply released immediately when join() is called.

In fact, it just now occurs to me that the main thread waits at d.join() until thread d finishes before it moves on to t.join().

In fact, to be very clear, consider this code:

import threading
import time

class Kiki(threading.Thread):
    def __init__(self, time):
        super(Kiki, self).__init__()
        self.time = time

    def run(self):
        print self.time, " seconds start!"
        for i in range(0,self.time):
            print "1 sec of ", self.time
        print self.time, " seconds finished!"

t1 = Kiki(3)
t2 = Kiki(2)
t3 = Kiki(1)
print "t1.join() finished"
print "t2.join() finished"
print "t3.join() finished"

It produces this output (note how the print statements are threaded into each other.)

$ python
32   seconds start! seconds start!1

 seconds start!
1 sec of  1
 1 sec of 1  seconds finished!
 21 sec of
1 sec of  3
1 sec of  2
2  seconds finished!
1 sec of  3
3  seconds finished!
t1.join() finished
t2.join() finished
t3.join() finished

The t1.join() is holding up the main thread. All three threads complete before the t1.join() finishes and the main thread moves on to execute the print then t2.join() then print then t3.join() then print.

Corrections welcome. I'm also new to threading.

(Note: in case you're interested, I'm writing code for a DrinkBot, and I need threading to run the ingredient pumps concurrently rather than sequentially -- less time to wait for each drink.)

PreparedStatement with Statement.RETURN_GENERATED_KEYS

private void alarmEventInsert(DriveDetail driveDetail, String vehicleRegNo, int organizationId) {

    final String ALARM_EVENT_INS_SQL = "INSERT INTO alarm_event (event_code,param1,param2,org_id,created_time) VALUES (?,?,?,?,?)";
    CachedConnection conn = JDatabaseManager.getConnection();
    PreparedStatement ps = null;
    ResultSet generatedKeys = null;
    try {
        ps = conn.prepareStatement(ALARM_EVENT_INS_SQL, ps.RETURN_GENERATED_KEYS);
        ps.setInt(1, driveDetail.getEventCode());
        ps.setString(2, vehicleRegNo);
        ps.setString(3, null);
        ps.setInt(4, organizationId);
        ps.setString(5, driveDetail.getCreateTime());
        generatedKeys = ps.getGeneratedKeys();
        if ( {
    } catch (SQLException e) {
        logger.error("Error inserting into alarm_event : {}", e
    } finally {
        if (ps != null) {
            try {

                if (ps != null)
            } catch (SQLException e) {
                logger.error("Error closing prepared statements : {}", e

java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver

Have you copied classes12.jar in lib folder of your web application and set the classpath in eclipse.

Right-click project in Package explorer Build path -> Add external archives...

Select your ojdbc6.jar archive

Press OK


Go through this link and read and do carefully.

The library should be now referenced in the "Referenced Librairies" under the Package explorer. Now try to run your program again.

how to fix Cannot call sendRedirect() after the response has been committed?

The root cause of IllegalStateException exception is a java servlet is attempting to write to the output stream (response) after the response has been committed.

It is always better to ensure that no content is added to the response after the forward or redirect is done to avoid IllegalStateException. It can be done by including a ‘return’ statement immediately next to the forward or redirect statement.



Show "Open File" Dialog

Addition to what Albert has already said:

This code (a mashup of various samples) provides the ability to have a SaveAs dialog box

Function getFileName() As String
    Dim fDialog    As Object
    Set fDialog = Application.FileDialog(msoFileDialogSaveAs)
    Dim varFile As Variant

    With fDialog
       .AllowMultiSelect = False
       .Title = "Select File Location to Export XLSx :"
       .InitialFileName = "jeffatwood.xlsx"

    If .Show = True Then
       For Each varFile In .SelectedItems
         getFileName = varFile
    End If
End With
End Function

Is there a Google Chrome-only CSS hack?

Only Chrome CSS hack:

@media all and (-webkit-min-device-pixel-ratio:0) and (min-resolution: .001dpcm) {
    #selector {
        background: red;

ASP.NET: HTTP Error 500.19 – Internal Server Error 0x8007000d

I had this problem with a brand new web service. Solved it by adding read-only access for Everyone on Properties->Security for the folder that the service was in.

TypeError: ObjectId('') is not JSON serializable

As a quick replacement, you can change {'owner': objectid} to {'owner': str(objectid)}.

But defining your own JSONEncoder is a better solution, it depends on your requirements.

How do I hide a menu item in the actionbar?

This worked for me from both Activity and Fragment

public void onPrepareOptionsMenu(Menu menu) {
    if (menu.findItem( != null)

Pandas: Subtracting two date columns and the result being an integer

I feel that the overall answer does not handle if the dates 'wrap' around a year. This would be useful in understanding proximity to a date being accurate by day of year. In order to do these row operations, I did the following. (I had this used in a business setting in renewing customer subscriptions).

def get_date_difference(row, x, y):
        # Calcuating the smallest date difference between the start and the close date
        # There's some tricky logic in here to calculate for determining date difference
        # the other way around (Dec -> Jan is 1 month rather than 11)

        sub_start_date = int(row[x].strftime('%j')) # day of year (1-366)
        close_date = int(row[y].strftime('%j')) # day of year (1-366)

        later_date_of_year = max(sub_start_date, close_date) 
        earlier_date_of_year = min(sub_start_date, close_date)
        days_diff = later_date_of_year - earlier_date_of_year

# Calculates the difference going across the next year (December -> Jan)
        days_diff_reversed = (365 - later_date_of_year) + earlier_date_of_year
        return min(days_diff, days_diff_reversed)

    except ValueError:
        return None

Then the function could be:

dfAC_Renew['date_difference'] = dfAC_Renew.apply(get_date_difference, x = 'customer_since_date', y = 'renewal_date', axis = 1)

Adding input elements dynamically to form

Try this JQuery code to dynamically include form, field, and delete/remove behavior:

$(document).ready(function() {_x000D_
    var max_fields = 10;_x000D_
    var wrapper = $(".container1");_x000D_
    var add_button = $(".add_form_field");_x000D_
    var x = 1;_x000D_
    $(add_button).click(function(e) {_x000D_
        if (x < max_fields) {_x000D_
            $(wrapper).append('<div><input type="text" name="mytext[]"/><a href="#" class="delete">Delete</a></div>'); //add input box_x000D_
        } else {_x000D_
            alert('You Reached the limits')_x000D_
    $(wrapper).on("click", ".delete", function(e) {_x000D_
<script src=""></script>_x000D_
<div class="container1">_x000D_
    <button class="add_form_field">Add New Field &nbsp; _x000D_
      <span style="font-size:16px; font-weight:bold;">+ </span>_x000D_
    <div><input type="text" name="mytext[]"></div>_x000D_

Refer Demo Here

Get key from a HashMap using the value

if you what to obtain "ONE" by giving in 100 then

initialize hash map by

hashmap = new HashMap<Object,String>();


and retrieve value by hashMap.get(100)

hope that helps.

Returning JSON object from an ASP.NET page

In your Page_Load you will want to clear out the normal output and write your own, for example:

string json = "{\"name\":\"Joe\"}";
Response.ContentType = "application/json; charset=utf-8";

To convert a C# object to JSON you can use a library such as Json.NET.

Instead of getting your .aspx page to output JSON though, consider using a Web Service (asmx) or WCF, both of which can output JSON.

Laravel 5 - How to access image uploaded in storage within View?

If you are like me and you somehow have full file paths (I did some glob() pattern matching on required photos so I do pretty much end up with full file paths), and your storage setup is well linked (i.e. such that your paths have the string storage/app/public/), then you can use my little dirty hack below :p)

 public static function hackoutFileFromStorageFolder($fullfilePath) {
        if (strpos($fullfilePath, 'storage/app/public/')) {
           $fileParts = explode('storage/app/public/', $fullfilePath);
           if( count($fileParts) > 1){
               return $fileParts[1];

        return '';

Check string for nil & empty


extension Optional where Wrapped == String {

    /// Checks to see whether the optional string is nil or empty ("")
    public var isNilOrEmpty: Bool {
        if let text = self, !text.isEmpty { return false }
        return true

Use like this on optional string:

if myString.isNilOrEmpty { print("Crap, how'd this happen?") } 

What are the differences between WCF and ASMX web services?

Keith Elder nicely compares ASMX to WCF here. Check it out.

Another comparison of ASMX and WCF can be found here - I don't 100% agree with all the points there, but it might give you an idea.

WCF is basically "ASMX on stereoids" - it can be all that ASMX could - plus a lot more!.

ASMX is:

  • easy and simple to write and configure
  • only available in IIS
  • only callable from HTTP

WCF can be:

  • hosted in IIS, a Windows Service, a Winforms application, a console app - you have total freedom
  • used with HTTP (REST and SOAP), TCP/IP, MSMQ and many more protocols

In short: WCF is here to replace ASMX fully.

Check out the WCF Developer Center on MSDN.

Update: link seems to be dead - try this: What Is Windows Communication Foundation?

Git clone particular version of remote repository

Probably git reset solves your problem.

git reset --hard -#commit hash-

URL rewriting with PHP

Although already answered, and author's intent is to create a front controller type app but I am posting literal rule for problem asked. if someone having the problem for same.

RewriteEngine On
RewriteRule ^([^/]+)/([^/]+)/([\d]+)$ $1?id=$3 [L]

Above should work for url picture.php/Some-text-goes-here/51. without using a index.php as a redirect app.

How can I build for release/distribution on the Xcode 4?

To set the build configuration to Debug or Release, choose 'Edit Scheme' from the 'Product' menu.

Then you see a clear choice.

The Apple Transition Guide mentions a button at the top left of the Xcode screen, but I cannot see it in Xcode 4.3.

Collection was modified; enumeration operation may not execute in ArrayList

Don't modify the list inside of a loop which iterates through the list.

Instead, use a for() or while() with an index, going backwards through the list. (This will let you delete things without getting an invalid index.)

var foo = new List<Bar>();

for(int i = foo.Count-1; i >= 0; --i)
  var item = foo[i];
  // do something with item

Razor View Engine : An expression tree may not contain a dynamic operation

In this link explain about @model, see a excerpt:

@model (lowercase "m") is a reserved keyword in Razor views to declare the model type at the top of your view. You have put the namespace too, e.g.: @model MyNamespace.Models.MyModel

Later in the file, you can reference the attribute you want with @Model.Attribute (uppercase "M").

The definitive guide to form-based website authentication

I'd like to add one suggestion I've used, based on defense in depth. You don't need to have the same auth&auth system for admins as regular users. You can have a separate login form on a separate url executing separate code for requests that will grant high privileges. This one can make choices that would be a total pain to regular users. One such that I've used is to actually scramble the login URL for admin access and email the admin the new URL. Stops any brute force attack right away as your new URL can be arbitrarily difficult (very long random string) but your admin user's only inconvenience is following a link in their email. The attacker no longer knows where to even POST to.

FormsAuthentication.SignOut() does not log the user out

The code you posted looks like it should correctly remove the forms authentication token, so it is possible that the folders/pages in question are not actually protected.

Have you confirmed that the pages cannot be accessed before a login has occured?

Can you post the web.config settings and login code that you are using?

Chart creating dynamically. in .net, c#

Try to include these lines on your code, after mych.Visible = true;:

ChartArea chA = new ChartArea();

Insert line after first match using sed

I had to do this recently as well for both Mac and Linux OS's and after browsing through many posts and trying many things out, in my particular opinion I never got to where I wanted to which is: a simple enough to understand solution using well known and standard commands with simple patterns, one liner, portable, expandable to add in more constraints. Then I tried to looked at it with a different perspective, that's when I realized i could do without the "one liner" option if a "2-liner" met the rest of my criteria. At the end I came up with this solution I like that works in both Ubuntu and Mac which i wanted to share with everyone:

insertLine=$(( $(grep -n "foo" sample.txt | cut -f1 -d: | head -1) + 1 ))
sed -i -e "$insertLine"' i\'$'\n''bar'$'\n' sample.txt

In first command, grep looks for line numbers containing "foo", cut/head selects 1st occurrence, and the arithmetic op increments that first occurrence line number by 1 since I want to insert after the occurrence. In second command, it's an in-place file edit, "i" for inserting: an ansi-c quoting new line, "bar", then another new line. The result is adding a new line containing "bar" after the "foo" line. Each of these 2 commands can be expanded to more complex operations and matching.

How can I programmatically check whether a keyboard is present in iOS app?

To check weather keyboard is appeared, we can use the Keyboard predefined notifications.

UIKeyboardDidShowNotification ,UIKeyboardDidHideNotification

For example I can use the following code to listen the keyboard notification

// Listen for keyboard appearances and disappearances

[[NSNotificationCenter defaultCenter] addObserver:self 

[[NSNotificationCenter defaultCenter] addObserver:self

in the methods I can get notifications

- (void)keyboardDidShow: (NSNotification *) notifyKeyBoardShow{
    // key board is closed

- (void)keyboardDidHide: (NSNotification *) notifyKeyBoardHide{
    // key board is opened

Django ManyToMany filter()

another way to do this is by going through the intermediate table. I'd express this within the Django ORM like this:

UserZone = User.zones.through

# for a single zone
users_in_zone = User.objects.filter(

# for multiple zones
users_in_zones = User.objects.filter(
  id__in=UserZone.objects.filter(zone__in=[zone1, zone2, zone3]).values('user'))

it would be nice if it didn't need the .values('user') specified, but Django (version 3.0.7) seems to need it.

the above code will end up generating SQL that looks something like:

SELECT * FROM users WHERE id IN (SELECT user_id FROM userzones WHERE zone_id IN (1,2,3))

which is nice because it doesn't have any intermediate joins that could cause duplicate users to be returned

Eclipse: The declared package does not match the expected package

If you have imported an existing project, then just remove your source folders and then add them again to build path, and restart eclipse. Most of the times eclipse will keep showing the error till you restart.

Automatic creation date for Django model form objects?

You can use the auto_now and auto_now_add options for updated_at and created_at respectively.

class MyModel(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

PYTHONPATH vs. sys.path

In general I would consider setting up of an environment variable (like PYTHONPATH) to be a bad practice. While this might be fine for a one off debugging but using this as
a regular practice might not be a good idea.

Usage of environment variable leads to situations like "it works for me" when some one
else reports problems in the code base. Also one might carry the same practice with the test environment as well, leading to situations like the tests running fine for a particular developer but probably failing when some one launches the tests.

ASP.NET Identity - HttpContext has no extension method for GetOwinContext

In my case adding Microsoft.AspNet.WebApi.Owin reference via nuget did the trick.

org.xml.sax.SAXParseException: Premature end of file for *VALID* XML

If input stream is not closed properly then this exception may happen. make sure : If inputstream used is not used "Before" in some way then where you are intended to read. i.e if read 2nd time from same input stream in single operation then 2nd call will get this exception. Also make sure to close input stream in finally block or something like that.

Insert data into a view (SQL Server)

Inserting 'test' to name will lead to inserting NULL values to other columns of the base table which wont be correct as Id is a PRIMARY KEY and it cannot have NULL value.

Selecting the first "n" items with jQuery

Use lt pseudo selector:


This matches the elements before the nth one (the nth element excluded). Numbering starts from 0.

how to zip a folder itself using java

I usually use a helper class I once wrote for this task:


public class ZipExample {
    public static void main(String[] args){
        ZipHelper zippy = new ZipHelper();
        try {
        } catch(IOException e2) {

class ZipHelper  
    public void zipDir(String dirName, String nameZipFile) throws IOException {
        ZipOutputStream zip = null;
        FileOutputStream fW = null;
        fW = new FileOutputStream(nameZipFile);
        zip = new ZipOutputStream(fW);
        addFolderToZip("", dirName, zip);

    private void addFolderToZip(String path, String srcFolder, ZipOutputStream zip) throws IOException {
        File folder = new File(srcFolder);
        if (folder.list().length == 0) {
            addFileToZip(path , srcFolder, zip, true);
        else {
            for (String fileName : folder.list()) {
                if (path.equals("")) {
                    addFileToZip(folder.getName(), srcFolder + "/" + fileName, zip, false);
                else {
                     addFileToZip(path + "/" + folder.getName(), srcFolder + "/" + fileName, zip, false);

    private void addFileToZip(String path, String srcFile, ZipOutputStream zip, boolean flag) throws IOException {
        File folder = new File(srcFile);
        if (flag) {
            zip.putNextEntry(new ZipEntry(path + "/" +folder.getName() + "/"));
        else {
            if (folder.isDirectory()) {
                addFolderToZip(path, srcFile, zip);
            else {
                byte[] buf = new byte[1024];
                int len;
                FileInputStream in = new FileInputStream(srcFile);
                zip.putNextEntry(new ZipEntry(path + "/" + folder.getName()));
                while ((len = > 0) {
                    zip.write(buf, 0, len);

SQL Stored Procedure set variables using SELECT

One advantage your current approach does have is that it will raise an error if multiple rows are returned by the predicate. To reproduce that you can use.

SELECT @currentTerm = currentterm,
       @termID = termid,
       @endDate = enddate
FROM   table1
WHERE  iscurrent = 1

IF( @@ROWCOUNT <> 1 )
      RAISERROR ('Unexpected number of matching rows',


Angular2 *ngFor in select list, set active based on string from object

Check it out in this demo fiddle, go ahead and change the dropdown or default values in the code.

Setting the passenger.Title with a value that equals to a title.Value should work.


<select [(ngModel)]="passenger.Title">
    <option *ngFor="let title of titleArray" [value]="title.Value">

TypeScript used:

class Passenger {
  constructor(public Title: string) { };
class ValueAndText {
  constructor(public Value: string, public Text: string) { }

export class AppComponent {
    passenger: Passenger = new Passenger("Lord");

    titleArray: ValueAndText[] = [new ValueAndText("Mister", "Mister-Text"),
                                  new ValueAndText("Lord", "Lord-Text")];


Making LaTeX tables smaller?

if it's too long for one page, use the longtable package. and if it's too wide for the page, use p{width} in place of l,r, or c for the column specifier. you can also go smaller than \small, i.e. \footnotesize and \tiny. I would consult the setspace package for options on how to remove the double space, though it's probably \singlespace or something like that.

Get current controller in view

Just use:


This will give you the whole Controller's Name

how to set radio button checked in edit mode in MVC razor view

To set radio button checked in edit mode in MVC razor view, please trying as follow:

<div class="col-lg-11 col-md-11">
     @Html.RadioButtonFor(m => m.Role, "1", Model.Role == 1 ? "checked" : string.Empty) 
     @Html.RadioButtonFor(m => m.Role, "0", Model.Role == 0 ? "checked" : string.Empty)
     @Html.HiddenFor(m => m.Role)

Hope it help!

How to create a list of objects?

In Python, the name of the class refers to the class instance. Consider:

class A: pass
class B: pass
class C: pass

lst = [A, B, C]

# instantiate second class
b_instance = lst[1]()
print b_instance

AngularJS - value attribute for select

If the model specified for the drop down does not exist then angular will generate an empty options element. So you will have to explicitly specify the model on the select like this:

<select ng-model="regions[index]" ng-options="....">

Refer to the following as it has been answered before:

Why does AngularJS include an empty option in select? and this fiddle

Update: Try this instead:

<select ng-model="regions[index].code" ng-options="i.code as for i in regions">


<select ng-model="regions[2]" ng-options=" for r in regions">

Note that there is no empty options element in the select.

Pass array to MySQL stored routine

You can pass a string with your list and use a prepared statements to run a query, e.g. -


CREATE PROCEDURE GetFruits(IN fruitArray VARCHAR(255))

  SET @sql = CONCAT('SELECT * FROM Fruits WHERE Name IN (', fruitArray, ')');
  PREPARE stmt FROM @sql;
  EXECUTE stmt;



How to use:

SET @fruitArray = '\'apple\',\'banana\'';
CALL GetFruits(@fruitArray);

How to set TextView textStyle such as bold, italic

Since I want to use a custom font only conjunction of several answers works for me. Obviously settings in my layout.xml like android:textStlyle="italic" was ignored by AOS. So finally I had to do as follows: in strings.xml the target string was declared as:

<string name="txt_sign"><i>The information blah blah ...</i></string>

then additionally in code:

TextView textSign = (TextView) findViewById(;
textSign.setTypeface(textSign.getTypeface(), Typeface.ITALIC);

I didn't try the Spannable option (which I assume MUST work) but


had no effect. Also if I remove the italic tag from strings.xml leaving the setTypeface() all alone it has no effect either. Tricky Android...

LaTeX: remove blank page after a \part or \chapter

I believe that in the book class all \part and \chapter are set to start on a recto page.

from book.cls:


you should be able to renew that command, and something similar for the \chapter.

How to call javascript function on page load in

Calling JavaScript function on code behind i.e. On Page_Load

ClientScript.RegisterStartupScript(GetType(), "Javascript", "javascript:FUNCTIONNAME(); ", true);

If you have UpdatePanel there then try like this

ScriptManager.RegisterStartupScript(GetType(), "Javascript", "javascript:FUNCTIONNAME(); ", true);

View Blog Article : How to Call javascript function from code behind in c#

On duplicate key ignore?

Would suggest NOT using INSERT IGNORE as it ignores ALL errors (ie its a sloppy global ignore). Instead, since in your example tag is the unique key, use:

INSERT INTO table_tags (tag) VALUES ('tag_a'),('tab_b'),('tag_c') ON DUPLICATE KEY UPDATE tag=tag;

on duplicate key produces:

Query OK, 0 rows affected (0.07 sec)

How to remove an item from an array in AngularJS scope?

You can also use this

$scope.persons = $filter('filter')($scope.persons , { id: ('!' + });

setAttribute('display','none') not working

It works for me

setAttribute('style', 'display:none');

Align two inline-blocks left and right on same line

Edit: 3 years has passed since I answered this question and I guess a more modern solution is needed, although the current one does the thing :)


It's by far the shortest and most flexible. Apply display: flex; to the parent container and adjust the placement of its children by justify-content: space-between; like this:

.header {
    display: flex;
    justify-content: space-between;

Can be seen online here -

Note however that flexbox support is IE10 and newer. If you need to support IE 9 or older, use the following solution:

2.You can use the text-align: justify technique here.

.header {
    background: #ccc; 
    text-align: justify; 

    /* ie 7*/  
    *width: 100%;  
    *-ms-text-justify: distribute-all-lines;
    *text-justify: distribute-all-lines;
    content: '';
    display: inline-block;
    width: 100%;
    height: 0;

h1 {
    display: inline-block;
    margin-top: 0.321em; 

    /* ie 7*/ 
    *display: inline;
    *zoom: 1;
    *text-align: left; 

.nav {
    display: inline-block;
    vertical-align: baseline; 

    /* ie 7*/
    *display: inline;
    *text-align: right;

The working example can be seen here: This code works from IE7 and above

If inline-block elements in HTML are not separated with space, this solution won't work - see example . This might be a case when you insert content with Javascript.

If we don't care about IE7 simply omit the star-hack properties. The working example using your markup is here - I just added the header:after part and justified the content.

In order to solve the issue of the extra space that is inserted with the after pseudo-element one can do a trick of setting the font-size to 0 for the parent element and resetting it back to say 14px for the child elements. The working example of this trick can be seen here:

Python: import cx_Oracle ImportError: No module named cx_Oracle error is thown

To access Oracle from python you need (additionally) the cx_Oracle module. The module must be located either in the system python path or you have to set the PYTHONPATH appropriate.

Hive ParseException - cannot recognize input near 'end' 'string'

You can always escape the reserved keyword if you still want to make your query work!!

Just replace end with `end`

Here is the list of reserved keywords

CREATE EXTERNAL TABLE moveProjects (cid string, `end` string, category string)
STORED BY 'org.apache.hadoop.hive.dynamodb.DynamoDBStorageHandler'
TBLPROPERTIES ("" = "Projects",
    "dynamodb.column.mapping" = "cid:cid,end:end,category:category");

Java NoSuchAlgorithmException - SunJSSE,$DefaultSSLContext

I've had a similar issue with this error. In my case, I was entering the incorrect password for the Keystore.

I changed the password for the Keystore to match what I was entering (I didn't want to change the password I was entering), but it still gave the same error.

keytool -storepasswd -keystore keystore.jks

Problem was that I also needed to change the Key's password within the Keystore.

When I initially created the Keystore, the Key was created with the same password as the Keystore (I accepted this default option). So I had to also change the Key's password as follows:

keytool -keypasswd  -alias my.alias -keystore keystore.jks

How to create a popup window (PopupWindow) in Android

are you done with the layout inflating? maybe you can try this!!

View myPoppyView = pw.getContentView();
Button myBelovedButton = (Button)myPoppyView.findViewById(;
//do something with my beloved button? :p

Using NULL in C++?

The downside of NULL in C++ is that it is a define for 0. This is a value that can be silently converted to pointer, a bool value, a float/double, or an int.

That is not very type safe and has lead to actual bugs in an application I worked on.

Consider this:

void Foo(int i);
void Foo(Bar* b);
void Foo(bool b);

     Foo(NULL); // same as Foo(0)

C++11 defines a nullptr that is convertible to a null pointer but not to other scalars. This is supported in all modern C++ compilers, including VC++ as of 2008. In older versions of GCC there is a similar feature, but then it was called __null.

Simple 3x3 matrix inverse code (C++)

I went ahead and wrote it in python since I think it's a lot more readable than in c++ for a problem like this. The function order is in order of operations for solving this by hand via this video. Just import this and call "print_invert" on your matrix.

def print_invert (matrix):
  i_matrix = invert_matrix (matrix)
  for line in i_matrix:
    print (line)

def invert_matrix (matrix):
  determinant = str (determinant_of_3x3 (matrix))
  cofactor = make_cofactor (matrix)
  trans_matrix = transpose_cofactor (cofactor)

  trans_matrix[:] = [[str (element) +'/'+ determinant for element in row] for row in trans_matrix]

  return trans_matrix

def determinant_of_3x3 (matrix):
  multiplication = 1
  neg_multiplication = 1
  total = 0
  for start_column in range (3):
    for row in range (3):
      multiplication *= matrix[row][(start_column+row)%3]
      neg_multiplication *= matrix[row][(start_column-row)%3]
    total += multiplication - neg_multiplication
    multiplication = neg_multiplication = 1
  if total == 0:
    total = 1
  return total

def make_cofactor (matrix):
  cofactor = [[0,0,0],[0,0,0],[0,0,0]]
  matrix_2x2 = [[0,0],[0,0]]
  # For each element in matrix...
  for row in range (3):
    for column in range (3):

      # ...make the 2x2 matrix in this inner loop
      matrix_2x2 = make_2x2_from_spot_in_3x3 (row, column, matrix)
      cofactor[row][column] = determinant_of_2x2 (matrix_2x2)

  return flip_signs (cofactor)

def make_2x2_from_spot_in_3x3 (row, column, matrix):
  c_count = 0
  r_count = 0
  matrix_2x2 = [[0,0],[0,0]]
  # ...make the 2x2 matrix in this inner loop
  for inner_row in range (3):
    for inner_column in range (3):
      if row is not inner_row and inner_column is not column:
        matrix_2x2[r_count % 2][c_count % 2] = matrix[inner_row][inner_column]
        c_count += 1
    if row is not inner_row:
      r_count += 1
  return matrix_2x2

def determinant_of_2x2 (matrix):
  total = matrix[0][0] * matrix [1][1]
  return total - (matrix [1][0] * matrix [0][1])

def flip_signs (cofactor):
  sign_pos = True 
  # For each element in matrix...
  for row in range (3):
    for column in range (3):
      if sign_pos:
        sign_pos = False
        cofactor[row][column] *= -1
        sign_pos = True
  return cofactor

def transpose_cofactor (cofactor):
  new_cofactor = [[0,0,0],[0,0,0],[0,0,0]]
  for row in range (3):
    for column in range (3):
      new_cofactor[column][row] = cofactor[row][column]
  return new_cofactor

How can I insert new line/carriage returns into an element.textContent?

nelek's answer is the best one posted so far, but it relies on setting the css value: white-space: pre, which might be undesirable.

I'd like to offer a different solution, which tries to tackle the real question that should've been asked here:

"How to insert untrusted text into a DOM element?"

If you trust the text, why not just use innerHTML?

domElement.innerHTML = trustedText.replace(/\r/g, '').replace(/\n/g, '<br>');

should be sufficient for all the reasonable cases.

If you decided you should use .textContent instead of .innerHTML, it means you don't trust the text that you're about to insert, right? This is a reasonable concern.

For example, you have a form where the user can create a post, and after posting it, the post text is stored in your database, and later on appended to pages whenever other users visit the relevant page.

If you use innerHTML here, you get a security breach. i.e., a user can post something like


(try to imagine that [] are <>, apparently stack overflow is appending text in unsafe ways!)

which won't trigger an alert if you use innerHTML, but it should give you an idea why using innerHTML can have issues. a smarter user would post

[img src="invalid_src" onerror="alert(1)"]

which would trigger an alert for every other user that visits the page. Now we have a problem. An even smarter user would put display: none on that img style, and make it post the current user's cookies to a cross domain site. Congratulations, all your user login details are now exposed on the internet.

So, the important thing to understand is, using innerHTML isn't wrong, it's perfect if you're just using it to build templates using only your own trusted developer code. The real question should've been "how do I append untrusted user text that has newlines to my HTML document".

This raises a question: which strategy do we use for newlines? do we use [br] elements? [p]s or [div]s?

Here is a short function that solves the problem:

function insertUntrustedText(domElement, untrustedText, newlineStrategy) {
    domElement.innerHTML = '';
    var lines = untrustedText.replace(/\r/g, '').split('\n');
    var linesLength = lines.length;
    if(newlineStrategy === 'br') {
        for(var i = 0; i < linesLength; i++) {
    else {
        for(var i = 0; i < linesLength; i++) {
            var lineElement = document.createElement(newlineStrategy);
            lineElement.textContent = lines[i];

You can basically throw this somewhere in your common_functions.js file and then just fire and forget whenever you need to append any user/api/etc -> untrusted text (i.e. not-written-by-your-own-developer-team) to your html pages.

usage example:

insertUntrustedText(document.querySelector('.myTextParent'), 'line1\nline2\r\nline3', 'br');

the parameter newlineStrategy accepts only valid dom element tags, so if you want [br] newlines, pass 'br', if you want each line in a [p] element, pass 'p', etc.

Angularjs - simple form submit

Sending data to some service page.

<form class="form-horizontal" role="form" ng-submit="submit_form()">
    <input type="text" name="user_id" ng-model = "formAdata.user_id">
    <input type="text" id="name" name="name" ng-model = "">

$scope.submit_form = function()
                        url: "http://localhost/services/test.php",
                        method: "POST",
                        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                        data: $.param($scope.formAdata)
                    }).success(function(data, status, headers, config) {
                        $scope.status = status;
                    }).error(function(data, status, headers, config) {
                        $scope.status = status;

Effectively use async/await with ASP.NET Web API

I would change your service layer to:

public Task<BackOfficeResponse<List<Country>>> ReturnAllCountries()
    return Task.Run(() =>
        return _service.Process<List<Country>>(BackOfficeEndpoint.CountryEndpoint, "returnCountries");

as you have it, you are still running your _service.Process call synchronously, and gaining very little or no benefit from awaiting it.

With this approach, you are wrapping the potentially slow call in a Task, starting it, and returning it to be awaited. Now you get the benefit of awaiting the Task.

Java: how to represent graphs?

If you need weighted edges and multigraphs, you might want to add another class Edge.

I would also recommend using generics to allow specifying which sub-class of Vertex and Edge are currently used. For example:

public class Graph<V extends Vertex> {
List<V> vertices;

When it comes to implementing graph algorithms, you could also define interfaces for your graph classes on which the algorithms can operate, so that you can play around with different implementations of the actual graph representation. For example, simple graphs that are well-connected might be better implemented by an adjacency matrix, sparser graphs might be represented by adjacency lists - it all depends...

BTW Building such structures efficiently can be quite challenging, so maybe you could give us some more details on what kind of job you would want to use them for? For more complex tasks I would suggest you have a look at the various Java graph libraries, to get some inspiration.

error: Your local changes to the following files would be overwritten by checkout

This error happens when the branch you are switching to, has changes that your current branch doesn't have.

If you are seeing this error when you try to switch to a new branch, then your current branch is probably behind one or more commits. If so, run:

git fetch

You should also remove dependencies which may also conflict with the destination branch.

For example, for iOS developers:

pod deintegrate

then try checking out a branch again.

If the desired branch isn't new you can either cherry pick a commit and fix the conflicts or stash the changes and then fix the conflicts.

1. Git Stash (recommended)

git stash
git checkout <desiredBranch>
git stash apply

2. Cherry pick (more work)

git add <your file>
git commit -m "Your message"
git log

Copy the sha of your commit. Then discard unwanted changes:

git checkout .
git checkout -- . 
git clean -f -fd -fx

Make sure your branch is up to date:

git fetch

Then checkout to the desired branch

git checkout <desiredBranch>

Then cherry pick the other commit:

git cherry-pick <theSha>

Now fix the conflict.

  1. Otherwise, your other option is to abandon your current branches changes with:
git checkout -f branch

CSS: Truncate table cells, but fit as much as possible

I've been recently working on it. Check out this jsFiddle test, try it yourself changing the width of the base table to check the behavior).

The solution is to embedded a table into another:

<table style="width: 200px;border:0;border-collapse:collapse">
            <td style="width: 100%;">
                <table style="width: 100%;border:0;border-collapse:collapse">
                                <div style="position: relative;overflow:hidden">
                                    <p style="overflow:hidden;text-overflow: ellipsis;position: absolute; top: 0pt; left: 0pt;width:100%">This cells has more content</p>
            <td style="white-space:nowrap">Less content here</td>

Is Fred now happy with Celldito's expansion?

Convert file path to a file URI?

The System.Uri constructor has the ability to parse full file paths and turn them into URI style paths. So you can just do the following:

var uri = new System.Uri("c:\\foo");
var converted = uri.AbsoluteUri;

Nested Recycler view height doesn't wrap its content

Simply wrap the content using RecyclerView with the Grid Layout

Image: Recycler as GridView layout

Just use the GridLayoutManager like this:

RecyclerView.LayoutManager mRecyclerGrid=new GridLayoutManager(this,3,LinearLayoutManager.VERTICAL,false);

You can set how many items should appear on a row (replace the 3).

Python+OpenCV: cv2.imwrite

wtluo, great ! May I propose a slight modification of your code 2. ? Here it is:

for i, detected_box in enumerate(detect_boxes):
    box = detected_box["box"]
    face_img = img[ box[1]:box[1] + box[3], box[0]:box[0] + box[2] ]
    cv2.imwrite("face-{:03d}.jpg".format(i+1), face_img)

Cannot find or open the PDB file in Visual Studio C++ 2010

PDB is a debug information file used by Visual Studio. These are system DLLs, which you don't have debug symbols for. Go to Tools->Options->Debugging->Symbols and select checkbox "Microsoft Symbol Servers", Visual Studio will download PDBs automatically. Or you may just ignore these warnings if you don't need to see correct call stack in these modules.

What are the various "Build action" settings in Visual Studio project properties and what do they do?

VS2010 has a property for 'Build Action', and also for 'Copy to Output Directory'. So an action of 'None' will still copy over to the build directory if the copy property is set to 'Copy if Newer' or 'Copy Always'.

So a Build Action of 'Content' should be reserved to indicate content you will access via 'Application.GetContentStream'

I used the 'Build Action' setting of 'None' and the 'Copy to Output Direcotry' setting of 'Copy if Newer' for some externally linked .config includes.


In C#, what is the difference between public, private, protected, and having no access modifier?

A graphical overview (summary in a nutshell)


Since static classes are sealed, they cannot be inherited (except from Object), so the keyword protected is invalid on static classes.

For the defaults if you put no access modifier in front, see here:
Default visibility for C# classes and members (fields, methods, etc.)?


enum                              public
non-nested classes / structs      internal
interfaces                        internal
delegates in namespace            internal
class/struct member(s)            private
delegates nested in class/struct  private


nested enum      public
nested interface public
nested class     private
nested struct    private

Also, there is the sealed-keyword, which makes a class not-inheritable.
Also, in VB.NET, the keywords are sometimes different, so here a cheat-sheet:

VB vs. CS equivalents

git: Your branch is ahead by X commits

Someone said you might be misreading your message, you aren't. This issue actually has to do with your <project>/.git/config file. In it will be a section similar to this:

[remote "origin"]
    url = <url>
    fetch = +refs/heads/*:refs/remotes/origin/*

If you remove the fetch line from your project's .git/config file you'll stop the "Your branch is ahead of 'origin/master' by N commits." annoyance from occurring.

Or so I hope. :)

R dplyr: Drop multiple columns

Beyond select(-one_of(drop.cols)) there are a couple other options for dropping columns using select() that do not involve defining all the specific column names (using the dplyr starwars sample data for some more variety in column names):

starwars %>% 
  select(-(name:mass)) %>%        # the range of columns from 'name' to 'mass'
  select(-contains('color')) %>%  # any column name that contains 'color'
  select(-starts_with('bi')) %>%  # any column name that starts with 'bi'
  select(-ends_with('er')) %>%    # any column name that ends with 'er'
  select(-matches('^f.+s$')) %>%  # any column name matching the regex pattern
  select_if(~!is.list(.)) %>%     # not by column name but by data type

# A tibble: 2 x 2
homeworld species
  <chr>     <chr>  
1 Tatooine  Human  
2 Tatooine  Droid 

Find files containing a given text

Try something like grep -r -n -i --include="*.html *.php *.js" searchstrinhere .

the -i makes it case insensitlve

the . at the end means you want to start from your current directory, this could be substituted with any directory.

the -r means do this recursively, right down the directory tree

the -n prints the line number for matches.

the --include lets you add file names, extensions. Wildcards accepted

For more info see:

Eclipse: The resource is not on the build path of a Java project

You can add the src folder to build path by:

  1. Select Java perspective.
  2. Right click on src folder.
  3. Select Build Path > Use a source folder.

And you are done. Hope this help.

EDIT: Refer to the Eclipse documentation

Declaring multiple variables in JavaScript

Besides maintainability, the first way eliminates possibility of accident global variables creation:

(function () {
var variable1 = "Hello, World!" // Semicolon is missed out accidentally
var variable2 = "Testing..."; // Still a local variable
var variable3 = 42;

While the second way is less forgiving:

(function () {
var variable1 = "Hello, World!" // Comma is missed out accidentally
    variable2 = "Testing...", // Becomes a global variable
    variable3 = 42; // A global variable as well

How do you rename a MongoDB database?

I tried doing.


and came to know that it has been Deprecated by the mongo community although it created the backup or renamed DB.

WARNING: db.copyDatabase is deprecated. See
        "note" : "Support for the copydb command has been deprecated. See",
        "ok" : 1

So not convinced with the above approach I had to take Dump of local using below command

mongodump --host --db DB_TobeRenamed --out E://FileName/

connected to Db.

use DB_TobeRenamed



then restored the DB with command.

mongorestore -host hostName -d Db_NewName E://FileName/