SyntaxFix.com - Programming Questions & Answers Hub For Beginners

Some Of The Best Answers From Latest Asked Questions

Is it possible to have a default parameter for a mysql stored procedure?

I have googled this and keep coming up with "No it is not possible" but these posts were dated 2005-2007 so I'm wondering if this has been changed. A code example: CREATE PROCEDURE `blah` ( myDefaultParam int = 0 -- This breaks the code for some r...

Command to collapse all sections of code?

In Visual Studio is there a command to collapse/expand all the sections of code in a file?...

Quickly create large file on a Windows system

In the same vein as Quickly create a large file on a Linux system, I'd like to quickly create a large file on a Windows system. By large I'm thinking 5 GB. The content doesn't matter. A built-in command or short batch file would be preferable, ...

What is the best way to auto-generate INSERT statements for a SQL Server table?

We are writing a new application, and while testing, we will need a bunch of dummy data. I've added that data by using MS Access to dump excel files into the relevant tables. Every so often, we want to "refresh" the relevant tables, which means drop...

Where are the Properties.Settings.Default stored?

I thought I knew this, but today I'm being proven wrong - again. Running VS2008, .NET 3.5 and C#. I added the User settings to the Properties Settings tab with default values, then read them in using this code: myTextBox.Text = Properties.Settings...

How to center an element in the middle of the browser window?

How can I place some HTML element (say, a <div>, for example) in the middle of a browser window (not page, not screen)? Not depending on browser window size, screen resolution, toolbar layout, etc. E.g. I want it to be in the middle of the brow...

How can one check to see if a remote file exists using PHP?

The best I could find, an if fclose fopen type thing, makes the page load really slowly. Basically what I'm trying to do is the following: I have a list of websites, and I want to display their favicons next to them. However, if a site doesn't have...

How to represent a DateTime in Excel

What is the best way of representing a DateTime in Excel? We use Syncfusions Essential XlsIO to output values to an Excel document which works great. But I can't figure out how to display a DateTime in a column. Not when doing it myself directly in E...

Colorized grep -- viewing the entire file with highlighted matches

I find grep's --color=always flag to be tremendously useful. However, grep only prints lines with matches (unless you ask for context lines). Given that each line it prints has a match, the highlighting doesn't add as much capability as it could. I'...

WCF timeout exception detailed investigation

We have an application that has a WCF service (*.svc) running on IIS7 and various clients querying the service. The server is running Win 2008 Server. The clients are running either Windows 2008 Server or Windows 2003 server. I am getting the followi...

Can I create a One-Time-Use Function in a Script or Stored Procedure?

In SQL Server 2005, is there a concept of a one-time-use, or local function declared inside of a SQL script or Stored Procedure? I'd like to abstract away some complexity in a script I'm writing, but it would require being able to declare a function....

How to recognize vehicle license / number plate (ANPR) from an image?

I have a web site that allows users to upload images of cars and I would like to put a privacy filter in place to detect registration plates on the vehicle and blur them. The blurring is not a problem but is there a library or component (open source...

Inputting a default image in case the src attribute of an html <img> is not valid?

Is there any way to render a default image in an HTML <img> tag, in case the src attribute is invalid (using only HTML)? If not, what would be your lightweight way to work around it? ...

"element.dispatchEvent is not a function" js error caught in firebug of FF3.0

i am getting the following error while loading my index page in FF3.0. Sorry, i am unable to paste the script here as it is 2030 lines of code. element.dispatchEvent is not a function On expansion it gives me below things, fire()()prototype...

How do I find the current executable filename?

Possible Duplicate: How do I get the name of the current executable in C#? An executable file loads an external library. Is there a way for the library to know the calling executable file? (I would have sworn I saw the answer to this el...

How to get the value from the GET parameters?

I have a URL with some GET parameters as follows: www.test.com/t.html?a=1&b=3&c=m2-m3-m4-m5 I need to get the whole value of c. I tried to read the URL, but I got only m2. How do I do this using JavaScript?...

Set background color of WPF Textbox in C# code

How can I change the background and foreground colors of a WPF Textbox programmatically in C#?...

What is the equivalent to getLastInsertId() in Cakephp?

If I do getLastInsertId() immediately after a save(), it works, but otherwise it does not. This is demonstrated in my controller: function designpage() { //to create a form Untitled $this->Form->saveField('name','Untitled Form'); e...

How to select the first element of a set with JSTL?

I managed to do it with the next code but there must be an easier way. <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %> <c:if test="${fn:length(...

Create a hidden field in JavaScript

How do you create a hidden field in JavaScript into a particular form ? <html> <head> <script type="text/javascript"> var a =10; function test() { if (a ==10) { // ... Here i need to create some...

What is the canonical way to trim a string in Ruby without creating a new string?

This is what I have now - which looks too verbose for the work it is doing. @title = tokens[Title].strip! || tokens[Title] if !tokens[Title].nil? Assume tokens is a array obtained by splitting a CSV line. now the functions like strip! chomp...

event.preventDefault() function not working in IE

Following is my JavaScript (mootools) code: $('orderNowForm').addEvent('submit', function (event) { event.preventDefault(); allFilled = false; $$(".required").each(function (inp) { if (inp.getValue() != '') { allFille...

Data binding to SelectedItem in a WPF Treeview

How can I retrieve the item that is selected in a WPF-treeview? I want to do this in XAML, because I want to bind it. You might think that it is SelectedItem but apparently that does not exist is readonly and therefore unusable. This is what I want...

git push says "everything up-to-date" even though I have local changes

I have a remote gitosis server and a local git repository, and each time I make a big change in my code, I'll push the changes to that server too. But today I find that even though I have some local changes and commit to local repository, when runn...

"Invalid signature file" when attempting to run a .jar

My java program is packaged in a jar file and makes use of an external jar library, bouncy castle. My code compiles fine, but running the jar leads to the following error: Exception in thread "main" java.lang.SecurityException: Invalid signature fil...

iPhone app signing: A valid signing identity matching this profile could not be found in your keychain

I'm pulling my hair out over this. I just downloaded the iPhone 3.0 SDK, but now I can't get my provisioning profiles to work. Here is what I have tried: Delete all provisioning profiles Delete login keychain Create new "login" keychain, make it de...

How to parse a date?

I am trying to parse this date with SimpleDateFormat and it is not working: import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class Formaterclass { public static void main(String[] args) throws Pa...

GUI-based or Web-based JSON editor that works like property explorer

Background: This is a request for something that may not exist yet, but I've been meaning to build one for a long time. First I will ask if anyone has seen anything like it yet. Suppose you have an arbitrary JSON structure like the following: { '...

Meaning of tilde in Linux bash (not home directory)

First off, I know that ~/ is the home directory. CDing to ~ or ~/ takes me to the home directory. However, cd ~X takes me to a special place, where X seems to be anything. In bash, if I hit "cd ~" and hit tab, it shows a bunch of possible ~X option...

How to store the hostname in a variable in a .bat file?

I would like to convert this /bin/sh syntax into a widely compatible Windows batch script: host=`hostname` echo ${host} How to do this so that it'll work on any Windows Vista, Windows XP, and Windows 2000 machine? To clarify: I would then like to...

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

How can I use javascript/jQuery/etc to detect if Flash is installed and if it isn't, display a div that contains information informing the user that they need to install flash?...

LINQ: Distinct values

I have the following item set from an XML: id category 5 1 5 3 5 4 5 3 5 3 I need a distinct list of these items: 5 1 5 3 5 4 How can I distinct ...

How to get current time and date in C++?

Is there a cross-platform way to get the current date and time in C++?...

What does %s mean in a python format string?

What does %s mean in Python? And what does the following bit of code do? For instance... if len(sys.argv) < 2: sys.exit('Usage: %s database-name' % sys.argv[0]) if not os.path.exists(sys.argv[1]): sys.exit('ERROR: Database %s was n...

How to convert DateTime to a number with a precision greater than days in T-SQL?

Both queries below translates to the same number SELECT CONVERT(bigint,CONVERT(datetime,'2009-06-15 15:00:00')) SELECT CAST(CONVERT(datetime,'2009-06-15 23:01:00') as bigint) Result 39978 39978 The generated number will be different only if the...

Does Java support default parameter values?

I came across some Java code that had the following structure: public MyParameterizedFunction(String param1, int param2) { this(param1, param2, false); } public MyParameterizedFunction(String param1, int param2, boolean param3) { //use all ...

How to create a hidden <img> in JavaScript?

How can you make a simple tag like <img src="a.gif"> hidden programmatically using JavaScript?...

Returning value that was passed into a method

I have a method on an interface: string DoSomething(string whatever); I want to mock this with MOQ, so that it returns whatever was passed in - something like: _mock.Setup( theObject => theObject.DoSomething( It.IsAny<string>( ) ) ) ....

Removing App ID from Developer Connection

How do I remove an App ID from the developer program portal area? I mistakenly added a couple of app id's under the wrong login and would like to remove them, but I am not seeing a way to do so....

Disable Transaction Log

Oracle has SQL commands that one can issue so that a transaction does not get logged. Is there something similar for SQL Server 2008? My scenario: We need Tx logs on servers (Dev, QA, Prod), but maybe we can do without them on developer machines....

Find the IP address of the client in an SSH session

I have a script that is to be run by a person that logs in to the server with SSH. Is there a way to find out automatically what IP address the user is connecting from? Of course, I could ask the user (it is a tool for programmers, so no problem wi...

Execute Immediate within a stored procedure keeps giving insufficient priviliges error

Here is the definition of the stored procedure: CREATE OR REPLACE PROCEDURE usp_dropTable(schema VARCHAR, tblToDrop VARCHAR) IS BEGIN DECLARE v_cnt NUMBER; BEGIN SELECT COUNT(*) INTO v_cnt FROM all_tables WHERE owner = sc...

urlencode vs rawurlencode?

If I want to create a URL using a variable I have two choices to encode the string. urlencode() and rawurlencode(). What exactly are the differences and which is preferred?...

SSH library for Java

Does anyone have an example of an SSH library connection using Java....

Catch browser's "zoom" event in JavaScript

Is it possible to detect, using JavaScript, when the user changes the zoom in a page? I simply want to catch a "zoom" event and respond to it (similar to window.onresize event). Thanks....

How do you completely remove the button border in wpf?

I'm trying to create a button that has an image in it and no border - just like the Firefox toolbar buttons before you hover over them and see the full button. I've tried setting the BorderBrush to Transparent, BorderThickness to 0, and also tried B...

What does ||= (or-equals) mean in Ruby?

What does the following code mean in Ruby? ||= Does it have any meaning or reason for the syntax?...

Https Connection Android

I am doing a https post and I'm getting an exception of ssl exception Not trusted server certificate. If i do normal http it is working perfectly fine. Do I have to accept the server certificate somehow?...

How can I make a .NET Windows Forms application that only runs in the System Tray?

What do I need to do to make a Windows Forms application to be able to run in the System Tray? Not an application that can be minimized to the tray, but an application that will be only exist in the tray, with nothing more than an icon a tool tip, a...

How to allow only numeric (0-9) in HTML inputbox using jQuery?

I am creating a web page where I have an input text field in which I want to allow only numeric characters like (0,1,2,3,4,5...9) 0-9. How can I do this using jQuery?...

Textarea to resize based on content length

I need a textarea where I type my text in the box, it grows in length as needed to avoid having to deal with scroll bars and it need to shrink after delete text! I didn’t want to go down the mootools or jquery route because I have a lightweight for...

How to create our own Listener interface in android?

Could someone help me to create user defined listener interface with some code snippets?...

How to unescape HTML character entities in Java?

Basically I would like to decode a given Html document, and replace all special chars, such as "&nbsp;" -> " ", "&gt;" -> ">". In .NET we can make use of HttpUtility.HtmlDecode. What's the equivalent function in Java?...

Resolving ORA-4031 "unable to allocate x bytes of shared memory"

I need some pointers on how to diagnose and fix this problem. I don't know if this is a simple server setup problem or an application design problem (or both). Once or twice every few months this Oracle XE database reports ORA-4031 errors. It doesn'...

Best way to make WPF ListView/GridView sort on column-header clicking?

There are lots of solutions on the internet attempting to fill this seemingly very-basic omission from WPF. I'm really confused as to what would be the "best" way. For example... I want there to be little up/down arrows in the column header to indica...

What are the advantages of NumPy over regular Python lists?

What are the advantages of NumPy over regular Python lists? I have approximately 100 financial markets series, and I am going to create a cube array of 100x100x100 = 1 million cells. I will be regressing (3-variable) each x with each y and z, to fil...

Adding POST parameters before submit

I've this simple form: <form id="commentForm" method="POST" action="api/comment"> <input type="text" name="name" title="Your name"/> <textarea cols="40" rows="10" name="comment" title="Enter a comment"> </textarea&g...

Creating a range of dates in Python

I want to create a list of dates, starting with today, and going back an arbitrary number of days, say, in my example 100 days. Is there a better way to do it than this? import datetime a = datetime.datetime.today() numdays = 100 dateList = [] for ...

Difference between Visual Basic 6.0 and VBA

What is the difference between the two. I always thought VBA is somewhat 'crippled' version of VB, but when a friend asked me the other day I had no idea what the actual differences are. Also, when you use, for example, Excel, is that VB or VBA ?...

How to detect when a UIScrollView has finished scrolling

UIScrollViewDelegate has got two delegate methods scrollViewDidScroll: and scrollViewDidEndScrollingAnimation: but neither of these tell you when scrolling has completed. scrollViewDidScroll only notifies you that the scroll view did scroll not that ...

Adding elements to a collection during iteration

Is it possible to add elements to a collection while iterating over it? More specifically, I would like to iterate over a collection, and if an element satisfies a certain condition I want to add some other elements to the collection, and make sure ...

What is sharding and why is it important?

I think I understand sharding to be putting back your sliced up data (the shards) into an easy to deal with aggregate that makes sense in the context. Is this correct? Update: I guess I am struggling here. In my opinion the application tier shoul...

How do I iterate over an NSArray?

I'm looking for the standard idiom to iterate over an NSArray. My code needs to be suitable for OS X 10.4+....

Convert MFC CString to integer

How to convert a CString object to integer in MFC....

Reading HTML content from a UIWebView

Is it possible to read the raw HTML content of a web page that has been loaded into a UIWebView? If not, is there another way to pull raw HTML content from a web page in the iPhone SDK (such as an equivalent of the .NET WebClient::openRead)?...

Java 256-bit AES Password-Based Encryption

I need to implement 256 bit AES encryption, but all the examples I have found online use a "KeyGenerator" to generate a 256 bit key, but I would like to use my own passkey. How can I create my own key? I have tried padding it out to 256 bits, but the...

Git Ignores and Maven targets

Anyone know if it is possible to ignore all the instances of a particular directory in a file structure managed by git. I'm looking to exclude all the 'target' folders in a maven project with a number of submodules. I know I can explicitly exclude ...

How to get .pem file from .key and .crt files?

How can I create a PEM file from an SSL certificate? These are the files that I have available: .crt server.csr server.key ...

file.delete() returns false even though file.exists(), file.canRead(), file.canWrite(), file.canExecute() all return true

I'm trying to delete a file, after writing something in it, with FileOutputStream. This is the code I use for writing: private void writeContent(File file, String fileContent) { FileOutputStream to; try { to = new FileOutputStream(fi...

How to get the containing form of an input?

I need to get a reference to the FORM parent of an INPUT when I only have a reference to that INPUT. Is this possible with JavaScript? Use jQuery if you like. function doSomething(element) { //element is input object //how to get reference t...

Counting repeated characters in a string in Python

I want to count the number of times each character is repeated in a string. Is there any particular way to do it apart from comparing each character of the string from A-Z and incrementing a counter? Update (in reference to Anthony's answer): Whatev...

How to make my font bold using css?

I'm very new to HTML and CSS and I was just wondering how I could make my font bold using CSS. I have a plain HTML page that imports a CSS file, and I can change the font in the CSS. But I don't know how to make the font bold, can anyone help me?...

How to calculate a mod b in Python?

Is there a modulo function in the Python math library? Isn't 15 % 4, 3? But 15 mod 4 is 1, right?...

Remove accents/diacritics in a string in JavaScript

How do I remove accentuated characters from a string? Especially in IE6, I had something like this: accentsTidy = function(s){ var r=s.toLowerCase(); r = r.replace(new RegExp(/\s/g),""); r = r.replace(new RegExp(/[àáâãäå]/g),"a");...

How to leave/exit/deactivate a Python virtualenv

I'm using virtualenv and the virtualenvwrapper. I can switch between virtualenv's just fine using the workon command. [email protected]:~$ workon env1 (env1)[email protected]:~$ workon env2 (env2)[email protected]:~$ workon env1 (env1)[email protected]:~$ How do I ...

What's the difference between SHA and AES encryption?

What's the difference between SHA and AES encryption?...

.htaccess rewrite to redirect root URL to subdirectory

Trying to get www.example.com to go directly to www.example.com/store I have tried multiple bits of code and none work. What I've tried: Options +FollowSymlinks RewriteEngine on RewriteCond %{HTTP_HOST} ^example.com$ RewriteRule (.*) http://...

Multiple lines of text in UILabel

Is there a way to have multiple lines of text in UILabel like in the UITextView or should I use the second one instead?...

Best way to log POST data in Apache?

Imagine you have a site API that accepts data in the form of GET requests with parameters, or as POST requests (say, with standard url-encoded, &-separated POST data). If you want to log and analyze API calls, the GET requests will be easy, beca...

Example for boost shared_mutex (multiple reads/one write)?

I have a multithreaded app that has to read some data often, and occasionally that data is updated. Right now a mutex keeps access to that data safe, but it's expensive because I would like multiple threads to be able to read simultaneously, and only...

Running a command in a new Mac OS X Terminal window

I've been trying to figure out how to run a bash command in a new Max OS X Terminal.app window. As, an example, here's how I would run my command in a new bash process: bash -c "my command here" But this reuses the existing terminal window instead...

Unable to Cast from Parent Class to Child Class

I am trying to cast from a parent class to a child class but I get an InvalidCastException. The child class only has one property of type int. Does anyone know what I need to do?...

Can I replace groups in Java regex?

I have this code, and I want to know, if I can replace only groups (not all pattern) in Java regex. Code: //... Pattern p = Pattern.compile("(\\d).*(\\d)"); String input = "6 example input 4"; Matcher m = p.matcher(input); if (m.find()...

How to prevent auto-closing of console after the execution of batch file

What command can I put at the end of a batch file to prevent auto-closing of the console after the execution of the file?...

How can I debug my JavaScript code?

When I find that I have a problematic code snippet, how should I go about debugging it?...

Convert a String representation of a Dictionary to a dictionary?

How can I convert the str representation of a dict, such as the following string, into a dict? s = "{'muffin' : 'lolz', 'foo' : 'kitty'}" I prefer not to use eval. What else can I use? The main reason for this, is one of my coworkers classes he w...

Why does Eclipse complain about @Override on interface methods?

I have an existing project that uses @Override on methods that override interface methods, rather than superclass methods. I cannot alter this in code, but I would like Eclpse to stop complaining about the annotation, as I can still build with Maven....

How to change an element's title attribute using jQuery

I have an form input element and want to change its title attribute. This has to be easy as pie, but for some reason I cannot find how to do this. How is this done, and where and how should I be searching on how to do this?...

Make .gitignore ignore everything except a few files

I understand that a .gitignore file cloaks specified files from Git's version control. I have a project (LaTeX) that generates lots of extra files (.auth, .dvi, .pdf, logs, etc) as it runs, but I don't want those to be tracked. I'm aware that I coul...

How to remove all namespaces from XML with C#?

I am looking for the clean, elegant and smart solution to remove namespacees from all XML elements? How would function to do that look like? Defined interface: public interface IXMLUtils { string RemoveAllNamespaces(string xmlDocument); } ...

Using Application context everywhere?

In an Android app, is there anything wrong with the following approach: public class MyApp extends android.app.Application { private static MyApp instance; public MyApp() { instance = this; } public static Context getConte...

Bulk Insert into Oracle database: Which is better: FOR Cursor loop or a simple Select?

Which would be a better option for bulk insert into an Oracle database ? A FOR Cursor loop like DECLARE CURSOR C1 IS SELECT * FROM FOO; BEGIN FOR C1_REC IN C1 LOOP INSERT INTO BAR(A, B, C) VALUES(C...

How can I get the browser's scrollbar sizes?

How can I determine the height of a horizontal scrollbar, or the width of a vertical one, in JavaScript?...

How to do a regular expression replace in MySQL?

I have a table with ~500k rows; varchar(255) UTF8 column filename contains a file name; I'm trying to strip out various strange characters out of the filename - thought I'd use a character class: [^a-zA-Z0-9()_ .\-] Now, is there a function in MySQ...

Clear the cache in JavaScript

How do I clear a browsers cache with JavaScript? We deployed the latest JavaScript code but we are unable to get the latest JavaScript code. Editorial Note: This question is semi-duplicated in the following places, and the answer in the first of th...

Convert pem key to ssh-rsa format

I have a certificate in der format, from it with this command I generate a public key: openssl x509 -inform der -in ejbcacert.cer -noout -pubkey > pub1key.pub Which results in this: -----BEGIN PUBLIC KEY----- MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQ...

Is it possible to modify a string of char in C?

I have been struggling for a few hours with all sorts of C tutorials and books related to pointers but what I really want to know is if it's possible to change a char pointer once it's been created. This is what I have tried: char *a = "This is a s...

How do you make a HTTP request with C++?

Is there any way to easily make a HTTP request with C++? Specifically, I want to download the contents of a page (an API) and check the contents to see if it contains a 1 or a 0. Is it also possible to download the contents into a string?...

Replace a value if null or undefined in JavaScript

I have a requirement to apply the ?? C# operator to JavaScript and I don't know how. Consider this in C#: int i?=null; int j=i ?? 10;//j is now 10 Now I have this set up in JavaScript: var options={ filters:{ firstName:'abc' ...

Get file name from a file location in Java

I have a String that provides an absolute path to a file (including the file name). I want to get just the file's name. What is the easiest way to do this? It needs to be as general as possible as I cannot know in advance what the URL will be. I can...