SyntaxFix.com - Programming Questions & Answers Hub For Beginners


Some Of The Best Answers From Latest Asked Questions

How can I echo a newline in a batch file?

Like the answer of Ken, but with the use of the delayed expansion.

setlocal EnableDelayedExpansion
(set \n=^
%=Do not remove this line=%
)

echo Line1!\n!Line2
echo Works also with quotes "!\n!line2"

First a single linefeed character is created and assigned to the \n-variable.
This works as the caret at the line end tries to escape the next character, but if this is a Linefeed it is ignored and the next character is read and escaped (even if this is also a linefeed).
Then you need a third linefeed to end the current instruction, else the third line would be appended to the LF-variable.
Even batch files have line endings with CR/LF only the LF are important, as the CR's are removed in this phase of the parser.

The advantage of using the delayed expansion is, that there is no special character handling at all.
echo Line1%LF%Line2 would fail, as the parser stops parsing at single linefeeds.

More explanations are at
SO:Long commands split over multiple lines in Vista/DOS batch (.bat) file
SO:How does the Windows Command Interpreter (CMD.EXE) parse scripts?

Edit: Avoid echo.

This doesn't answer the question, as the question was about single echo that can output multiple lines.

But despite the other answers who suggests the use of echo. to create a new line, it should be noted that echo. is the worst, as it's very slow and it can completly fail, as cmd.exe searches for a file named ECHO and try to start it.

For printing just an empty line, you could use one of

echo,
echo;
echo(
echo/
echo+
echo=

But the use of echo., echo\ or echo: should be avoided, as they can be really slow, depending of the location where the script will be executed, like a network drive.

What's the difference between an element and a node in XML?

The Node object is the primary data type for the entire DOM.

A node can be an element node, an attribute node, a text node, or any other of the node types explained in the "Node types" chapter.

An XML element is everything from (including) the element's start tag to (including) the element's end tag.

Direct casting vs 'as' operator?

The as keyword is good in asp.net when you use the FindControl method.

Hyperlink link = this.FindControl("linkid") as Hyperlink;
if (link != null)
{
     ...
}

This means you can operate on the typed variable rather then having to then cast it from object like you would with a direct cast:

object linkObj = this.FindControl("linkid");
if (link != null)
{
     Hyperlink link = (Hyperlink)linkObj;
}

It's not a huge thing, but it saves lines of code and variable assignment, plus it's more readable

How do I correct the character encoding of a file?

I found this question when searching for a solution to a code page issue i had with Chinese characters, but in the end my problem was just an issue with Windows not displaying them correctly in the UI.

In case anyone else has that same issue, you can fix it simply by changing the local in windows to China and then back again.

I found the solution here:

http://answers.microsoft.com/en-us/windows/forum/windows_7-desktop/how-can-i-get-chinesejapanese-characters-to/fdb1f1da-b868-40d1-a4a4-7acadff4aafa?page=2&auth=1

Also upvoted Gabriel's answer as looking at the data in notepad++ was what tipped me off about windows.

Showing the stack trace from a running Python application

I am in the GDB camp with the python extensions. Follow https://wiki.python.org/moin/DebuggingWithGdb, which means

  1. dnf install gdb python-debuginfo or sudo apt-get install gdb python2.7-dbg
  2. gdb python <pid of running process>
  3. py-bt

Also consider info threads and thread apply all py-bt.

Servlet for serving static content

I've had good results with FileServlet, as it supports pretty much all of HTTP (etags, chunking, etc.).

How do I get a list of all subdomains of a domain?

You can use:

$ host -l domain.com

Under the hood, this uses the AXFR query mentioned above. You might not be allowed to do this though. In that case, you'll get a transfer failed message.

Keyboard shortcut to paste clipboard content into command prompt window (Win XP)

If you use the clipboard manager Ditto (open source, gratis), you can simply use the shortcut to paste from Ditto, and it will paste the clipboard in CMD for you.

enter image description here

unsigned int vs. size_t

Classic C (the early dialect of C described by Brian Kernighan and Dennis Ritchie in The C Programming Language, Prentice-Hall, 1978) didn't provide size_t. The C standards committee introduced size_t to eliminate a portability problem

Explained in detail at embedded.com (with a very good example)

Inline style to act as :hover in CSS

If you are only debugging, you might use javascript to modify the css:

<a onmouseover="this.style.textDecoration='underline';" 
    onmouseout="this.style.textDecoration='none';">bar</a>

Best way to do Version Control for MS Excel

I have been looking into this too. It apears that the latest Team Foundation Server 2010 may have an Excel Add-In.

Here is a clue:

http://team-foundation-server.blogspot.com/2009/07/tf84037-there-was-problem-initializing.html

How can I measure the actual memory usage of an application or process?

Given some of the answers, to get the actual swap and RAM for a single application I came up with the following, say we want to know what 'firefox' is using

sudo smem | awk '/firefox/{swap+=$5; pss+=$7;}END{print "swap = "swap/1024" PSS = "pss/1024}'
or for libvirt;
sudo smem | awk '/libvirt/{swap+=$5; pss+=$7;}END{print "swap = "swap/1024" PSS = "pss/1024}'

this will give you the total in MB like so;

swap = 0 PSS = 2096.92
swap = 224.75 PSS = 421.455

Oracle Insert via Select from multiple tables where one table may not have a row

Try:

insert into account_type_standard (account_type_Standard_id, tax_status_id, recipient_id)
select account_type_standard_seq.nextval,
       ts.tax_status_id, 
       ( select r.recipient_id
         from recipient r
         where r.recipient_code = ?
       )
from tax_status ts
where ts.tax_status_code = ?

How do I get a range's address including the worksheet name, but not the workbook name, in Excel VBA?

You may need to write code that handles a range with multiple areas, which this does:

Public Function GetAddressWithSheetname(Range As Range, Optional blnBuildAddressForNamedRangeValue As Boolean = False) As String

    Const Seperator As String = ","

    Dim WorksheetName As String
    Dim TheAddress As String
    Dim Areas As Areas
    Dim Area As Range

    WorksheetName = "'" & Range.Worksheet.Name & "'"

    For Each Area In Range.Areas
'           ='Sheet 1'!$H$8:$H$15,'Sheet 1'!$C$12:$J$12
        TheAddress = TheAddress & WorksheetName & "!" & Area.Address(External:=False) & Seperator

    Next Area

    GetAddressWithSheetname = Left(TheAddress, Len(TheAddress) - Len(Seperator))

    If blnBuildAddressForNamedRangeValue Then
        GetAddressWithSheetname = "=" & GetAddressWithSheetname
    End If

End Function

iPhone viewWillAppear not firing

In my case problem was with custom transition animation. When set modalPresentationStyle = .custom viewWillAppear not called

in custom transition animation class need call methods: beginAppearanceTransition and endAppearanceTransition

Read binary file as string in Ruby

To avoid leaving the file open, it is best to pass a block to File.open. This way, the file will be closed after the block executes.

contents = File.open('path-to-file.tar.gz', 'rb') { |f| f.read }

How to build a Debian/Ubuntu package from source?

For what you want to do, you probably want to use the debian source diff, so your package is similar to the official one apart from the upstream version used. You can download the source diff from packages.debian.org, or can get it along with the .dsc and the original source archive by using "apt-get source".

Then you unpack your new version of the upstream source, change into that directory, and apply the diff you downloaded by doing

zcat ~/downloaded.diff.gz | patch -p1
chmod +x debian/rules

Then make the changes you wanted to compile options, and build the package by doing

dpkg-buildpackage -rfakeroot -us -uc

Request UAC elevation from within a Python script?

It took me a little while to get dguaraglia's answer working, so in the interest of saving others time, here's what I did to implement this idea:

import os
import sys
import win32com.shell.shell as shell
ASADMIN = 'asadmin'

if sys.argv[-1] != ASADMIN:
    script = os.path.abspath(sys.argv[0])
    params = ' '.join([script] + sys.argv[1:] + [ASADMIN])
    shell.ShellExecuteEx(lpVerb='runas', lpFile=sys.executable, lpParameters=params)
    sys.exit(0)

How do you check for permissions to write to a directory or file?

Wow...there is a lot of low-level security code in this thread -- most of which did not work for me, either -- although I learned a lot in the process. One thing that I learned is that most of this code is not geared to applications seeking per user access rights -- it is for Administrators wanting to alter rights programmatically, which -- as has been pointed out -- is not a good thing. As a developer, I cannot use the "easy way out" -- by running as Administrator -- which -- I am not one on the machine that runs the code, nor are my users -- so, as clever as these solutions are -- they are not for my situation, and probably not for most rank and file developers, either.

Like most posters of this type of question -- I initially felt it was "hackey", too -- I have since decided that it is perfectly alright to try it and let the possible exception tell you exactly what the user's rights are -- because the information I got did not tell me what the rights actually were. The code below -- did.

  Private Function CheckUserAccessLevel(folder As String) As Boolean
Try
  Dim newDir As String = String.Format("{0}{1}{2}",
                                       folder,
                                       If(folder.EndsWith("\"),
                                          "",
                                          "\"),
                                       "LookWhatICanDo")
  Dim lookWhatICanDo = Directory.CreateDirectory(newDir)

  Directory.Delete(newDir)
  Return True

Catch ex As Exception
  Return False
End Try

End Function

How can I let a table's body scroll but keep its head fixed in place?

If its ok to use JavaScript here is my solution Create a table set fixed width on all columns (pixels!) add the class Scrollify to the table and add this javascript + jquery 1.4.x set height in css or style!

Tested in: Opera, Chrome, Safari, FF, IE5.5(Epic script fail), IE6, IE7, IE8, IE9

//Usage add Scrollify class to a table where all columns (header and body) have a fixed pixel width
$(document).ready(function () {
    $("table.Scrollify").each(function (index, element) {
        var header = $(element).children().children().first();
        var headerHtml = header.html();
        var width = $(element).outerWidth();
        var height = parseInt($(element).css("height")) - header.outerHeight();
        $(element).height("auto");
        header.remove();
        var html = "<table style=\"border-collapse: collapse;\" border=\"1\" rules=\"all\" cellspacing=\"0\"><tr>" + headerHtml +
                         "</tr></table><div style=\"overflow: auto;border:0;margin:0;padding:0;height:" + height + "px;width:" + (parseInt(width) + scrollbarWidth()) + "px;\">" +
                         $(element).parent().html() + "</div>";

        $(element).parent().html(html);
    });
});


//Function source: http://www.fleegix.org/articles/2006-05-30-getting-the-scrollbar-width-in-pixels
//License: Apache License, version 2
function scrollbarWidth() {
    var scr = null;
    var inn = null;
    var wNoScroll = 0;
    var wScroll = 0;

    // Outer scrolling div
    scr = document.createElement('div');
    scr.style.position = 'absolute';
    scr.style.top = '-1000px';
    scr.style.left = '-1000px';
    scr.style.width = '100px';
    scr.style.height = '50px';
    // Start with no scrollbar
    scr.style.overflow = 'hidden';

    // Inner content div
    inn = document.createElement('div');
    inn.style.width = '100%';
    inn.style.height = '200px';

    // Put the inner div in the scrolling div
    scr.appendChild(inn);
    // Append the scrolling div to the doc
    document.body.appendChild(scr);

    // Width of the inner div sans scrollbar
    wNoScroll = inn.offsetWidth;
    // Add the scrollbar
    scr.style.overflow = 'auto';
    // Width of the inner div width scrollbar
    wScroll = inn.offsetWidth;

    // Remove the scrolling div from the doc
    document.body.removeChild(
        document.body.lastChild);

    // Pixel width of the scroller
    return (wNoScroll - wScroll);
}

Edit: Fixed height.

Are there constants in JavaScript?

in Javascript already exists constants. You define a constant like this:

const name1 = value;

This cannot change through reassignment.

How do I simulate a low bandwidth, high latency environment?

I've been looking for an easy to use tool for this type of testing for a while now. I just came across this the other day: Network Delay Simulator

If you're running Windows, you should check it out. It was super easy to set up and get going, and seems to work really well. It allows you to define bandwidth, latency, and packet loss in each direction. The other really nice thing is that you can define "Flow Match Conditions" so that it only affects the traffic you want it to. Oh yeah, and it's free.

Is it possible to modify a registry entry via a .bat/.cmd script?

@Franci Penov - modify is possible in the sense of overwrite with /f, eg

reg add "HKCU\Software\etc\etc" /f /v "value" /t REG_SZ /d "Yes"

throwing exceptions out of a destructor

Throwing an exception out of a destructor is dangerous.
If another exception is already propagating the application will terminate.

#include <iostream>

class Bad
{
    public:
        // Added the noexcept(false) so the code keeps its original meaning.
        // Post C++11 destructors are by default `noexcept(true)` and
        // this will (by default) call terminate if an exception is
        // escapes the destructor.
        //
        // But this example is designed to show that terminate is called
        // if two exceptions are propagating at the same time.
        ~Bad() noexcept(false)
        {
            throw 1;
        }
};
class Bad2
{
    public:
        ~Bad2()
        {
            throw 1;
        }
};


int main(int argc, char* argv[])
{
    try
    {
        Bad   bad;
    }
    catch(...)
    {
        std::cout << "Print This\n";
    }

    try
    {
        if (argc > 3)
        {
            Bad   bad; // This destructor will throw an exception that escapes (see above)
            throw 2;   // But having two exceptions propagating at the
                       // same time causes terminate to be called.
        }
        else
        {
            Bad2  bad; // The exception in this destructor will
                       // cause terminate to be called.
        }
    }
    catch(...)
    {
        std::cout << "Never print this\n";
    }

}

This basically boils down to:

Anything dangerous (i.e. that could throw an exception) should be done via public methods (not necessarily directly). The user of your class can then potentially handle these situations by using the public methods and catching any potential exceptions.

The destructor will then finish off the object by calling these methods (if the user did not do so explicitly), but any exceptions throw are caught and dropped (after attempting to fix the problem).

So in effect you pass the responsibility onto the user. If the user is in a position to correct exceptions they will manually call the appropriate functions and processes any errors. If the user of the object is not worried (as the object will be destroyed) then the destructor is left to take care of business.

An example:

std::fstream

The close() method can potentially throw an exception. The destructor calls close() if the file has been opened but makes sure that any exceptions do not propagate out of the destructor.

So if the user of a file object wants to do special handling for problems associated to closing the file they will manually call close() and handle any exceptions. If on the other hand they do not care then the destructor will be left to handle the situation.

Scott Myers has an excellent article about the subject in his book "Effective C++"

Edit:

Apparently also in "More Effective C++"
Item 11: Prevent exceptions from leaving destructors

Windows batch command(s) to read first line from text file

for /f "delims=" %a in (downing.txt) do echo %a & pause>nul

Prints 1st line, then waits for user to press a key to print next line. After printing required lines, press Ctrl+C to stop.

@Ross Presser: This method prints lines only, not prepend line numbers.

Command line .cmd/.bat script, how to get directory of running script

for /F "eol= delims=~" %%d in ('CD') do set curdir=%%d

pushd %curdir%

Source

How can I sanitize user input with PHP?

One trick that can help in the specific circumstance where you have a page like /mypage?id=53 and you use the id in a WHERE clause is to ensure that id definitely is an integer, like so:

if (isset($_GET['id'])) {
  $id = $_GET['id'];
  settype($id, 'integer');
  $result = mysql_query("SELECT * FROM mytable WHERE id = '$id'");
  # now use the result
}

But of course that only cuts out one specific attack, so read all the other answers. (And yes I know that the code above isn't great, but it shows the specific defence.)

What is declarative programming?

Declarative programming is "the act of programming in languages that conform to the mental model of the developer rather than the operational model of the machine".

The difference between declarative and imperative programming is well illustrated by the problem of parsing structured data.

An imperative program would use mutually recursive functions to consume input and generate data. A declarative program would express a grammar that defines the structure of the data so that it can then be parsed.

The difference between these two approaches is that the declarative program creates a new language that is more closely mapped to the mental model of the problem than is its host language.

How do you test that a Python function throws an exception?

Your code should follow this pattern (this is a unittest module style test):

def test_afunction_throws_exception(self):
    try:
        afunction()
    except ExpectedException:
        pass
    except Exception:
       self.fail('unexpected exception raised')
    else:
       self.fail('ExpectedException not raised')

On Python < 2.7 this construct is useful for checking for specific values in the expected exception. The unittest function assertRaises only checks if an exception was raised.

postgreSQL - psql \i : how to execute script in a given path

Try this, I work myself to do so

\i 'somedir\\script2.sql'

How do you do a deep copy of an object in .NET?

I believe that the BinaryFormatter approach is relatively slow (which came as a surprise to me!). You might be able to use ProtoBuf .NET for some objects if they meet the requirements of ProtoBuf. From the ProtoBuf Getting Started page (http://code.google.com/p/protobuf-net/wiki/GettingStarted):

Notes on types supported:

Custom classes that:

  • Are marked as data-contract
  • Have a parameterless constructor
  • For Silverlight: are public
  • Many common primitives, etc.
  • Single dimension arrays: T[]
  • List<T> / IList<T>
  • Dictionary<TKey, TValue> / IDictionary<TKey, TValue>
  • any type which implements IEnumerable<T> and has an Add(T) method

The code assumes that types will be mutable around the elected members. Accordingly, custom structs are not supported, since they should be immutable.

If your class meets these requirements you could try:

public static void deepCopy<T>(ref T object2Copy, ref T objectCopy)
{
    using (var stream = new MemoryStream())
    {
        Serializer.Serialize(stream, object2Copy);
        stream.Position = 0;
        objectCopy = Serializer.Deserialize<T>(stream);
    }
}

Which is VERY fast indeed...

Edit:

Here is working code for a modification of this (tested on .NET 4.6). It uses System.Xml.Serialization and System.IO. No need to mark classes as serializable.

public void DeepCopy<T>(ref T object2Copy, ref T objectCopy)
{
    using (var stream = new MemoryStream())
    {
        var serializer = new XS.XmlSerializer(typeof(T));

        serializer.Serialize(stream, object2Copy);
        stream.Position = 0;
        objectCopy = (T)serializer.Deserialize(stream);
    }
}

How do you redirect to a page using the POST verb?

If you want to pass data between two actions during a redirect without include any data in the query string, put the model in the TempData object.

ACTION

TempData["datacontainer"] = modelData;

VIEW

var modelData= TempData["datacontainer"] as ModelDataType; 

TempData is meant to be a very short-lived instance, and you should only use it during the current and the subsequent requests only! Since TempData works this way, you need to know for sure what the next request will be, and redirecting to another view is the only time you can guarantee this.

Therefore, the only scenario where using TempData will reliably work is when you are redirecting.

Optimistic vs. Pessimistic locking

There are basically two most popular answers. The first one basically says

Optimistic needs a three-tier architectures where you do not necessarily maintain a connection to the database for your session whereas Pessimistic Locking is when you lock the record for your exclusive use until you have finished with it. It has much better integrity than optimistic locking you need either a direct connection to the database.

Another answer is

optimistic (versioning) is faster because of no locking but (pessimistic) locking performs better when contention is high and it is better to prevent the work rather than discard it and start over.

or

Optimistic locking works best when you have rare collisions

As it is put on this page.

I created my answer to explain how "keep connection" is related to "low collisions".

To understand which strategy is best for you, think not about the Transactions Per Second your DB has but the duration of a single transaction. Normally, you open trasnaction, performa operation and close the transaction. This is a short, classical transaction ANSI had in mind and fine to get away with locking. But, how do you implement a ticket reservation system where many clients reserve the same rooms/seats at the same time?

You browse the offers, fill in the form with lots of available options and current prices. It takes a lot of time and options can become obsolete, all the prices invalid between you started to fill the form and press "I agree" button because there was no lock on the data you have accessed and somebody else, more agile, has intefered changing all the prices and you need to restart with new prices.

You could lock all the options as you read them, instead. This is pessimistic scenario. You see why it sucks. Your system can be brought down by a single clown who simply starts a reservation and goes smoking. Nobody can reserve anything before he finishes. Your cash flow drops to zero. That is why, optimistic reservations are used in reality. Those who dawdle too long have to restart their reservation at higher prices.

In this optimistic approach you have to record all the data that you read (as in mine Repeated Read) and come to the commit point with your version of data (I want to buy shares at the price you displayed in this quote, not current price). At this point, ANSI transaction is created, which locks the DB, checks if nothing is changed and commits/aborts your operation. IMO, this is effective emulation of MVCC, which is also associated with Optimistic CC and also assumes that your transaction restarts in case of abort, that is you will make a new reservation. A transaction here involves a human user decisions.

I am far from understanding how to implement the MVCC manually but I think that long-running transactions with option of restart is the key to understanding the subject. Correct me if I am wrong anywhere. My answer was motivated by this Alex Kuznecov chapter.

Can attributes be added dynamically in C#?

Attributes are static metadata. Assemblies, modules, types, members, parameters, and return values aren't first-class objects in C# (e.g., the System.Type class is merely a reflected representation of a type). You can get an instance of an attribute for a type and change the properties if they're writable but that won't affect the attribute as it is applied to the type.

CASCADE DELETE just once

If you really want DELETE FROM some_table CASCADE; which means "remove all rows from table some_table", you can use TRUNCATE instead of DELETE and CASCADE is always supported. However, if you want to use selective delete with a where clause, TRUNCATE is not good enough.

USE WITH CARE - This will drop all rows of all tables which have a foreign key constraint on some_table and all tables that have constraints on those tables, etc.

Postgres supports CASCADE with TRUNCATE command:

TRUNCATE some_table CASCADE;

Handily this is transactional (i.e. can be rolled back), although it is not fully isolated from other concurrent transactions, and has several other caveats. Read the docs for details.

Getting Spring Application Context

If the object that needs access to the container is a bean in the container, just implement the BeanFactoryAware or ApplicationContextAware interfaces.

If an object outside the container needs access to the container, I've used a standard GoF singleton pattern for the spring container. That way, you only have one singleton in your application, the rest are all singleton beans in the container.

Convert from MySQL datetime to another format with PHP

Forget all. Just use:

$date = date("Y-m-d H:i:s",strtotime(str_replace('/','-',$date)))

Key Presses in Python

If you're platform is Windows, I wouldn't actually recommend Python. Instead, look into Autohotkey. Trust me, I love Python, but in this circumstance a macro program is the ideal tool for the job. Autohotkey's scripting is only decent (in my opinion), but the ease of simulating input will save you countless hours. Autohotkey scripts can be "compiled" as well so you don't need the interpreter to run the script.

Also, if this is for something on the Web, I recommend iMacros. It's a firefox plugin and therefore has a much better integration with websites. For example, you can say "write 1000 'a's in this form" instead of "simulate a mouseclick at (319,400) and then press 'a' 1000 times".

For Linux, I unfortunately have not been able to find a good way to easily create keyboard/mouse macros.

How do I programmatically force an onchange event on an input?

Taken from the bottom of QUnit

function triggerEvent( elem, type, event ) {
    if ( $.browser.mozilla || $.browser.opera ) {
        event = document.createEvent("MouseEvents");
        event.initMouseEvent(type, true, true, elem.ownerDocument.defaultView,
            0, 0, 0, 0, 0, false, false, false, false, 0, null);
        elem.dispatchEvent( event );
    } else if ( $.browser.msie ) {
        elem.fireEvent("on"+type);
    }
}

You can, of course, replace the $.browser stuff to your own browser detection methods to make it jQuery independent.

To use this function:

var event;
triggerEvent(ele, "change", event);

This will basically fire the real DOM event as if something had actually changed.

Searching for UUIDs in text with regex

@ivelin: UUID can have capitals. So you'll either need to toLowerCase() the string or use:

[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}

Would have just commented this but not enough rep :)

Change the URL in the browser without loading the new page using JavaScript

Browser security settings prevent people from modifying the displayed url directly. You could imagine the phishing vulnerabilities that would cause.

Only reliable way to change the url without changing pages is to use an internal link or hash. e.g.: http://site.com/page.html becomes http://site.com/page.html#item1 . This technique is often used in hijax(AJAX + preserve history).

When doing this I'll often just use links for the actions with the hash as the href, then add click events with jquery that use the requested hash to determine and delegate the action.

I hope that sets you on the right path.

Any way to make a WPF textblock selectable?

I've implemented SelectableTextBlock in my opensource controls library. You can use it like this:

<jc:SelectableTextBlock Text="Some text" />

Get integer value of the current year in Java

As some people answered above:

If you want to use the variable later, better use:

int year;

year = Calendar.getInstance().get(Calendar.YEAR);

If you need the year for just a condition you better use:

Calendar.getInstance().get(Calendar.YEAR)

For example using it in a do while that checks introduced year is not less than the current year-200 or more than the current year (Could be birth year):

import java.util.Calendar;
import java.util.Scanner;

public static void main (String[] args){

    Scanner scannernumber = new Scanner(System.in);
    int year;

    /*Checks that the year is not higher than the current year, and not less than the current year - 200 years.*/

    do{
        System.out.print("Year (Between "+((Calendar.getInstance().get(Calendar.YEAR))-200)+" and "+Calendar.getInstance().get(Calendar.YEAR)+") : ");
        year = scannernumber.nextInt();
    }while(year < ((Calendar.getInstance().get(Calendar.YEAR))-200) || year > Calendar.getInstance().get(Calendar.YEAR));
}

Get last n lines of a file, similar to tail

Simple and fast solution with mmap:

import mmap
import os

def tail(filename, n):
    """Returns last n lines from the filename. No exception handling"""
    size = os.path.getsize(filename)
    with open(filename, "rb") as f:
        # for Windows the mmap parameters are different
        fm = mmap.mmap(f.fileno(), 0, mmap.MAP_SHARED, mmap.PROT_READ)
        try:
            for i in xrange(size - 1, -1, -1):
                if fm[i] == '\n':
                    n -= 1
                    if n == -1:
                        break
            return fm[i + 1 if i else 0:].splitlines()
        finally:
            fm.close()

Difference between staticmethod and classmethod

You might want to consider the difference between:

class A:
    def foo():  # no self parameter, no decorator
        pass

and

class B:
    @staticmethod
    def foo():  # no self parameter
        pass

This has changed between python2 and python3:

python2:

>>> A.foo()
TypeError
>>> A().foo()
TypeError
>>> B.foo()
>>> B().foo()

python3:

>>> A.foo()
>>> A().foo()
TypeError
>>> B.foo()
>>> B().foo()

So using @staticmethod for methods only called directly from the class has become optional in python3. If you want to call them from both class and instance, you still need to use the @staticmethod decorator.

The other cases have been well covered by unutbus answer.

How do I format a String in an email so Outlook will print the line breaks?

\r\n will not work until you set body type as text.

message.setBody(MessageBody.getMessageBodyFromText(msg));
BodyType type = BodyType.Text;
message.getBody().setBodyType(type);

Catch multiple exceptions at once?

In c# 6.0,Exception Filters is improvements for exception handling

try
{
    DoSomeHttpRequest();
}
catch (System.Web.HttpException e)
{
    switch (e.GetHttpCode())
    {
        case 400:
            WriteLine("Bad Request");
        case 500:
            WriteLine("Internal Server Error");
        default:
            WriteLine("Generic Error");
    }
}

java.net.SocketException: Software caused connection abort: recv failed

This error occurs when a connection is closed abruptly (when a TCP connection is reset while there is still data in the send buffer). The condition is very similar to a much more common 'Connection reset by peer'. It can happen sporadically when connecting over the Internet, but also systematically if the timing is right (e.g. with keep-alive connections on localhost).

An HTTP client should just re-open the connection and retry the request. It is important to understand that when a connection is in this state, there is no way out of it other than to close it. Any attempt to send or receive will produce the same error.

Don't use URL.open(), use Apache-Commons HttpClient which has a retry mechanism, connection pooling, keep-alive and many other features.

Sample usage:

HttpClient httpClient = HttpClients.custom()
            .setConnectionTimeToLive(20, TimeUnit.SECONDS)
            .setMaxConnTotal(400).setMaxConnPerRoute(400)
            .setDefaultRequestConfig(RequestConfig.custom()
                    .setSocketTimeout(30000).setConnectTimeout(5000).build())
            .setRetryHandler(new DefaultHttpRequestRetryHandler(5, true))
            .build();
// the httpClient should be re-used because it is pooled and thread-safe.

HttpGet request = new HttpGet(uri);
HttpResponse response = httpClient.execute(request);
reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
// handle response ...

What are the different types of indexes, what are the benefits of each?

Conventional wisdom suggests that index choice should be based on cardinality. They'll say,

For a low cardinality column like GENDER, use bitmap. For a high cardinality like LAST_NAME, use b-tree.

This is not the case with Oracle, where index choice should instead be based on the type of application (OLTP vs. OLAP). DML on tables with bitmap indexes can cause serious lock contention. On the other hand, the Oracle CBO can easily combine multiple bitmap indexes together, and bitmap indexes can be used to search for nulls. As a general rule:

For an OLTP system with frequent DML and routine queries, use btree. For an OLAP system with infrequent DML and adhoc queries, use bitmap.

I'm not sure if this applies to other databases, comments are welcome. The following articles discuss the subject further:

Setting environment variables on OS X

Update (2017-08-04)

As of (at least) macOS 10.12.6 (Sierra) this method seems to have stopped working for Apache httpd (for both the system and the user option of launchctl config). Other programs do not seem to be affected. It is conceivable that this is a bug in httpd.

Original answer

This concerns OS X 10.10+ (10.11+ specifically due to rootless mode where /usr/bin is no longer writeable).

I've read in multiple places that using launchctl setenv PATH <new path> to set the PATH variable does not work due to a bug in OS X (which seems true from personal experience). I found that there's another way the PATH can be set for applications not launched from the shell:

sudo launchctl config user path <new path>

This option is documented in the launchctl man page:

config system | user parameter value

Sets persistent configuration information for launchd(8) domains. Only the system domain and user domains may be configured. The location of the persistent storage is an implementation detail, and changes to that storage should only be made through this subcommand. A reboot is required for changes made through this subcommand to take effect.

[...]

path

Sets the PATH environment variable for all services within the target domain to the string value. The string value should conform to the format outlined for the PATH environment variable in environ(7). Note that if a service specifies its own PATH, the service-specific environment variable will take precedence.

NOTE: This facility cannot be used to set general environment variables for all services within the domain. It is intentionally scoped to the PATH environment vari- able and nothing else for security reasons.

I have confirmed this to work with a GUI application started from Finder (which uses getenv to get PATH). Note that you only have to do this once and the change will be persistent through reboots.

How to identify unused CSS definitions from multiple CSS files in a project

I have just found this site – http://unused-css.com/

Looks good but I would need to thoroughly check its outputted 'clean' css before uploading it to any of my sites.

Also as with all these tools I would need to check it didn't strip id's and classes with no style but are used as JavaScript selectors.

The below content is taken from http://unused-css.com/ so credit to them for recommending other solutions:

Latish Sehgal has written a windows application to find and remove unused CSS classes. I haven't tested it but from the description, you have to provide the path of your html files and one CSS file. The program will then list the unused CSS selectors. From the screenshot, it looks like there is no way to export this list or download a new clean CSS file. It also looks like the service is limited to one CSS file. If you have multiple files you want to clean, you have to clean them one by one.

Dust-Me Selectors is a Firefox extension (for v1.5 or later) that finds unused CSS selectors. It extracts all the selectors from all the stylesheets on the page you're viewing, then analyzes that page to see which of those selectors are not used. The data is then stored so that when testing subsequent pages, selectors can be crossed off the list as they're encountered. This tool is supposed to be able to spider a whole website but I unfortunately could make it work. Also, I don't believe you can configure and download the CSS file with the styles removed.

Topstyle is a windows application including a bunch of tools to edit CSS. I haven't tested it much but it looks like it has the ability to removed unused CSS selectors. This software costs 80 USD.

Liquidcity CSS cleaner is a php script that uses regular expressions to check the styles of one page. It will tell you the classes that aren't available in the HTML code. I haven't tested this solution.

Deadweight is a CSS coverage tool. Given a set of stylesheets and a set of URLs, it determines which selectors are actually used and lists which can be "safely" deleted. This tool is a ruby module and will only work with rails website. The unused selectors have to be manually removed from the CSS file.

Helium CSS is a javascript tool for discovering unused CSS across many pages on a web site. You first have to install the javascript file to the page you want to test. Then, you have to call a helium function to start the cleaning.

UnusedCSS.com is web application with an easy to use interface. Type the url of a site and you will get a list of CSS selectors. For each selector, a number indicates how many times a selector is used. This service has a few limitations. The @import statement is not supported. You can't configure and download the new clean CSS file.

CSSESS is a bookmarklet that helps you find unused CSS selectors on any site. This tool is pretty easy to use but it won't let you configure and download clean CSS files. It will only list unused CSS files.

Difference between drop table and truncate table?

I think you means the difference between DELETE TABLE and TRUNCATE TABLE.

DROP TABLE

remove the table from the database.

DELETE TABLE

without a condition delete all rows. If there are trigger and references then this will process for every row. Also a index will be modify if there one.

TRUNCATE TABLE

set the row count zero and without logging each row. That it is many faster as the other both.

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

Performance

Today 2020.12.17 I perform tests on MacOs HighSierra 10.13.6 on Chrome v87, Safari v13.1.2 and Firefox v83 for chosen solutions.

Results

I compare only solutions A-F because they give valid result for all cased used in snippet in details section. For all browsers

  • solution based on in (A) is fast or fastest
  • solution (E) is fastest for chrome for big objects and fastest for firefox for small arrays if key not exists
  • solution (F) is fastest (~ >10x than other solutions) for small arrays
  • solutions (D,E) are quite fast
  • solution based on losash has (B) is slowest

enter image description here

Details

I perform 4 tests cases:

  • when object has 10 fields and searched key exists - you can run it HERE
  • when object has 10 fields and searched key not exists - you can run it HERE
  • when object has 10000 fields and searched key exists - you can run it HERE
  • when object has 10000 fields and searched key exists - you can run it HERE

Below snippet presents differences between solutions A B C D E F G H I J K

_x000D_
_x000D_
// SO https://stackoverflow.com/q/135448/860099


// src: https://stackoverflow.com/a/14664748/860099
function A(x) {
  return 'key' in x
}

// src: https://stackoverflow.com/a/11315692/860099
function B(x) {
  return _.has(x, 'key')
}

// src: https://stackoverflow.com/a/40266120/860099
function C(x) {
  return Reflect.has( x, 'key')
}

// src: https://stackoverflow.com/q/135448/860099
function D(x) {
  return x.hasOwnProperty('key')
}

// src: https://stackoverflow.com/a/11315692/860099
function E(x) {
  return Object.prototype.hasOwnProperty.call(x, 'key')
}

// src: https://stackoverflow.com/a/136411/860099
function F(x) {
  function hasOwnProperty(obj, prop) {
      var proto = obj.__proto__ || obj.constructor.prototype;
      return (prop in obj) &&
          (!(prop in proto) || proto[prop] !== obj[prop]);
  }
  return hasOwnProperty(x,'key')
}

// src: https://stackoverflow.com/a/135568/860099
function G(x) {
  return typeof(x.key) !== 'undefined'
}

// src: https://stackoverflow.com/a/22740939/860099
function H(x) {
  return x.key !== undefined
}

// src: https://stackoverflow.com/a/38332171/860099
function I(x) {
  return !!x.key
}

// src: https://stackoverflow.com/a/41184688/860099
function J(x) {
  return !!x['key']
}

// src: https://stackoverflow.com/a/54196605/860099
function K(x) {
  return Boolean(x.key)
}


// --------------------
// TEST
// --------------------

let x1 = {'key': 1};
let x2 = {'key': "1"};
let x3 = {'key': true};
let x4 = {'key': []};
let x5 = {'key': {}};
let x6 = {'key': ()=>{}};
let x7 = {'key': ''};
let x8 = {'key': 0};
let x9 = {'key': false};
let x10= {'key': undefined};
let x11= {'nokey': 1};



let b= x=> x ? 1:0;

console.log('  1 2 3 4 5 6 7 8 9 10 11');

[A,B,C,D,E,F,G,H,I,J,K ].map(f=> {  
  console.log(
    `${f.name} ${b(f(x1))} ${b(f(x2))} ${b(f(x3))} ${b(f(x4))} ${b(f(x5))} ${b(f(x6))} ${b(f(x7))} ${b(f(x8))} ${b(f(x9))} ${b(f(x10))}  ${b(f(x11))} `
  )})
  
console.log('\nLegend: Columns (cases)');
console.log('1.  key = 1 ');
console.log('2.  key = "1" ');
console.log('3.  key = true ');
console.log('4.  key = [] ');
console.log('5.  key = {} ');
console.log('6.  key = ()=>{} ');
console.log('7.  key = "" ');
console.log('8.  key = 0 ');
console.log('9.  key = false ');
console.log('10. key = undefined ');
console.log('11. no-key ');
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js" integrity="sha512-90vH1Z83AJY9DmlWa8WkjkV79yfS2n2Oxhsi2dZbIv0nC4E6m5AbH8Nh156kkM7JePmqD6tcZsfad1ueoaovww==" crossorigin="anonymous"> </script>
  
This shippet only presents functions used in performance tests - it not perform tests itself!
_x000D_
_x000D_
_x000D_

And here are example results for chrome

enter image description here

How do I use reflection to invoke a private method?

And if you really want to get yourself in trouble, make it easier to execute by writing an extension method:

static class AccessExtensions
{
    public static object call(this object o, string methodName, params object[] args)
    {
        var mi = o.GetType ().GetMethod (methodName, System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance );
        if (mi != null) {
            return mi.Invoke (o, args);
        }
        return null;
    }
}

And usage:

    class Counter
    {
        public int count { get; private set; }
        void incr(int value) { count += value; }
    }

    [Test]
    public void making_questionable_life_choices()
    {
        Counter c = new Counter ();
        c.call ("incr", 2);             // "incr" is private !
        c.call ("incr", 3);
        Assert.AreEqual (5, c.count);
    }

Difference between ref and out parameters in .NET

They are subtly different.

An out parameter does not need to be initialized by the callee before being passed to the method. Therefore, any method with an out parameter

  • Cannot read the parameter before assigning a value to it
  • Must assign a value to it before returning

This is used for a method which needs to overwrite its argument regardless of its previous value.


A ref parameter must be initialized by the callee before passing it to the method. Therefore, any method with a ref parameter

  • Can inspect the value before assigning it
  • Can return the original value, untouched

This is used for a method which must (e.g.) inspect its value and validate it or normalize it.

What's the difference between JavaScript and JScript?

Just different names for what is really ECMAScript. John Resig has a good explanation.

Here's the full version breakdown:

  • IE 6-7 support JScript 5 (which is equivalent to ECMAScript 3, JavaScript 1.5)
  • IE 8 supports JScript 6 (which is equivalent to ECMAScript 3, JavaScript 1.5 - more bug fixes over JScript 5)
  • Firefox 1.0 supports JavaScript 1.5 (ECMAScript 3 equivalent)
  • Firefox 1.5 supports JavaScript 1.6 (1.5 + Array Extras + E4X + misc.)
  • Firefox 2.0 supports JavaScript 1.7 (1.6 + Generator + Iterators + let + misc.)
  • Firefox 3.0 supports JavaScript 1.8 (1.7 + Generator Expressions + Expression Closures + misc.)
  • The next version of Firefox will support JavaScript 1.9 (1.8 + To be determined)
  • Opera supports a language that is equivalent to ECMAScript 3 + Getters and Setters + misc.
  • Safari supports a language that is equivalent to ECMAScript 3 + Getters and Setters + misc.

Should you always favor xrange() over range()?

A good example given in book: Practical Python By Magnus Lie Hetland

>>> zip(range(5), xrange(100000000))
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]

I wouldn’t recommend using range instead of xrange in the preceding example—although only the first five numbers are needed, range calculates all the numbers, and that may take a lot of time. With xrange, this isn’t a problem because it calculates only those numbers needed.

Yes I read @Brian's answer: In python 3, range() is a generator anyway and xrange() does not exist.

Python Library Path

import sys
sys.path

How do you perform address validation?

There is no global solution. For any given country it is at best rather tricky.

In the UK, the PostOffice controlls postal addresses, and can provide (at a cost) address information for validation purposes.

Government agencies also keep an extensive list of addresses, and these are centrally collated in the NLPG (National Land and Property Gazetteer).

Actually validating against these lists is very difficult. Most people don't even know exactly how their address as it is held by the PostOffice. Some businesses don't even know what number they are on a particular street.

Your best bet is to approach a company that specialises in this kind of thing.

Display number with leading zeros

df['Col1']=df['Col1'].apply(lambda x: '{0:0>5}'.format(x))

The 5 is the number of total digits.

I used this link: http://www.datasciencemadesimple.com/add-leading-preceding-zeros-python/

How do I list all cron jobs for all users?

The following strips away comments, empty lines, and errors from users with no crontab. All you're left with is a clear list of users and their jobs.

Note the use of sudo in the 2nd line. If you're already root, remove that.

for USER in $(cut -f1 -d: /etc/passwd); do \
USERTAB="$(sudo crontab -u "$USER" -l 2>&1)";  \
FILTERED="$(echo "$USERTAB"| grep -vE '^#|^$|no crontab for|cannot use this program')";  \
if ! test -z "$FILTERED"; then  \
echo "# ------ $(tput bold)$USER$(tput sgr0) ------";  \
echo "$FILTERED";  \
echo "";  \
fi;  \
done

Example output:

# ------ root ------
0 */6 * * * /usr/local/bin/disk-space-notify.sh
45 3 * * * /opt/mysql-backups/mysql-backups.sh
5 7 * * * /usr/local/bin/certbot-auto renew --quiet --no-self-upgrade

# ------ sammy ------
55 * * * * wget -O - -q -t 1 https://www.example.com/cron.php > /dev/null

I use this on Ubuntu (12 thru 16) and Red Hat (5 thru 7).

How to pretty print XML from Java?

For those searching for a quick and dirty solution - which doesn't need the XML to be 100% valid. e.g. in case of REST / SOAP logging (you never know what the others send ;-))

I found and advanced a code snipped I found online which I think is still missing here as a valid possible approach:

public static String prettyPrintXMLAsString(String xmlString) {
    /* Remove new lines */
    final String LINE_BREAK = "\n";
    xmlString = xmlString.replaceAll(LINE_BREAK, "");
    StringBuffer prettyPrintXml = new StringBuffer();
    /* Group the xml tags */
    Pattern pattern = Pattern.compile("(<[^/][^>]+>)?([^<]*)(</[^>]+>)?(<[^/][^>]+/>)?");
    Matcher matcher = pattern.matcher(xmlString);
    int tabCount = 0;
    while (matcher.find()) {
        String str1 = (null == matcher.group(1) || "null".equals(matcher.group())) ? "" : matcher.group(1);
        String str2 = (null == matcher.group(2) || "null".equals(matcher.group())) ? "" : matcher.group(2);
        String str3 = (null == matcher.group(3) || "null".equals(matcher.group())) ? "" : matcher.group(3);
        String str4 = (null == matcher.group(4) || "null".equals(matcher.group())) ? "" : matcher.group(4);

        if (matcher.group() != null && !matcher.group().trim().equals("")) {
            printTabs(tabCount, prettyPrintXml);
            if (!str1.equals("") && str3.equals("")) {
                ++tabCount;
            }
            if (str1.equals("") && !str3.equals("")) {
                --tabCount;
                prettyPrintXml.deleteCharAt(prettyPrintXml.length() - 1);
            }

            prettyPrintXml.append(str1);
            prettyPrintXml.append(str2);
            prettyPrintXml.append(str3);
            if (!str4.equals("")) {
                prettyPrintXml.append(LINE_BREAK);
                printTabs(tabCount, prettyPrintXml);
                prettyPrintXml.append(str4);
            }
            prettyPrintXml.append(LINE_BREAK);
        }
    }
    return prettyPrintXml.toString();
}

private static void printTabs(int count, StringBuffer stringBuffer) {
    for (int i = 0; i < count; i++) {
        stringBuffer.append("\t");
    }
}

public static void main(String[] args) {
    String x = new String(
            "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"><soap:Body><soap:Fault><faultcode>soap:Client</faultcode><faultstring>INVALID_MESSAGE</faultstring><detail><ns3:XcbSoapFault xmlns=\"\" xmlns:ns3=\"http://www.someapp.eu/xcb/types/xcb/v1\"><CauseCode>20007</CauseCode><CauseText>INVALID_MESSAGE</CauseText><DebugInfo>Problems creating SAAJ object model</DebugInfo></ns3:XcbSoapFault></detail></soap:Fault></soap:Body></soap:Envelope>");
    System.out.println(prettyPrintXMLAsString(x));
}

here is the output:

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <soap:Fault>
        <faultcode>soap:Client</faultcode>
        <faultstring>INVALID_MESSAGE</faultstring>
        <detail>
            <ns3:XcbSoapFault xmlns="" xmlns:ns3="http://www.someapp.eu/xcb/types/xcb/v1">
                <CauseCode>20007</CauseCode>
                <CauseText>INVALID_MESSAGE</CauseText>
                <DebugInfo>Problems creating SAAJ object model</DebugInfo>
            </ns3:XcbSoapFault>
        </detail>
    </soap:Fault>
  </soap:Body>
</soap:Envelope>

How to output HTML from JSP <%! ... %> block?

I suppose this would help:

<%! 
   String someOutput() {
     return "Some Output";
  }
%>
...
<%= someOutput() %>

Anyway, it isn't a good idea to have code in a view.

How to test if a file is a directory in a batch script?

I use this:

if not [%1] == [] (
  pushd %~dpn1 2> nul
  if errorlevel == 1 pushd %~dp1
)

How to get UTF-8 working in Java webapps?

One other point that hasn't been mentioned relates to Java Servlets working with Ajax. I have situations where a web page is picking up utf-8 text from the user sending this to a JavaScript file which includes it in a URI sent to the Servlet. The Servlet queries a database, captures the result and returns it as XML to the JavaScript file which formats it and inserts the formatted response into the original web page.

In one web app I was following an early Ajax book's instructions for wrapping up the JavaScript in constructing the URI. The example in the book used the escape() method, which I discovered (the hard way) is wrong. For utf-8 you must use encodeURIComponent().

Few people seem to roll their own Ajax these days, but I thought I might as well add this.

Initializing a static std::map<int, int> in C++

Just wanted to share a pure C++ 98 work around:

#include <map>

std::map<std::string, std::string> aka;

struct akaInit
{
    akaInit()
    {
        aka[ "George" ] = "John";
        aka[ "Joe" ] = "Al";
        aka[ "Phil" ] = "Sue";
        aka[ "Smitty" ] = "Yando";
    }
} AkaInit;

How can I create database tables from XSD files?

Commercial Product: Altova's XML Spy.

Note that there's no general solution to this. An XSD can easily describe something that does not map to a relational database.

While you can try to "automate" this, your XSD's must be designed with a relational database in mind, or it won't work out well.

If the XSD's have features that don't map well you'll have to (1) design a mapping of some kind and then (2) write your own application to translate the XSD's into DDL.

Been there, done that. Work for hire -- no open source available.

What are Java command line options to set to allow JVM to be remotely debugged?

-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=PORT_NUMBER

Here we just use a Socket Attaching Connector, which is enabled by default when the dt_socket transport is configured and the VM is running in the server debugging mode.

For more details u can refer to : https://stackify.com/java-remote-debugging/

Iterate all files in a directory using a 'for' loop

Iterate through...

  • ...files in current dir: for %f in (.\*) do @echo %f
  • ...subdirs in current dir: for /D %s in (.\*) do @echo %s
  • ...files in current and all subdirs: for /R %f in (.\*) do @echo %f
  • ...subdirs in current and all subdirs: for /R /D %s in (.\*) do @echo %s

Unfortunately I did not find any way to iterate over files and subdirs at the same time.

Just use cygwin with its bash for much more functionality.

Apart from this: Did you notice, that the buildin help of MS Windows is a great resource for descriptions of cmd's command line syntax?

Also have a look here: http://technet.microsoft.com/en-us/library/bb490890.aspx

How to do a SQL NOT NULL with a DateTime?

SELECT * FROM Table where codtable not in (Select codtable from Table where fecha is null)

Landscape printing from HTML

I tried to solve this problem once, but all my research led me towards ActiveX controls/plug-ins. There is no trick that the browsers (3 years ago anyway) permitted to change any print settings (number of copies, paper size).

I put my efforts into warning the user carefully that they needed to select "landscape" when the browsers print dialog appeared. I also created a "print preview" page, which worked much better than IE6's did! Our application had very wide tables of data in some reports, and the print preview made it clear to the users when the table would spill off the right-edge of the paper (since IE6 couldnt cope with printing on 2 sheets either).

And yes, people are still using IE6 even now.

How much faster is C++ than C#?

For graphics the standard C# Graphics class is way slower than GDI accessed via C/C++. I know this has nothing to do with the language per se, more with the total .NET platform, but Graphics is what is offered to the developer as a GDI replacement, and its performance is so bad I wouldn't even dare to do graphics with it.

We have a simple benchmark we use to see how fast a graphics library is, and that is simply drawing random lines in a window. C++/GDI is still snappy with 10000 lines while C#/Graphics has difficulty doing 1000 in real-time.

How to extract img src, title and alt from html using php?

I used preg_match to do it.

In my case, I had a string containing exactly one <img> tag (and no other markup) that I got from Wordpress and I was trying to get the src attribute so I could run it through timthumb.

// get the featured image
$image = get_the_post_thumbnail($photos[$i]->ID);

// get the src for that image
$pattern = '/src="([^"]*)"/';
preg_match($pattern, $image, $matches);
$src = $matches[1];
unset($matches);

In the pattern to grab the title or the alt, you could simply use $pattern = '/title="([^"]*)"/'; to grab the title or $pattern = '/title="([^"]*)"/'; to grab the alt. Sadly, my regex isn't good enough to grab all three (alt/title/src) with one pass though.

How to read the RGB value of a given pixel in Python?

Image manipulation is a complex topic, and it's best if you do use a library. I can recommend gdmodule which provides easy access to many different image formats from within Python.

Wildcards in a Windows hosts file

Acrylic DNS Proxy (free, open source) does the job. It creates a proxy DNS server (on your own computer) with its own hosts file. The hosts file accepts wildcards.

Download from the offical website

http://mayakron.altervista.org/support/browse.php?path=Acrylic&name=Home

Configuring Acrylic DNS Proxy

To configure Acrylic DNS Proxy, install it from the above link then go to:

  1. Start
  2. Programs
  3. Acrylic DNS Proxy
  4. Config
  5. Edit Custom Hosts File (AcrylicHosts.txt)

Add the folowing lines on the end of the file:

127.0.0.1   *.localhost
127.0.0.1   *.local
127.0.0.1   *.lc

Restart the Acrylic DNS Proxy service:

  1. Start
  2. Programs
  3. Acrilic DNS Proxy
  4. Config
  5. Restart Acrylic Service

You will also need to adjust your DNS setting in you network interface settings:

  1. Start
  2. Control Panel
  3. Network and Internet
  4. Network Connections
  5. Local Area Connection Properties
  6. TCP/IPv4

Set "Use the following DNS server address":

Preferred DNS Server: 127.0.0.1

If you then combine this answer with jeremyasnyder's answer (using VirtualDocumentRoot) you can then automatically setup domains/virtual hosts by simply creating a directory.

What is so bad about singletons?

The singleton pattern is not a problem in itself. The problem is that the pattern is often used by people developing software with object-oriented tools without having a solid grasp of OO concepts. When singletons are introduced in this context they tend to grow into unmanageable classes that contain helper methods for every little use.

Singletons are also a problem from a testing perspective. They tend to make isolated unit-tests difficult to write. Inversion of control (IoC) and dependency injection are patterns meant to overcome this problem in an object-oriented manner that lends itself to unit testing.

In a garbage collected environment singletons can quickly become an issue with regard to memory management.

There is also the multi-threaded scenario where singletons can become a bottleneck as well as a synchronization issue.

Determining whether an object is a member of a collection in VBA

Not exactly elegant, but the best (and quickest) solution i could find was using OnError. This will be significantly faster than iteration for any medium to large collection.

Public Function InCollection(col As Collection, key As String) As Boolean
  Dim var As Variant
  Dim errNumber As Long

  InCollection = False
  Set var = Nothing

  Err.Clear
  On Error Resume Next
    var = col.Item(key)
    errNumber = CLng(Err.Number)
  On Error GoTo 0

  '5 is not in, 0 and 438 represent incollection
  If errNumber = 5 Then ' it is 5 if not in collection
    InCollection = False
  Else
    InCollection = True
  End If

End Function

SQL SERVER, SELECT statement with auto generate row id

You can do this directly in SQL2000, as per Microsoft's page: http://support.microsoft.com/default.aspx?scid=kb;en-us;186133

 select rank=count(*), a1.au_lname, a1.au_fname
   from authors a1, authors a2
   where a1.au_lname + a1.au_fname >= a2.au_lname + a2.au_fname
   group by a1.au_lname, a1.au_fname
   order by rank

The only problem with this approach is that (As Jeff says on SQL Server Central) it's a triangular join. So, if you have ten records this will be quick, if you have a thousand records it will be slow, and with a million records it may never complete!

See here for a better explanation of triangular joins: http://www.sqlservercentral.com/articles/T-SQL/61539/


Expand a random range from 1–5 to 1–7

Assuming that rand(n) here means "random integer in a uniform distribution from 0 to n-1", here's a code sample using Python's randint, which has that effect. It uses only randint(5), and constants, to produce the effect of randint(7). A little silly, actually

from random import randint
sum = 7
while sum >= 7:
    first = randint(0,5)   
    toadd = 9999
    while toadd>1:
        toadd = randint(0,5)
    if toadd:
        sum = first+5
    else:
        sum = first

assert 7>sum>=0 
print sum

What does the "no version information available" error from linux dynamic linker mean?

How are you compiling your app? What compiler flags?

In my experience, when targeting the vast realm of Linux systems out there, build your packages on the oldest version you are willing to support, and because more systems tend to be backwards compatible, your app will continue to work. Actually this is the whole reason for library versioning - ensuring backward compatibility.

Where does Console.WriteLine go in ASP.NET?

If you use System.Diagnostics.Debug.WriteLine(...) instead of Console.WriteLine(), then you can see the results in the Output window of Visual Studio.

How do you render primitives as wireframes in OpenGL?

In Modern OpenGL(OpenGL 3.2 and higher), you could use a Geometry Shader for this :

#version 330

layout (triangles) in;
layout (line_strip /*for lines, use "points" for points*/, max_vertices=3) out;

in vec2 texcoords_pass[]; //Texcoords from Vertex Shader
in vec3 normals_pass[]; //Normals from Vertex Shader

out vec3 normals; //Normals for Fragment Shader
out vec2 texcoords; //Texcoords for Fragment Shader

void main(void)
{
    int i;
    for (i = 0; i < gl_in.length(); i++)
    {
        texcoords=texcoords_pass[i]; //Pass through
        normals=normals_pass[i]; //Pass through
        gl_Position = gl_in[i].gl_Position; //Pass through
        EmitVertex();
    }
    EndPrimitive();
}

Notices :

Null vs. False vs. 0 in PHP

Well, I can't remember enough from my PHP days to answer the "===" part, but for most C-style languages, NULL should be used in the context of pointer values, false as a boolean, and zero as a numeric value such as an int. '\0' is the customary value for a character context. I usually also prefer to use 0.0 for floats and doubles.

So.. the quick answer is: context.

Excel CSV - Number cell format

I had this issue when exporting CSV data from C# code, and resolved this by prepending the leading zero data with the tab character \t, so the data was interpreted as text rather than numeric in Excel (yet unlike prepending other characters, it wouldn't be seen).

I did like the ="001" approach, but this wouldn't allow exported CSV data to be re-imported again to my C# application without removing all this formatting from the import CSV file (instead I'll just trim the import data).

How to embed a SWF file in an HTML page?

If you are using one of those js libraries to insert Flash, I suggest adding plain object embed tag inside of <noscript/>.

How to deal with a slow SecureRandom generator?

If you want true random data, then unfortunately you have to wait for it. This includes the seed for a SecureRandom PRNG. Uncommon Maths can't gather true random data any faster than SecureRandom, although it can connect to the internet to download seed data from a particular website. My guess is that this is unlikely to be faster than /dev/random where that's available.

If you want a PRNG, do something like this:

SecureRandom.getInstance("SHA1PRNG");

What strings are supported depends on the SecureRandom SPI provider, but you can enumerate them using Security.getProviders() and Provider.getService().

Sun is fond of SHA1PRNG, so it's widely available. It isn't especially fast as PRNGs go, but PRNGs will just be crunching numbers, not blocking for physical measurement of entropy.

The exception is that if you don't call setSeed() before getting data, then the PRNG will seed itself once the first time you call next() or nextBytes(). It will usually do this using a fairly small amount of true random data from the system. This call may block, but will make your source of random numbers far more secure than any variant of "hash the current time together with the PID, add 27, and hope for the best". If all you need is random numbers for a game, though, or if you want the stream to be repeatable in future using the same seed for testing purposes, an insecure seed is still useful.

What's the best visual merge tool for Git?

You can install ECMerge diff/merge tool on your Linux, Mac or Windows. It is pre-configured in Git, so just using git mergetool will do the job.

How do you get assembler output from C/C++ source in gcc?

Use the -S option to gcc (or g++).

gcc -S helloworld.c

This will run the preprocessor (cpp) over helloworld.c, perform the initial compilation and then stop before the assembler is run.

By default this will output a file helloworld.s. The output file can be still be set by using the -o option.

gcc -S -o my_asm_output.s helloworld.c

Of course this only works if you have the original source. An alternative if you only have the resultant object file is to use objdump, by setting the --disassemble option (or -d for the abbreviated form).

objdump -S --disassemble helloworld > helloworld.dump

This option works best if debugging option is enabled for the object file (-g at compilation time) and the file hasn't been stripped.

Running file helloworld will give you some indication as to the level of detail that you will get by using objdump.

Has an event handler already been added?

I recently came to a similar situation where I needed to register a handler for an event only once. I found that you can safely unregister first, and then register again, even if the handler is not registered at all:

myClass.MyEvent -= MyHandler;
myClass.MyEvent += MyHandler;

Note that doing this every time you register your handler will ensure that your handler is registered only once. Sounds like a pretty good practice to me :)

Is there a way to catch the back button event in javascript?

I have created a solution which may be of use to some people. Simply include the code on your page, and you can write your own function that will be called when the back button is clicked.

I have tested in IE, FF, Chrome, and Safari, and are all working. The solution I have works based on iframes without the need for constant polling, in IE and FF, however, due to limitations in other browsers, the location hash is used in Safari.

Is there a "do ... while" loop in Ruby?

CAUTION:

The begin <code> end while <condition> is rejected by Ruby's author Matz. Instead he suggests using Kernel#loop, e.g.

loop do 
  # some code here
  break if <condition>
end 

Here's an email exchange in 23 Nov 2005 where Matz states:

|> Don't use it please.  I'm regretting this feature, and I'd like to
|> remove it in the future if it's possible.
|
|I'm surprised.  What do you regret about it?

Because it's hard for users to tell

  begin <code> end while <cond>

works differently from

  <code> while <cond>

RosettaCode wiki has a similar story:

During November 2005, Yukihiro Matsumoto, the creator of Ruby, regretted this loop feature and suggested using Kernel#loop.

Using SimpleXML to create an XML object from scratch

In PHP5, you should use the Document Object Model class instead. Example:

$domDoc = new DOMDocument;
$rootElt = $domDoc->createElement('root');
$rootNode = $domDoc->appendChild($rootElt);

$subElt = $domDoc->createElement('foo');
$attr = $domDoc->createAttribute('ah');
$attrVal = $domDoc->createTextNode('OK');
$attr->appendChild($attrVal);
$subElt->appendChild($attr);
$subNode = $rootNode->appendChild($subElt);

$textNode = $domDoc->createTextNode('Wow, it works!');
$subNode->appendChild($textNode);

echo htmlentities($domDoc->saveXML());

How do I find the size of a struct?

The sizeof the structure should be 8 bytes on a 32 bit system, so that the size of the structure becomes multiple of 2. This makes individual structures available at the correct byte boundaries when an array of structures is declared. This is achieved by padding the structure with 3 bytes at the end.

If the structure had the pointer declared after the char, it would still be 8 bytes in size but the 3 byte padding would have been added to keep the pointer (which is a 4 byte element) aligned at a 4 byte address boundary.

The rule of thumb is that elements should be at an offset which is the multiple of their byte size and the structure itself should be of a size which is a multiple of 2.

Change Oracle port from port 8080

Execute Exec DBMS_XDB.SETHTTPPORT(8181); as SYS/SYSTEM. Replace 8181 with the port you'd like changing to. Tested this with Oracle 10g.

Source : http://hodentekhelp.blogspot.com/2008/08/my-oracle-10g-xe-is-on-port-8080-can-i.html

How do I import a pre-existing Java project into Eclipse and get up and running?

I think you'll have to import the project via the file->import wizard:

http://www.coderanch.com/t/419556/vc/Open-existing-project-Eclipse

It's not the last step, but it will start you on your way.

I also feel your pain - there is really no excuse for making it so difficult to do a simple thing like opening an existing project. I truly hope that the Eclipse designers focus on making the IDE simpler to use (tho I applaud their efforts at trying different approaches - but please, Eclipse designers, if you are listening, never complicate something simple).

What is a "callback" in C and how are they implemented?

A simple call back program. Hope it answers your question.

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include "../../common_typedef.h"

typedef void (*call_back) (S32, S32);

void test_call_back(S32 a, S32 b)
{
    printf("In call back function, a:%d \t b:%d \n", a, b);
}

void call_callback_func(call_back back)
{
    S32 a = 5;
    S32 b = 7;

    back(a, b);
}

S32 main(S32 argc, S8 *argv[])
{
    S32 ret = SUCCESS;

    call_back back;

    back = test_call_back;

    call_callback_func(back);

    return ret;
}

ModalPopupExtender OK Button click event not firing?

None of the previous answers worked for me. I called the postback of the button on the OnOkScript event.

<div>
    <cc1:ModalPopupExtender PopupControlID="Panel1" 
         ID="ModalPopupExtender1"
         runat="server" TargetControlID="LinkButton1" OkControlID="Ok" 
         OnOkScript="__doPostBack('Ok','')">
    </cc1:ModalPopupExtender>

    <asp:LinkButton ID="LinkButton1" runat="server">LinkButton</asp:LinkButton> 
</div>        


<asp:Panel ID="Panel1" runat="server">
    <asp:Button ID="Ok" runat="server" Text="Ok" onclick="Ok_Click" />            
</asp:Panel>