Daily Archives

Articles indexed Friday May 28 2010

Page 13/107 | < Previous Page | 9 10 11 12 13 14 15 16 17 18 19 20  | Next Page >

  • Looping differences in Ruby using Range vs. Times

    - by jbjuly
    I'm trying to solve a Project Euler problem using Ruby, I used 4 different looping methods, the for-loop, times, range and upto method, however the for-loop and times method only produces the expected answer, while the range and upto method does not. I'm assuming that they are somewhat the same, but I found out it's not. Can someone please explain the differences between these methods? Here's the looping structure I used # for-loop method for n in 0..1 puts n end 0 1 => 0..1 # times method 2.times do |n| puts n end 0 1 => 2 # range method (0..1).each do |n| puts n end 0 1 => 0..1 # upto method 0.upto(1) do |n| puts n end 0 1 => 0

    Read the article

  • PHP, We have sessions, and cookies....I love cookies, but they are blowing my mind right now.

    - by Matt
    I am not sure how to go about accessing the variable I need to set on a cookie... I was thinking about using the $_POST global but I dont know how based on my design if it will work. I am using a master page type design seperating index.php from my function includes and database information and individual pages (that will be returned to an include in index.php based on a $_GET) Okay so back to my question. What is the most efficient way to set a cookie on a design that has a main page that everything will branch from. How would I pull the value. Is $_POST a good enough way to go about it? Also...by saying it must be the first thing sent...does that mean I cannot run any serverside scripts before that? I could definately utilize a login query I think but I dont want to write code just to be dissapointed based on my lack of time and knowledge. I did search for answers...I know this most likely feels like a generic question that could be answered in a difference place...but I know I will get an accurate and professional answer here...so I dont want to bet on the half answers I found otherwise. Of course I will sanitize everything and not store any sensitive information (passwords,address,phone,or anything really for that matter besides some kind of session ID and the username) If this is confusing I am sorry but I am on a gov computer...and they lock these tighter than ft knox...so getting my code on here will be a chore until I get back to my room. Thanks, Matt

    Read the article

  • Potential Django Bug In QuerySet.query?

    - by Mike
    Disclaimer: I'm still learning Django, so I might be missing something here, but I can't see what it would be... I'm running Python 2.6.1 and Django 1.2.1. (InteractiveConsole) >>> from myproject.myapp.models import * >>> qs = Identifier.objects.filter(Q(key="a") | Q(key="b")) >>> print qs.query SELECT `app_identifier`.`id`, `app_identifier`.`user_id`, `app_identifier`.`key`, `app_identifier`.`value` FROM `app_identifier` WHERE (`app_identifier`.`key` = a OR `app_identifier`.`key` = b ) >>> Notice that it doesn't put quotes around "a" or "b"! Now, I've determined that the query executes fine. So, in reality, it must be doing so. But, it's pretty annoying that printing out the query prints it wrong. Especially if I did something like this... >>> qs = Identifier.objects.filter(Q(key=") AND") | Q(key="\"x\"); DROP TABLE `app_identifier`")) >>> print qs.query SELECT `app_identifier`.`id`, `app_identifier`.`user_id`, `app_identifier`.`key`, `app_identifier`.`value` FROM `app_identifier` WHERE (`app_identifier`.`key` = ) AND OR `app_identifier`.`key` = "x"); DROP TABLE `app_identifier` ) >>> Which, as you can see, not only creates completely malformed SQL code, but also has the seeds of a SQL injection attack. Now, obviously this wouldn't actually work, for quite a number of reasons (1. The syntax is all wrong, intentionally, to show the oddity of Django's behavior. 2. Django won't actually execute the query like this, it will actually put quotes and slashes and all that in there like it's supposed to). But, this really makes debugging confusing, and it makes me wonder if something's gone wrong with my Django installation. Does this happen for you? If so/not, what version of Python and Django do you have? Any thoughts?

    Read the article

  • C# SQL Parameter Errors in Loops

    - by jakesankey
    Please help me out with this. I have this small application to load txt files into a sql db and it works fine with sqlite. When I ported to SQL I started getting 'parameter already declared' errors.. If anyone can help me reorganize this code, it would be great! I need to get the parameter definitions outside of the loops or something.. using System; using System.Data; using System.Data.SQLite; using System.IO; using System.Text.RegularExpressions; using System.Threading; using System.Collections.Generic; using System.Linq; using System.Data.SqlClient; namespace JohnDeereCMMDataParser { internal class Program { public static List<string> GetImportedFileList() { List<string> ImportedFiles = new List<string>(); using (SqlConnection connect = new SqlConnection(@"Server=FRXSQLDEV;Database=RX_CMMData;Integrated Security=YES")) { connect.Open(); using (SqlCommand fmd = connect.CreateCommand()) { fmd.CommandText = @"SELECT FileName FROM Import;"; fmd.CommandType = CommandType.Text; SqlDataReader r = fmd.ExecuteReader(); while (r.Read()) { ImportedFiles.Add(Convert.ToString(r["FileName"])); } } } return ImportedFiles; } private static void Main(string[] args) { using (SqlConnection con = new SqlConnection(@"Server=FRXSQLDEV;Database=RX_CMMData;Integrated Security=YES")) { con.Open(); using (SqlCommand insertCommand = con.CreateCommand()) { Console.WriteLine("Connecting to SQL server..."); SqlCommand cmdd = con.CreateCommand(); string[] files = Directory.GetFiles(@"C:\Documents and Settings\js91162\Desktop\", "R.txt*", SearchOption.AllDirectories); insertCommand.Parameters.Add(new SqlParameter("@FeatType", DbType.String)); insertCommand.Parameters.Add(new SqlParameter("@FeatName", DbType.String)); insertCommand.Parameters.Add(new SqlParameter("@Value", DbType.String)); insertCommand.Parameters.Add(new SqlParameter("@Actual", DbType.Decimal)); insertCommand.Parameters.Add(new SqlParameter("@Nominal", DbType.Decimal)); insertCommand.Parameters.Add(new SqlParameter("@Dev", DbType.Decimal)); insertCommand.Parameters.Add(new SqlParameter("@TolMin", DbType.Decimal)); insertCommand.Parameters.Add(new SqlParameter("@TolPlus", DbType.Decimal)); insertCommand.Parameters.Add(new SqlParameter("@OutOfTol", DbType.Decimal)); List<string> ImportedFiles = GetImportedFileList(); foreach (string file in files.Except(ImportedFiles)) { var FileNameExt1 = Path.GetFileName(file); cmdd.Parameters.Add(new SqlParameter("@FileExt", FileNameExt1)); cmdd.CommandText = @" IF (EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'RX_CMMData' AND TABLE_NAME = 'Import')) BEGIN SELECT COUNT(*) FROM Import WHERE FileName = @FileExt; END"; int count = Convert.ToInt32(cmdd.ExecuteScalar()); con.Close(); con.Open(); if (count == 0) { Console.WriteLine("Parsing CMM data for SQL database... Please wait."); insertCommand.CommandText = @" INSERT INTO Import (FeatType, FeatName, Value, Actual, Nominal, Dev, TolMin, TolPlus, OutOfTol, PartNumber, CMMNumber, Date, FileName) VALUES (@FeatType, @FeatName, @Value, @Actual, @Nominal, @Dev, @TolMin, @TolPlus, @OutOfTol, @PartNumber, @CMMNumber, @Date, @FileName);"; string FileNameExt = Path.GetFullPath(file); string RNumber = Path.GetFileNameWithoutExtension(file); string RNumberE = RNumber.Split('_')[0]; string RNumberD = RNumber.Split('_')[1]; string RNumberDate = RNumber.Split('_')[2]; DateTime dateTime = DateTime.ParseExact(RNumberDate, "yyyyMMdd", Thread.CurrentThread.CurrentCulture); string cmmDate = dateTime.ToString("dd-MMM-yyyy"); string[] lines = File.ReadAllLines(file); bool parse = false; foreach (string tmpLine in lines) { string line = tmpLine.Trim(); if (!parse && line.StartsWith("Feat. Type,")) { parse = true; continue; } if (!parse || string.IsNullOrEmpty(line)) { continue; } Console.WriteLine(tmpLine); foreach (SqlParameter parameter in insertCommand.Parameters) { parameter.Value = null; } string[] values = line.Split(new[] { ',' }); for (int i = 0; i < values.Length - 1; i++) { SqlParameter param = insertCommand.Parameters[i]; if (param.DbType == DbType.Decimal) { decimal value; param.Value = decimal.TryParse(values[i], out value) ? value : 0; } else { param.Value = values[i]; } } } insertCommand.Parameters.Add(new SqlParameter("@PartNumber", RNumberE)); insertCommand.Parameters.Add(new SqlParameter("@CMMNumber", RNumberD)); insertCommand.Parameters.Add(new SqlParameter("@Date", cmmDate)); insertCommand.Parameters.Add(new SqlParameter("@FileName", FileNameExt)); // insertCommand.ExecuteNonQuery(); } } Console.WriteLine("CMM data successfully imported to SQL database..."); } con.Close(); } } } } FYI - the PartNumber, CMMNumber, Date, etc at the bottom are pulled from the file name and I need it in the table next to each respective record.

    Read the article

  • .NET Regular Expressions - Shorter match

    - by Xavier
    Hi Guys, I have a question regarding .NET regular expressions and how it defines matches. I am writing: var regex = new Regex("<tr><td>1</td><td>(.+)</td><td>(.+)</td>"); if (regex.IsMatch(str)) { var groups = regex.Match(str).Groups; var matches = new List<string>(); for (int i = 1; i < groups.Count; i++) matches.Add(groups[i].Value); return matches; } What I want is get the content of the two following tags. Instead it returns: [0]: Cell 1</td><td>Cell 2</td>... [1]: Last row of the table Why is the first match taking </td> and the rest of the string instead of stopping at </td>?

    Read the article

  • How do I encapsulate form/post/validation[/redirect] in ViewUserControl in ASP.Net MVC 2

    - by paul
    What I am trying to achieve: encapsulate a Login (or any) Form to be reused across site post to self when Login/validation fails, show original page with Validation Summary (some might argue to just post to Login Page and show Validation Summary there; if what I'm trying to achieve isn't possible, I will just go that route) when Login succeeds, redirect to /App/Home/Index also, want to: stick to PRG principles avoid ajax keep Login Form (UserController.Login()) as encapsulated as possible; avoid having to implement HomeController.Login() since the Login Form might appear elsewhere All but the redirect works. My approach thus far has been: Home/Index includes Login Form: <%Html.RenderAction("Login","User");%> User/Login ViewUserControl<UserLoginViewModel> includes: <%=Html.ValidationSummary("") % using(Html.BeginForm()){} includes hidden form field "userlogin"="1" public class UserController : BaseController { ... [AcceptPostWhenFieldExists(FieldName = "userlogin")] public ActionResult Login(UserLoginViewModel model, FormCollection form){ if (ModelState.IsValid) { if(checkUserCredentials()) { setUserCredentials() return this.RedirectToAction<Areas.App.Controllers.HomeController>(x = x.Index()); } else { return View(); } } ... } Works great when: ModelState or User Credentials fail -- return View() does yield to Home/Index and displays appropriate validation summary. (I have a Register Form on the same page, using the same structure. Each form's validation summary only shows when that form is submitted.) Fails when: ModelState and User Credentials valid -- RedirectToAction<>() gives following error: "Child actions are not allowed to perform redirect actions." It seems like in the Classic ASP days, this would've been solved with Response.Buffer=True. Is there an equivalent setting or workaround now? Btw, running: ASP.Net 4, MVC 2, VS 2010, Dev/Debugging Web Server I hope all of that makes sense. So, what are my options? Or where am I going wrong in my approach? tia!

    Read the article

  • Use different Python version with virtualenv

    - by Ulf
    I have a Debian system currently running with python 2.5.4. I got virtualenv properly installed, everything is working fine. Is there a possibility that I can use a virtualenv with a different version of Python? I compiled Python 2.6.2 and would like to use it with some virtualenv. Is it enough to overwrite the binary file? Or do I have to change something in respect to the libraries?

    Read the article

  • Having trouble creating vectors of System::String^

    - by Justen
    So I have a regex expression to parse certain parts of a file name. I'm trying to store each part in its own vector until I use it later, but it won't let me. One error I get when I try making a vector of System::String^ is that error C3698: 'System::String ^' : cannot use this type as argument of 'new' Then, when I try just making a vector of std::string, it can't implicitly convert to type System::String^, and casting won't work either. void parseData() { System::String^ pattern = "(\\D+)(\\d+)(\\w{1})(\\d+)\\.(\\D{3})"; std::vector < System::String^ > x, y, filename, separator; Regex re( pattern ); for ( int i = 0; i < openFileDialog1->FileNames->Length; i++ ) { Match^ m = re.Match( openFileDialog1->FileNames[i] ); filename.push_back( m->Groups[0]->Value );/* x.push_back( m->Groups[1]->Value ); separator.push_back( m->Groups[2]->Value ); y.push_back( m->Groups[3]->Value );*/ } }

    Read the article

  • how to initialize spring bean from database

    - by wavelet
    hi,i use spring security and my config is in database: <sec:http auto-config="true" entry-point-ref="casProcessingFilterEntryPoint"> <sec:remember-me /> <sec:session-management> <sec:concurrency-control max-sessions="1" error-if-maximum-exceeded="true" /> </sec:session-management> <sec:logout logout-success-url="${host.url}/logout/" /> <sec:custom-filter ref="casAuthenticationFilter" after="CAS_FILTER" /> <sec:custom-filter ref="filterInvocationInterceptor" before="FILTER_SECURITY_INTERCEPTOR" /> </sec:http> like ${host.url} is in database how can i initialize ?

    Read the article

  • Painfully Slow iPhone Backup?

    - by Christopher House
    And now for something completely different... For the past couple of weeks, I've not been able to sync my iPhone.  What happens is that I plug it in to my computer, start the sync and two hours later, iTunes shows it's about 75% complete.  After some googling, I tried a few things like deleting old backups, changing some settings, etc, but nothing seemed to help.  Tonight I decided I'd try deleting all the photos and videos on my phone.  Sure enough, that did the trick.  I'm now able to successfully sync in a reasonable amount of time.

    Read the article

  • scp stalls and ssh sessions freeze up (but eventually start again)

    - by coleifer
    I am running ubuntu on various computers on a home network. Some are on 9.04x64, some 10.04x64 and one 9.04x32. Running scp with a large file starts out at 2.1 mbps and drops down to about 200k, stalling and dropping until the transfer is complete. I've noticed this when I have a secure shell open on any of these servers as well. I have tried this with 2 different routers, both brand new, different brands.

    Read the article

  • How does Azureus get my firewall to open a port (Debian Linux)?

    - by Norman Ramsey
    I downloaded Azureus (a bittorrent client) for Debian Linux, and I notice that Azureus got my firewall (a Verizon wireless base station) to open a TCP and UDP port forwarding for it, without my having to do anything. My base station is password protected, and I'm alarmed at the idea that any random application can open ports without my knowing about it. Can somebody explain to me what is going on and how it is possible that Azureus can create this port-forwarding rule without any authentication?

    Read the article

  • Search Engine Optimization - The Five Factors Search Engines Use to Rank Websites

    At the end of the day, SEO requires a lot of extremely specialized knowledge, time, and attention - on an ongoing basis. But because a SEO effort can give a website's rankings a dramatic boost in the search results - and there is a significant connection between search engine ranking and search referral traffic - it is well worth doing whatever it takes to develop the knowledge and to be able to invest the time and attention.

    Read the article

  • Bad Effects From Bad Neighbors

    There are websites who make use of ethical SEO but still don't reach the top positions of the search engine results. The main reason why this situation happens can be chosen from the three: sandbox effect, over optimization or bad neighborhood.

    Read the article

  • Query data using LINQ to SQL and Entity Framework with foreign key? (Help me please)

    - by The Wind
    Hello! There is a problem I need help with your query on the data using LINQ to SQL and Entity Framework (I'm using Visual Studio 2010). My picure here: http://img.tamtay.vn/files/photo2/2010/5/28/10/962/4bff3a3b_1093f58f_untitled-1.gif I have three tables: tbl NewsDetails tblNewsCategories tblNewsInCategories (See screen 1 in my picture) Now, I want to retrieve records in the tblNewsDetails table, with condition: CategoryId=1, as the following results: (See screen 2 in my picture) But NewsID and CategoryId in tblNewsInCategories table is two foreign key, I do not see them and I do not know how to use them in your code. My code has errors: (See screen 3 in my picture) Please help me. Thanks! (I am a new member, should not have the right to insert images)

    Read the article

  • How to push both value and key into array with php

    - by sombe
    $GET = array(); $key = 'one=1'; $rule = explode('=',$key); /* array_push($GET,$rule[0]=>$rule[1]); */ I'm looking for something like this so that: print_r($GET); /*output:*/ $GET[one=>1,two=>2,...] is there a function to do this (because array_push won't work this way). thanks!

    Read the article

< Previous Page | 9 10 11 12 13 14 15 16 17 18 19 20  | Next Page >