Daily Archives

Articles indexed Thursday April 29 2010

Page 10/119 | < Previous Page | 6 7 8 9 10 11 12 13 14 15 16 17  | Next Page >

  • MySQL top count({column}) with a limit

    - by Josh K
    I have a table with an ip address column. I would like to find the top five addresses which are listed. Right now I'm planning it out the following: Select all distinct ip addresses Loop through them all saying count(id) where IP='{ip}' and storing the count List the top five counts. Downsides include what if I have 500 ip addresses. That's 500 queries I have to run to figure out what are the top five. I'd like to build a query like so select ip from table where 1 order by count({distinct ip}) asc limit 5

    Read the article

  • $_POST data returns empty when headers are > POST_MAX_SIZE

    - by Jared
    Hi Hopefully someone here might have an answer to my question. I have a basic form that contains simple fields, like name, number, email address etc and 1 file upload field. I am trying to add some validation into my script that detects if the file is too large and then rejects the user back to the form to select/upload a smaller file. My problem is, if a user selects a file that is bigger than my validation file size rule and larger than php.ini POST_MAX_SIZE/UPLOAD_MAX_FILESIZE and pushes submit, then PHP seems to try process the form only to fail on the POST_MAX_SIZE settings and then clears the entire $_POST array and returns nothing back to the form. Is there a way around this? Surely if someone uploads something than the max size configured in the php.ini then you can still get the rest of the $_POST data??? Here is my code. <?php function validEmail($email) { $isValid = true; $atIndex = strrpos($email, "@"); if (is_bool($atIndex) && !$atIndex) { $isValid = false; } else { $domain = substr($email, $atIndex+1); $local = substr($email, 0, $atIndex); $localLen = strlen($local); $domainLen = strlen($domain); if ($localLen < 1 || $localLen > 64) { // local part length exceeded $isValid = false; } else if ($domainLen < 1 || $domainLen > 255) { // domain part length exceeded $isValid = false; } else if ($local[0] == '.' || $local[$localLen-1] == '.') { // local part starts or ends with '.' $isValid = false; } else if (preg_match('/\\.\\./', $local)) { // local part has two consecutive dots $isValid = false; } else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain)) { // character not valid in domain part $isValid = false; } else if (preg_match('/\\.\\./', $domain)) { // domain part has two consecutive dots $isValid = false; } else if (!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/', str_replace("\\\\","",$local))) { // character not valid in local part unless // local part is quoted if (!preg_match('/^"(\\\\"|[^"])+"$/', str_replace("\\\\","",$local))) { $isValid = false; } } } return $isValid; } //setup post variables @$name = htmlspecialchars(trim($_REQUEST['name'])); @$emailCheck = htmlspecialchars(trim($_REQUEST['email'])); @$organisation = htmlspecialchars(trim($_REQUEST['organisation'])); @$title = htmlspecialchars(trim($_REQUEST['title'])); @$phone = htmlspecialchars(trim($_REQUEST['phone'])); @$location = htmlspecialchars(trim($_REQUEST['location'])); @$description = htmlspecialchars(trim($_REQUEST['description'])); @$fileError = 0; @$phoneError = ""; //setup file upload handler $target_path = 'uploads/'; $filename = basename( @$_FILES['uploadedfile']['name']); $max_size = 8000000; // maximum file size (8mb in bytes) NB: php.ini max filesize upload is 10MB on test environment. $allowed_filetypes = Array(".pdf", ".doc", ".zip", ".txt", ".xls", ".docx", ".csv", ".rtf"); //put extensions in here that should be uploaded only. $ext = substr($filename, strpos($filename,'.'), strlen($filename)-1); // Get the extension from the filename. if(!is_writable($target_path)) die('You cannot upload to the specified directory, please CHMOD it to 777.'); //Check if we can upload to the specified upload folder. //display form function function displayForm($name, $emailCheck, $organisation, $phone, $title, $location, $description, $phoneError, $allowed_filetypes, $ext, $filename, $fileError) { //make $emailCheck global so function can get value from global scope. global $emailCheck; global $max_size; echo '<form action="geodetic_form.php" method="post" name="contact" id="contact" enctype="multipart/form-data">'."\n". '<fieldset>'."\n".'<div>'."\n"; //name echo '<label for="name"><span class="mandatory">*</span>Your name:</label>'."\n". '<input type="text" name="name" id="name" class="inputText required" value="'. $name .'" />'."\n"; //check if name field is filled out if (isset($_REQUEST['submit']) && empty($name)) { echo '<label for="name" class="error">Please enter your name.</label>'."\n"; } echo '</div>'."\n". '<div>'."\n"; //Email echo '<label for="email"><span class="mandatory">*</span>Your email:</label>'."\n". '<input type="text" name="email" id="email" class="inputText required email" value="'. $emailCheck .'" />'."\n"; // check if email field is filled out and proper format if (isset($_REQUEST['submit']) && validEmail($emailCheck) == false) { echo '<label for="email" class="error">Invalid email address entered.</label>'."\n"; } echo '</div>'."\n". '<div>'."\n"; //organisation echo '<label for="phone">Organisation:</label>'."\n". '<input type="text" name="organisation" id="organisation" class="inputText" value="'. $organisation .'" />'."\n"; echo '</div>'."\n". '</fieldset>'."\n".'<fieldset>'. "\n" . '<div>'."\n"; //title echo '<label for="phone">Title:</label>'."\n". '<input type="text" name="title" id="title" class="inputText" value="'. $title .'" />'."\n"; echo '</div>'."\n". '</fieldset>'."\n".'<fieldset>'. "\n" . '<div>'."\n"; //phone echo '<label for="phone"><span class="mandatory">*</span>Phone <br /><span class="small">(include area code)</span>:</label>'."\n". '<input type="text" name="phone" id="phone" class="inputText required" value="'. $phone .'" />'."\n"; // check if phone field is filled out that it has numbers and not characters if (isset($_REQUEST['submit']) && $phoneError == "true" && empty($phone)) echo '<label for="email" class="error">Please enter a valid phone number.</label>'."\n"; echo '</div>'."\n". '</fieldset>'."\n".'<fieldset>'. "\n" . '<div>'."\n"; //Location echo '<label class="location" for="location"><span class="mandatory">*</span>Location:</label>'."\n". '<textarea name="location" id="location" class="required">'. $location .'</textarea>'."\n"; //check if message field is filled out if (isset($_REQUEST['submit']) && empty($_REQUEST['location'])) echo '<label for="location" class="error">This field is required.</label>'."\n"; echo '</div>'."\n". '</fieldset>'."\n".'<fieldset>'. "\n" . '<div>'."\n"; //description echo '<label class="description" for="description">Description:</label>'."\n". '<textarea name="description" id="queryComments">'. $description .'</textarea>'."\n"; echo '</div>'."\n". '</fieldset>'."\n".'<fieldset>'. "\n" . '<div>'."\n"; //file upload echo '<label class="uploadedfile" for="uploadedfile">File:</label>'."\n". '<input type="file" name="uploadedfile" id="uploadedfile" value="'. $filename .'" />'."\n"; // Check if the filetype is allowed, if not DIE and inform the user. switch ($fileError) { case "1": echo '<label for="uploadedfile" class="error">The file you attempted to upload is not allowed.</label>'; break; case "2": echo '<label for="uploadedfile" class="error">The file you attempted to upload is too large.</label>'; break; } echo '</div>'."\n". '</fieldset>'; //end of form echo '<div class="submit"><input type="submit" name="submit" value="Submit" id="submit" /></div>'. '<div class="clear"><p><br /></p></div>'; } //end function //setup error validations if (isset($_REQUEST['submit']) && !empty($_REQUEST['phone']) && !is_numeric($_REQUEST['phone'])) $phoneError = "true"; if (isset($_REQUEST['submit']) && $_FILES['uploadedfile']['error'] != 4 && !in_array($ext, $allowed_filetypes)) $fileError = 1; if (isset($_REQUEST['submit']) && $_FILES["uploadedfile"]["size"] > $max_size) $fileError = 2; echo "this condition " . $fileError; $POST_MAX_SIZE = ini_get('post_max_size'); $mul = substr($POST_MAX_SIZE, -1); $mul = ($mul == 'M' ? 1048576 : ($mul == 'K' ? 1024 : ($mul == 'G' ? 1073741824 : 1))); if ($_SERVER['CONTENT_LENGTH'] > $mul*(int)$POST_MAX_SIZE && $POST_MAX_SIZE) echo "too big!!"; echo $POST_MAX_SIZE; if(empty($name) || empty($phone) || empty($location) || validEmail($emailCheck) == false || $phoneError == "true" || $fileError != 0) { displayForm($name, $emailCheck, $organisation, $phone, $title, $location, $description, $phoneError, $allowed_filetypes, $ext, $filename, $fileError); echo $fileError; echo "max size is: " .$max_size; echo "and file size is: " . $_FILES["uploadedfile"]["size"]; exit; } else { //copy file from temp to upload directory $path_of_uploaded_file = $target_path . $filename; $tmp_path = $_FILES["uploadedfile"]["tmp_name"]; echo $tmp_path; echo "and file size is: " . filesize($_FILES["uploadedfile"]["tmp_name"]); exit; if(is_uploaded_file($tmp_path)) { if(!copy($tmp_path,$path_of_uploaded_file)) { echo 'error while copying the uploaded file'; } } //test debug stuff echo "sending email..."; exit; } ?> PHP is returning this error in the log: [29-Apr-2010 10:32:47] PHP Warning: POST Content-Length of 57885895 bytes exceeds the limit of 10485760 bytes in Unknown on line 0 Excuse all the debug stuff :) FTR, I am running PHP 5.1.2 on IIS. TIA Jared

    Read the article

  • Migrating ASP.NET (MVC 2) on .NET 3.5 over to .NET 4

    - by Charlino
    I've currently got a ASP.NET MVC 2 application on .NET 3.5 and I want to migrate it over to the new .NET 4.0 with Visual Studio 2010. Reason being that it's always good to stay on top of these things - plus I really like the new automatic encoding with <%: %> and clean web.config :-) So, does anyone have any experience they could share? Looking for gotchas and the likes. I guess this could also apply to any ASP.NET Forms projects aswell. TIA, Charles

    Read the article

  • Match e-mail addresses not contained in HTML tag

    - by SvartalF
    I need to highlight an email addresses in text but not highlight them if contained in HTML tags, content, or attributes. For example, the string [email protected] must be converted to <a href="mailto:[email protected]">[email protected]</a> But email addresses in the string <a href="mailto:[email protected]">[email protected]</a> must not be processed. I've tried something like this regexp: (?<![":])[a-zA-Z0-9._%-+]+@[a-zA-Z0-9._%-]+.[a-zA-Z]{2,6}(?!") but it doesn't work properly.

    Read the article

  • Returning searched results in an array in Java without ArrayList

    - by Crystal
    I started down this path of implementing a simple search in an array for a hw assignment without knowing we could use ArrayList. I realized it had some bugs in it and figured I'd still try to know what my bug is before using ArrayList. I basically have a class where I can add, remove, or search from an array. public class AcmeLoanManager { public void addLoan(Loan h) { int loanId = h.getLoanId(); loanArray[loanId - 1] = h; } public Loan[] getAllLoans() { return loanArray; } public Loan[] findLoans(Person p) { //Loan[] searchedLoanArray = new Loan[10]; // create new array to hold searched values searchedLoanArray = this.getAllLoans(); // fill new array with all values // Looks through only valid array values, and if Person p does not match using Person.equals() // sets that value to null. for (int i = 0; i < searchedLoanArray.length; i++) { if (searchedLoanArray[i] != null) { if (!(searchedLoanArray[i].getClient().equals(p))) { searchedLoanArray[i] = null; } } } return searchedLoanArray; } public void removeLoan(int loanId) { loanArray[loanId - 1] = null; } private Loan[] loanArray = new Loan[10]; private Loan[] searchedLoanArray = new Loan[10]; // separate array to hold values returned from search } When testing this, I thought it worked, but I think I am overwriting my member variable after I do a search. I initially thought that I could create a new Loan[] in the method and return that, but that didn't seem to work. Then I thought I could have two arrays. One that would not change, and the other just for the searched values. But I think I am not understanding something, like shallow vs deep copying???....

    Read the article

  • SQL Server query replace for MySQL Instruction

    - by pojomx
    Hi, I'm new to SQL Server, and used mysql for a while now... SELECT A.acol, IF(A.acol<0,"Neg","Pos") as Column2 From Table I want to do something like that on SQL Server, but there doesn't exist the IF instruction. How do I replace that if, in a SQL Server 2008 Query?

    Read the article

  • EXEC_BAD_ACCESS in UITableView cellForRowAtIndexPath

    - by David van Dugteren
    My UITable is returning EXEC_BAD_ACCESS, but why! See this code snippet! Loading the UITableView works fine, so allXYZArray != nil and is populated! Then scrolling the tableview to the bottom and back up causes it to crash, as it goes to reload the method cellForRowAtIndexPath It fails on line: "NSLog(@"allXYZArray::count: %i", [allXYZArray count]);" - (UITableViewCell *)tableView:(UITableView *)theTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"CellIdentifier"; UITableViewCell *cell = [theTableView dequeueReusableCellWithIdentifier:CellIdentifier]; cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; @try { if (allAdviceArray == nil) { NSLog(@"nil"); allXYZArray = [ToolBox getMergedSortedDictionaries:allXYZGiven SecondDictionary:allXYZSought]; } NSLog(@"%i", [indexPath row]); NSLog(@"allXYZArray::count: %i", [allXYZArray count]);

    Read the article

  • How to format float to 2 decimals in objective C

    - by iamdadude
    I have a string that I'm converting to a float that I want to check for values in an if statement. The original float value is the iPhone's trueHeading that is returned from the didUpdateHeading method. When I convert the original float to a string using @"%.2f" it works perfectly, but what I'm trying to do is convert the original float number to the same value. IF I just convert the string to [string floatValue] I get the same original float number, and I don't want that. To make it short and simple, how do I take an existing float value and just get the first 2 decimals?

    Read the article

  • Rails user authorization

    - by Zachary
    I am currently building a Rails app, and trying to figure out the best way to authenticate that a user owns whatever data object they are trying to edit. I already have an authentication system in place (restful-authentication), and I'm using a simple before_filter to make sure a user is logged in before they can reach certain areas of the website. However, I'm not sure the best way to handle a user trying to edit a specific piece of data - for example lets say users on my site can own Books, and they can edit the properties of the book (title, author, pages, etc), but they should only be able to do this for Books that -they- own. In my 'edit' method on the books controller I would have a find that only retrieved books owned by the current_user. However, if another user knew the id of the book, they could type in http://website.com/book/7/edit , and the controller would verify that they are logged in, then show the edit page for that book (seems to bypass the controller). What is the best way to handle this? Is it more of a Rails convention routing issue that I don't understand (being able to go straight to the edit page), or should I be adding in a before_find, before_save, before_update, etc callbacks to my model?

    Read the article

  • Combobox with collection view itemssource does not update selection box item on changes to the Model

    - by Vinit Sankhe
    Hello, Sorry for the earlier lengthy post. Here is my concise (!) description. I bind a collection view to a combobox as a itemsSource and also bind its selectedvalue with a property from my view model. I must keep IsSynchronizedWithCurrentItem="False". I change the source list ofr the view and then refresh the view. The changed (added, removed, edited) items appear correctly in the item list of the combo. But problem is with the selected item. When I change its property which is also the displaymember path of the combo, the changed property value does not reflect back on the selecton box of the combo. If you open the combo dropdown it appears correctly on the item list but not on the selection box. Now if I change the combobox tag to Listbox in my XAML (keeping all attributes as it is) then when selected item's displaymember property value is updated, the changes reflect back on the selected item of the list box . Why this issue? Just FYI: My View Model has properties EmployeeCollectionView and SelectedEmployeeId which are bound to combo as ItemsSource and SelectedValue resp. This VM implements the INotifyPropertyChanged interface. My core employee class (list of which is the source for the EmployeeCollectionView) is simply a Model class without INotifyPropertyChanged. DisplayMemberPath is "Name" property of employee Model class. I change this by some means and expect the combo selection box to update the value. I tried refreshing ther SelectedEmployeeId by setting it 0 (where it correctly selects the dummy "-- Select All --" employee entry from itemsSource) and old selected value back. But no use. The old value takes me back to the old label. Items collection has latest entry though. When I make combobox's IsEditable=True before the view's refresh and after refresh I make IsEditable=False then the things work out correctly! But this is a patch and is unnecessary. Thx Vinit Sankhe

    Read the article

  • Having template function defination in cpp file - Not work for VC6

    - by Yan Cheng CHEOK
    I have the following source code : // main.cpp #include "a.h" int main() { A::push(100); } // a.cpp #include "a.h" template <class T> void A::push(T t) { } template void A::push(int t); // a.h #ifndef A_H class A { public: template <class T> static void push(T t); }; #endif The code compiled charming and no problem under VC2008. But when come to my beloved VC6, it give me error : main.obj : error LNK2001: unresolved external symbol "public: static void __cdecl A::push(int)" (?push@A@@SAXH@Z) Any workaround? I just want to ensure my function definition is re-inside cpp file.

    Read the article

  • Checking for Error during execution of a procedure in oracle

    - by Sumit Sharma
    create or replace procedure proc_advertisement(CustomerID in Number, NewspaperID in number, StaffID in Number, OrderDate in date, PublishDate in date, Type in varchar, Status in varchar, Units in number) is begin insert into PMS.Advertisement(CustomerID, NewspaperID, StaffID, OrderDate, PublishDate, Type, Status, Units) values(CustomerID,NewspaperID, StaffID, OrderDate, PublishDate, Type, Status, Units); dbms_output.put_line('Advertisement Order Placed Successfully'); end; How to check for if any error has occurred during the execution of the procedure and if any error has occurred then I wish to display an error message.

    Read the article

  • In WPF, What is the best way to create toolbar buttons so that the images are properly scaled?

    - by T.R.
    Specifically, I'm looking to use the 16*16 32-bit png images included with the VS2008ImageLibrary. I've tried manually setting the Height and Width attributes of the image, adjusting margins and padding, adjusting Stretch and RenderOptions. My attempts to create toolbar buttons have all led to either Improper Scaling (blurry icons), the bottom row of pixels on the icon being truncated, or the toolbar button being improperly sized - not to mention the disappearing icons already mentioned Here. Has anyone found the best way to make standard, VisualStudio/WinForms-style toolbar buttons that display properly in WPF?

    Read the article

  • Lucene Analyzer to Use With Special Characters and Punctuation?

    - by Brandon
    I have a Lucene index that has several documents in it. Each document has multiple fields such as: Id Project Name Description The Id field will be a unique identifier such as a GUID, Project is a user's ProjectID and a user can only view documents for their project, and Name and Description contain text that can have special characters. When a user performs a search on the Name field, I want to be able to attempt to match the best I can such as: First Will return both: First.Last and First.Middle.Last Name can also be something like: Test (NameTest) Where, if a user types in 'Test', 'Name', or '(NameTest)', then they can find the result. However, if I say that Project is 'ProjectA' then that needs to be an exact match (case insensitive search). The same goes with the Id field. Which fields should I set up as Tokenized and which as Untokenized? Also, is there a good Analyzer I should consider to make this happen? I am stuck trying to decide the best route to implement the desired searching.

    Read the article

  • Making a COM dll to be invoked from c#, HRESULT error handling?

    - by Daniel
    I'm making a COM interface that c# will be using, however i am wondering how i am to check for errors and exception handling on the c# end as at the moment i am just returning a HRESTULT or bool for most methods. But several things can go wrong in some of these methods and returning a E_FAIL just doesn't cut it. What can i do in order to return more information? Can i make a HRESULT of my own?

    Read the article

  • Looking for calculator source code, BSD-licensed

    - by Horace Ho
    I have an urgent project which need many functions of a calculator (plus a few in-house business rule formulas). As I won't have time to re-invent the wheel so I am looking for source code directly. Requirements: BSD licensed (GPL won't help) in c/c++ programming language 32-bit CPU minimum dependency on platform API/data structure best with both RPN and prefix notation supported emulator/simulator code also acceptable (if not impossible to add custom formula) with following functions (from wikipedia) Scientific notation for calculating large numbers floating point arithmetic logarithmic functions, using both base 10 and base e trigonometry functions (some including hyperbolic trigonometry) exponents and roots beyond the square root quick access to constants such as pi and e plus hexadecimal, binary, and octal calculations, including basic Boolean math fractions optional statistics and probability calculations complex numbers programmability equation solving

    Read the article

  • Swapping from NHibernate to Entity Framework &ndash; Sanity Check

    - by DesigningCode
    Now I’m not an expert in either of these techs.  I have a nice framework for unit of work / repository built with NHibernate.  Works pretty well.  I use FluentNhibernate to do the mappings.  Works well.  Takes very little code to get going with a DB back OO model. So why swap? Linq.  In Entity Framework you get much better linq support.  Visibility. I have no idea what's really happening with NHibernate….its a cloud of mystery most of the time.  You have to read all the blogs, mailing lists, etc to know what's going on. So, EF 4.0 looks like pretty good….  it has reasonably good support for mapping POCOs.  Wrapping UnitOfWork and Repository around it seems ok. Only thing I haven’t liked too much is having to explicitly load lazy loading entities. So…. am I sane?  is EF the way to go?  or is NHibernate going to suddenly release the next generation of coolness?  Is there any other major gotchas of using EF over NHibernate?

    Read the article

  • Recommend an SFTP solution for Windows (Server & Client) that integrates well with Dreamweaver

    - by aaandre
    Could you please recommend a secure FTP solution for updating files on a remote windows server from windows workstations? We would like to replace the FTP-based workflow with a secure FTP one. Windows Server 2003 on the remotely hosted webserver, WinXP on the workstations. We manage the files via Dreamweaver's built-in FTP. My understanding is Dreamweaver supports sFTP out of the box so I guess I am looking for a good sFTP server for Windows Server 2003. Ideally, that would not require cygwin. Ideally, the solution would use authentication based on the existing windows accounts and permissions. Thank you!

    Read the article

  • Is it worth while to learn Awk?

    - by user41755
    I am decent with bash scripting and I am catching on to regex, and a little sed usage. Is learning awk still worth while with all the alternatives out there. I am kind of averse to using perl, I see it as dying, for some reason I feel like bash is more of a survivor. Opinions?

    Read the article

  • Win 7 Privilege Level (Run as administrator) via GP or command line

    - by FinalizedFrustration
    Is there a way to set the Privilege Level for legacy software via group policy or on the command line? I have some legacy software, which we unfortunately cannot move away from. This software requires administrator access. I know I can go into the Properties dialog and check "Run this program as an administrator" on every single instance on every single one of my workstations, but that gets old after the 30th install. If I had my way, we would dump this software, find some software that did what we needed, was fully compliant with Win7 security best-practices and give everyone limited user accounts... However, I am not the boss, so everyone gets administrator accounts. Given that, I suppose I could just tell everyone to open the context menu and choose "Run as administrator", but we have some very, very, VERY low-tech users, and half of them might just choose "Delete" instead. Anyone know of a way to set this option on the command line? or better yet, through Group Policy?

    Read the article

< Previous Page | 6 7 8 9 10 11 12 13 14 15 16 17  | Next Page >