Search Results

Search found 6988 results on 280 pages for 'statement'.

Page 4/280 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • IF statement error in tcsh

    - by kaustav datta
    Having trouble executing an IF statement through tcsh. This works FINE for me - #!/bin/bash if echo `cal|tail -6|sed -e 's/^.\{3\}//' -e 's/.\{3\}$//' |tr -s '[:blank:]' '\n' | head -11|tail -10|tr -s '\n' ' '`|grep -w `date "+%e"` then echo "present" else echo "absent" fi This is the PROBLEM - #!/bin/tcsh if echo `cal|tail -6|sed -e 's/^.\{3\}//' -e 's/.\{3\}$//' |tr -s '[:blank:]' '\n' | head -11|tail -10|tr -s '\n' ' '`|grep -w `date "+%e"` then echo "present" else echo "absent" endif Getting this error- if: Expression Syntax. then: Command not found. I really need this to run using "tcsh"

    Read the article

  • Does a C# using statement perform try/finally?

    - by Lirik
    Suppose that I have the following code: private void UpdateDB(QuoteDataSet dataSet, Strint tableName) { using(SQLiteConnection conn = new SQLiteConnection(_connectionString)) { conn.Open(); using (SQLiteTransaction transaction = conn.BeginTransaction()) { using (SQLiteCommand cmd = new SQLiteCommand("SELECT * FROM " + tableName, conn)) { using (SQLiteDataAdapter sqliteAdapter = new SQLiteDataAdapter()) { sqliteAdapter.Update(dataSet, tableName); } } transaction.Commit(); } } } The C# documentation states that with a using statement the object within the scope will be disposed and I've seen several places where it's suggested that we don't need to use try/finally clause. I usually surround my connections with a try/finally, and I always close the connection in the finally clause. Given the above code, is it reasonable to assume that the connection will be closed if there is an exception?

    Read the article

  • Why is the 'if' statement considered evil?

    - by Vadim
    I just came from Simple Design and Testing Conference. In one of the session we were talking about evil keywords in programming languages. Corey Haines, who proposed the subject, was convinced that if statement is absolute evil. His alternative was to create functions with predicates. Can you please explain to me why if is evil. I understand that you can write very ugly code abusing if. But I don't believe that it's that bad.

    Read the article

  • Pro/con: Initializing a variable in a conditional statement

    - by steffenj
    In C++ you can initialize a variable in an if statement, like so: if (CThing* pThing = GetThing()) { } Why would one consider this bad or good style? What are the benefits and disadvantages? Personally i like this style because it limits the scope of the pThing variable, so it can never be used accidentally when it is NULL. However, i don't like that you can't do this: if (CThing* pThing = GetThing() && pThing->IsReallySomeThing()) { } If there's a way to make the above work, please post. But if that's just not possible, i'd still like to know why. Question borrowed from here, similar topic but PHP.

    Read the article

  • how can i use switch statement on type-safe enum pattern

    - by Fer
    I found a goodlooking example about implementation enums in a different way. That is called type-safe enum pattern i think. I started using it but i realized that i can not use it in a switch statement. My implementation looks like the following: public sealed class MyState { private readonly string m_Name; private readonly int m_Value; public static readonly MyState PASSED= new MyState(1, "OK"); public static readonly MyState FAILED= new MyState(2, "ERROR"); private MyState(int value, string name) { m_Name = name; m_Value = value; } public override string ToString() { return m_Name; } public int GetIntValue() { return m_Value; } } What can i add to my class in order to be able to use this pattern in switch statements in C#? Thanks.

    Read the article

  • Broken if statement

    - by Vladimir Nani
    Maybe I am crazy but how that could be? some == null is always false but debugger goes into if-statement body anyway. Any ideas? I have restarted visual studio I have cleaned every bin/obj folder It is not the case that i don`t understand that WindowsIdentity.GetCurrent() may return null. That was my first idea. var some = new object(); if (some == null) { throw new Exception("hi!"); } else { do(); } My code: private void GetCurrentWindowsIdentity() { var identity = WindowsIdentity.GetCurrent() if (identity == null) { throw new Exception(Errors.IdentityIsNullException); } try { if (CurrentAuthenticationWrapper.AuthenticationType == AuthenticationType.Windows) { CurrentLogin = _identity != null ? _identity.Name : string.Empty; } } catch (Exception ex) { ViewManager.ShowError(ex); } _identity = identity; }

    Read the article

  • Strange behavior of Switch Case statement in Java

    - by supernova
    I understand that Java switch case are designed this way but why is this behavior in Java int x = 1; switch(x){ case 1: System.out.println(1); case 2: System.out.println(2); case 3: System.out.println(3); default: System.out.println("default"); } output : 1 2 3 default My question is why case 2 and 3 are executed? I know I omitted break statement but x was never 2 or 3 but case 2 and case 3 still executes?

    Read the article

  • JQuery if/else statement matching a wildcard css name

    - by Neokoenig
    Hi All, I'm trying to write an if/else statement in jQuery which can change an elements class by matching 'IN' or 'OUT' (in this case). I.e, I have several Divs with class='IN-something' OR class='OUT-something'. The below would work if I new the exact CSS class, but all I'll know is whether it contains 'IN' or 'OUT'. So like this, but works: if ($(jRow).hasClass('IN-*')) {jRow.attr( "class", "OUT-foo" );} else {jRow.attr( "class", "IN-foo");} Ideas? Thanks!

    Read the article

  • python's `with` statement

    - by Prestel Nué
    Hi there, seems like I do not understand something with---the python with statement. Consider this class: class test(object): def __enter__(self): pass def __exit__(self, *ignored): pass now, when using it with with, like in with test() as michael: print repr(michael) I would expect some output like <test instance at memore blah>. But I get None. Something wrong here? Any suggestions would help. (I am using Python 2.6.6.) EDIT: Thanks to ephement for pointing me to the documentation. The __enter__ method should read def __enter__(self): return self

    Read the article

  • Entering If Statement Despite Not Meeting Condition

    - by msmf14
    This is a specific problem, but I can't seem to figure out what is wrong. else if (X == 2) //move left { if (Level[X-1][Y] == 0); { cout << Level[X-1][Y] << "\n"; cout << "\n MOVING LEFT from RIGHT\n"; //PROBLEM IS HERE Level[X][Y] = 1; // block it X = X - 1; moved = 1; } } What I am doing is I am checking if Level[X-1][Y] is 1, indicating a column, so I can not move my player there. However for some reason, despite it being 1 and not 0 (as indicated by the output), the IF statement is still accessed. Any help will be appreciated.

    Read the article

  • “if” statement vs OO Design - 2

    - by hilal
    I encountered similar problem “if” statement vs OO Design - 1 but it is slightly different. Here is the problem that open the popup (different objects/popups) onValueChange of listbox Popup1 p1; // different objects Popup2 p2; // different objects Popup3 p3; ... listbox.add("p1"); listbox.add("p2"); listbox.add("p3"); ... listbox.addChangeHandler() { if(getSelectedItem().equals("p1")){ p1 = new Popup1(); p1.show(); } else if() {...} .... } I don't want to write "if" that if p1 then p1 = new Popup1(); p1.center(); How I can handle this situation? Any design-pattern? Here is my solution but it is so costly map() { map.put("p1", new Popup1()); map.put("p2", new Popup2()); map.put("p3", new Popup3()); } onValueChange() { map.get(selectedItem).show(); } One drawback is initialization all the popups. but it is require only when valueChange

    Read the article

  • Simply if Statement for checking co-ordinate square.

    - by JonB
    I have an UIImageView and taking the raw touch input. I need to check if a touch is within a certain set of squares. At the moment... I have this if statement.... if(46 < touchedAt.x && touchedAt.x < 124 && 18 < touchedAt.y && touchedAt.y < 75) but I have tried to simplify it to this one... if(46 < touchedAt.x < 124 && 18 < touchedAt.y < 75) It didn't work. Is it possible to simplify like this or am I stuck with the slightly lengthier version at the top? Is there a reason why the types of comparisons in the bottom if don't work? Many Thanks.

    Read the article

  • Help with MySQL Query using CASE statement

    - by hairdresser-101
    I am trying to group a number of customers together based on their "Head Office" or "Parent" location. THis works ok except for a flaw which I didn't forsee when I was developing my system... For customers that did not have a "Parent" (standalone business) I defaulted the parent_id to 0. Therefore, my data would look like this: id parent_id customer 1 0 CustName#1 2 4 CustName#2 - Melbourne 3 4 CustName#2 - Sydney 4 0 CustName#2 (Head Office) What I want to do is Group my results together so that I have one row for CustName#1 and one row for CustName#2 BUT my problem is that there is no parent record for parent_id=0 and these rows are being excluded when using an inner join. I've tried using a case statement but that is not working either (parents are still being ignored) Any help would be greatly appreciated. Here is my query (My CASE is basically trying to get the business_name from the customer table based on the parent_id EXCEPT when the parent_id = 0, THEN just use the customer_name that is listed in the job_summary table): SELECT js.month_of_year, (CASE js.parent_id WHEN 0 THEN js.customer_name ELSE c.business_name END) as customer, SUM(js.jobs), SUM(js.total_cost), sum(js.total_sell) FROM JOB_SUMMARY js INNER JOIN customer c on js.parent_id=c.id group by js.month_of_year, (CASE c.parent_id WHEN 0 THEN js.customer_name ELSE c.business_name END) ORDER BY `customer` ASC

    Read the article

  • if/else statement in a function: using onclick as a switch

    - by Aurora Schmidt
    I have looked for solutions to this on google for what seems like an eternity, but I can't seem to formulate my search correctly, or nobody has posted the code I'm looking for earlier. I am currently trying to make a function that will modify one or several margins of a div element. I want to use an if/else statement within the function, so that the onclick event will switch between the two conditions. This is what I have been working on so far; function facebookToggle() { if($('#facebooktab').style.margin-left == "-250px";) { document.getElementById("facebooktab").style.marginLeft="0px"; } else { document.getElementById("facebooktab").style.marginLeft="-250px"; } } I have tried twisting it around a little, like switching between "marginLeft" and "margin-left", to see if I was just using the wrong terms.. I'm starting to wonder if it might not be possible to combine jQuery and regular javascript? I don't know.. It's all just guesses on my part at this point. Anyway, I have a div, which is now positioned (fixed) so almost all of it is hidden outside the borders of the browser. I want the margin to change onclick so that it will be fully shown on the page. And when it is shown, I want to be able to hide it again by clicking it. I might be approaching this in the wrong way, but I really hope someone can help me out, or even tell me another way to get the same results. Thank you for any help you can give me. You can see it in action at: http://www.torucon.no/test/ (EDIT: By the way, I am a complete javascript novice, I have no experience with javascript prior to this experiment. Please don't be too harsh, as I am aware I probably made some really stupid mistakes in this short code.) EDITED CODE: function facebookToggle() { if($('#facebooktab').css('margin-left', '-250px') { $('#facebooktab').css('margin-left', '0px'); } else { $('#facebooktab').css('margin-left', '-250px'); } }

    Read the article

  • Java - If statement with String comparison fails

    - by Andrea
    I really don't know why the if statement below is not executing: if (s == "/quit") { System.out.println("quitted"); } Below is the whole class. It is probably a really stupid logic problem but I have been pulling my hair out over here not being able to figure this out. Thanks for looking :) class TextParser extends Thread { public void run() { while (true) { for(int i = 0; i < connectionList.size(); i++) { try { System.out.println("reading " + i); Connection c = connectionList.elementAt(i); Thread.sleep(200); System.out.println("reading " + i); String s = ""; if (c.in.ready() == true) { s = c.in.readLine(); //System.out.println(i + "> "+ s); if (s == "/quit") { System.out.println("quitted"); } if(! s.equals("")) { for(int j = 0; j < connectionList.size(); j++) { Connection c2 = connectionList.elementAt(j); c2.out.println(s); } } } } catch(Exception e){ System.out.println("reading error"); } } } } }

    Read the article

  • PHP elseif statement not executed even though initial if statement is false

    - by DarwinIcesurfer
    I am writing a recursive function to print out the differences between 2 multildimensional php arrays. The purpose of this code is to see the difference between jpeg headers to deteremine how adobe bridge cs3 is saving rating information within the jpg file. When I am single-stepping through the code using my eclipse - zend debugger ide, it appears that even though the initial if statement is false (ie both values are arrays), the subsequent elseif statements are never executed. The function is attached below. function array_diff_multi($array1,$array2,$level){ $keys = array_keys($array1); foreach($keys as $key) { $value1 = $array1[$key]; if(array_key_exists($key,$array2) ){ $value2 = $array2[$key]; // Check if they are both arrays, if so recursion is needed if (is_array($value1) && is_array($value2)){ array_diff_multi($value1,$value2,$level . "[ " . $key . " ]"); } // the values aren't both arrays *** THE CODE IN THE ELSEIF BELOW IS NOT EXECUTED *** elseif(is_array($value1) != is_array($value2)){ print "" . $level . $key ."=" . $value1 . "as array, compared to ". $value2 .""; } // the values don't match elseif($value1 != $value2){ print "" . $level . $key ."=" . $value1 ." != " . $value2 .""; } else; } else{ print "" . $level. $key . "does not exist in array2"; } } }

    Read the article

  • Problems with string parameter insertion into prepared statement

    - by c0d3x
    Hi, I have a database running on an MS SQL Server. My application communicates via JDBC and ODBC with it. Now I try to use prepared statements. When I insert a numeric (Long) parameter everything works fine. When I insert a string parameter it does not work. There is no error message, but an empty result set. WHERE column LIKE ('%' + ? + '%') --inserted "test" -> empty result set WHERE column LIKE ? --inserted "%test%" -> empty result set WHERE column = ? --inserted "test" -> works But I need the LIKE functionality. When I insert the same string directly into the query string (not as a prepared statement parameter) it runs fine. WHERE column LIKE '%test%' It looks a little bit like double quoting for me, but I never used quotes inside a string. I use preparedStatement.setString(int index, String x) for insertion. What is causing this problem? How can I fix it? Thanks in advance.

    Read the article

  • If statement question iphone?

    - by NextRev
    I am creating a game where where you complete shapes and the area gets filled in. However, if there is an enemy bird within your shape, it will not fill in. I want to make it so that if you do trap a bird within your shape, you will lose a life. How can I write an if statement that pretty much says if the below code doesn't take place, then you lose a life. If it helps losing a life is called doDie in my code. -(void)fillMutablePath{ CGPoint movePoint = CGPointFromString([pointsToFillArray objectAtIndex:0]); CGPathMoveToPoint(fillPath, NULL, movePoint.x, movePoint.y); for (int i=0; i<[pointsToFillArray count]; i++) { CGPoint tempPoint = CGPointFromString([pointsToFillArray objectAtIndex:i]); CGPathAddLineToPoint(fillPath, NULL, tempPoint.x, tempPoint.y); } CGContextAddPath(gameViewObj._myContext, fillPath); CGContextFillPath(gameViewObj._myContext); CGPathRelease(fillPath); [pointsToFillArray removeAllObjects]; } if(fillMutablePath doesn't take place when making a shape){ [self doDie]; } Like i said above, the reason fillMutablePath wouldn't take place is because a bird would be trapped within the shape. Any help would be much appreciated!!

    Read the article

  • Use a certain select statement in a stored procedure depending on the Exec statement

    - by MyHeadHurts
    Alright so i am not even sure if this is possible I have a q_00 and q_01 and q_02 which are all in my stored procedure. then on the bottom i have 3 select statements that select a certain catagory for example Sales,Net Sales and INS sales What i want to be able to do is if the user types exec (name of my sp) (sales) (and a year which is the @yearparameter) it will run the sales select statement If they type Exec (name of my SP) netsales (@Yeartoget) it will show the net sales is this possible or do i need multiple stored procedures ALTER PROCEDURE [dbo].[casof] @YearToGet int as ; with q_00 as ( select DIVISION , SDESCR , DYYYY , sum(APRICE) as asofSales , sum(PARTY) as asofPAX , sum(NetAmount) as asofNetSales , sum(InsAmount) as asofInsSales , sum(CancelRevenue) as asofCXSales , sum(OtherAmount) as asofOtherSales , sum(CXVALUE) as asofCXValue from dbo.B101BookingsDetails where Booked <= CONVERT(int,DateAdd(year, @YearToGet - Year(getdate()), DateAdd(day, DateDiff(day, 1, getdate()), 0))) and DYYYY = @YearToGet group by DIVISION, SDESCR, DYYYY ), q_01 as ( select DIVISION , SDESCR , DYYYY , sum(APRICE) as YESales , sum(PARTY) as YEPAX , sum(NetAmount) as YENetSales , sum(InsAmount) as YEInsSales , sum(CancelRevenue) as YECXSales , sum(OtherAmount) as YEOtherSales , sum(CXVALUE) as YECXValue from dbo.B101BookingsDetails where DYYYY=@YearToGet group by DIVISION, SDESCR, DYYYY ), q_02 as ( select DIVISION , SDESCR , DYYYY , sum(APRICE) as CurrentSales , sum(PARTY) as CurrentPAX , sum(NetAmount) as CurrentNetSales , sum(InsAmount) as CurrentInsSales , sum(CancelRevenue) as CurrentCXSales , sum(OtherAmount) as CurrentOtherSales , sum(CXVALUE) as CurrentCXValue from dbo.B101BookingsDetails where Booked <= CONVERT(int,DateAdd(year, (year( getdate() )) - Year(getdate()), DateAdd(day, DateDiff(day, 1, getdate()), 0))) and DYYYY = (year( getdate() )) group by DIVISION, SDESCR, DYYYY ) select a.DIVISION , a.SDESCR , a.DYYYY , asofSales , asofPAX , YESales , YEPAX , CurrentSales , CurrentPAX , asofsales/ ISNULL(NULLIF(yesales,0),1) as percentsales , asofpax/yepax as percentpax ,currentsales/ISNULL(NULLIF((asofsales/ISNULL(NULLIF(yesales,0),1)),0),1) as projectedsales ,currentpax/ISNULL(NULLIF((asofpax/ISNULL(NULLIF(yepax,0),1)),0),1) as projectedpax from q_00 as a join q_01 as b on (b.DIVISION = a.DIVISION and b.SDESCR = a.SDESCR and b.DYYYY = a.DYYYY) join q_02 as c on (b.DIVISION = c.DIVISION and b.SDESCR = c.SDESCR) order by a.DIVISION, a.SDESCR, a.DYYYY ; select a.DIVISION , a.SDESCR , a.DYYYY , asofPAX , asofNetSales , YEPAX , YENetSales , CurrentPAX , CurrentNetSales , asofnetsales/ ISNULL(NULLIF(yenetsales,0),1) as percentnetsales , asofpax/yepax as percentpax ,currentnetsales/ISNULL(NULLIF((asofnetsales/ISNULL(NULLIF(yenetsales,0),1)),0),1) as projectednetsales ,currentpax/ISNULL(NULLIF((asofpax/ISNULL(NULLIF(yepax,0),1)),0),1) as projectedpax from q_00 as a join q_01 as b on (b.DIVISION = a.DIVISION and b.SDESCR = a.SDESCR and b.DYYYY = a.DYYYY) join q_02 as c on (b.DIVISION = c.DIVISION and b.SDESCR = c.SDESCR) order by a.DIVISION, a.SDESCR, a.DYYYY ; select a.DIVISION , a.SDESCR , a.DYYYY , asofPAX , asofInsSales , YEPAX , YEInsSales , CurrentPAX , CurrentInsSales , asofinssales/ ISNULL(NULLIF(yeinssales,0),1) as percentsales , asofpax/yepax as percentpax ,currentinssales/ISNULL(NULLIF((asofinssales/ISNULL(NULLIF(yeinssales,0),1)),0),1) as projectedinssales from q_00 as a join q_01 as b on (b.DIVISION = a.DIVISION and b.SDESCR = a.SDESCR and b.DYYYY = a.DYYYY) join q_02 as c on (b.DIVISION = c.DIVISION and b.SDESCR = c.SDESCR) order by a.DIVISION, a.SDESCR, a.DYYYY ;

    Read the article

  • Can't bind string containing @ char with mysqli_stmt_bind_param

    - by Tirithen
    I have a problem with my database class. I have a method that takes one prepared statement and any number of parameters, binds them to the statement, executes the statement and formats the result into a multidimentional array. Everthing works fine until I try to include an email adress in one of the parameters. The email contains an @ character and that one seems to break everything. When I supply with parameters: $types = "ss" and $parameters = array("[email protected]", "testtest") I get the error: Warning: Parameter 3 to mysqli_stmt_bind_param() expected to be a reference, value given in ...db/Database.class.php on line 63 Here is the method: private function bindAndExecutePreparedStatement(&$statement, $parameters, $types) { if(!empty($parameters)) { call_user_func_array('mysqli_stmt_bind_param', array_merge(array($statement, $types), &$parameters)); /*foreach($parameters as $key => $value) { mysqli_stmt_bind_param($statement, 's', $value); }*/ } $result = array(); $statement->execute() or debugLog("Database error: ".$statement->error); $rows = array(); if($this->stmt_bind_assoc($statement, $row)) { while($statement->fetch()) { $copied_row = array(); foreach($row as $key => $value) { if($value !== null && mb_substr($value, 0, 1, "UTF-8") == NESTED) { // If value has a nested result inside $value = mb_substr($value, 1, mb_strlen($value, "UTF-8") - 1, "UTF-8"); $value = $this->parse_nested_result_value($value); } $copied_row[$ke<y] = $value; } $rows[] = $copied_row; } } // Generate result $result['rows'] = $rows; $result['insert_id'] = $statement->insert_id; $result['affected_rows'] = $statement->affected_rows; $result['error'] = $statement->error; return $result; } I have gotten one suggestion that: the array_merge is casting parameter to string in the merge change it to &$parameters so it remains a reference So I tried that (3rd line of the method), but it did not do any difference. How should I do? Is there a better way to do this without call_user_func_array?

    Read the article

  • ms sql use like statement result in if statement

    - by Asha
    declare @d varchar set @d = 'No filter' if (@d like 'No filter') BEGIN select 'matched' end else begin select 'not matched' end the result of above is always not matched can anybody tell me why and how can I use the like or '=' result in my stored procedure. thanks

    Read the article

  • Show choosen option in a notification Feed, Django

    - by apoo
    Hey I have a model where : LIST_OPTIONS = ( ('cheap','cheap'), ('expensive','expensive'), ('normal', 'normal'), ) then I have assigned the LIST_OPTIONS to nature variable. nature = models.CharField(max_length=15, choices=LIST_OPTIONS, null=False, blank=False). then I save it: if self.pk: new=False else: new=True super(Listing, self).save(force_insert, force_update) if new and notification: notification.send(User.objects.all().exclude(id=self.owner.id), "listing_new", {'listing':self, }, ) then in my management.py: def create_notice_types(app, created_models,verbosity, **kwargs): notification.create_notice_type("listing_new", _("New Listing"), _("someone has posted a new listing"), default=2) and now in my notice.html I want to show to users different sentences based on the options that they have choose so something like this: LINK href="{{ listing.owner.get_absolute_url }} {{listing.owner}} {% ifequal listing.nature "For Sale" %} created a {{ listing.nature }} listing, <a href="{{ listing.get_absolute_url }}">{{listing.title}}</a>. {% ifequals listing.equal "Give Away"%} is {{ listing.nature }} , LINK href="{{ listing.get_absolute_url }}" {{listing.title}}. {% ifequal listing.equal "Looking For"%} is {{ listing.nature }} , LINK href="{{ listing.get_absolute_url }}" {{listing.title}} {% endifequal %} {% endifequal %} {% endifequal %} Could you please help me out with this. Thank you

    Read the article

  • How to join dynamic sql statement in variable with normal statement

    - by Oliver
    I have a quite complicated query which will by built up dynamically and is saved in a variable. As second part i have another normal query and i'd like to make an inner join between these both. To make it a little more easier here is a little example to illustrate my problem. For this little example i used the AdventureWorks database. Some query built up dynamically (Yes, i know here is nothing dynamic here, cause it's just an example.) DECLARE @query AS varchar(max) ; set @query = ' select HumanResources.Employee.EmployeeID ,HumanResources.Employee.LoginID ,HumanResources.Employee.Title ,HumanResources.EmployeeAddress.AddressID from HumanResources.Employee inner join HumanResources.EmployeeAddress on HumanResources.Employee.EmployeeID = HumanResources.EmployeeAddress.EmployeeID ;'; EXEC (@query); The normal query i have select Person.Address.AddressID ,Person.Address.City from Person.Address Maybe what i'd like to have but doesn't work select @query.* ,Addresses.City from @query as Employees inner join ( select Person.Address.AddressID ,Person.Address.City from Person.Address ) as Addresses on Employees.AddressID = Addresses.AddressID

    Read the article

  • Java: If vs. Switch

    - by _ande_turner_
    I have a piece of code with a) which I replaced with b) purely for legibility ... a) if ( WORD[ INDEX ] == 'A' ) branch = BRANCH.A; /* B through to Y */ if ( WORD[ INDEX ] == 'Z' ) branch = BRANCH.Z; b) switch ( WORD[ INDEX ] ) { case 'A' : branch = BRANCH.A; break; /* B through to Y */ case 'Z' : branch = BRANCH.Z; break; } ... will the switch version cascade through all the permutations or jump to a case ? EDIT: Some of the answers below regard alternative approaches to the approach above. I have included the following to provide context for its use. The reason I asked, the Question above, was because the speed of adding words empirically improved. This isn't production code by any means, and was hacked together quickly as a PoC. The following seems to be a confirmation of failure for a thought experiment. I may need a much bigger corpus of words than the one I am currently using though. The failure arises from the fact I did not account for the null references still requiring memory. ( doh ! ) public class Dictionary { private static Dictionary ROOT; private boolean terminus; private Dictionary A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z; private static Dictionary instantiate( final Dictionary DICTIONARY ) { return ( DICTIONARY == null ) ? new Dictionary() : DICTIONARY; } private Dictionary() { this.terminus = false; this.A = this.B = this.C = this.D = this.E = this.F = this.G = this.H = this.I = this.J = this.K = this.L = this.M = this.N = this.O = this.P = this.Q = this.R = this.S = this.T = this.U = this.V = this.W = this.X = this.Y = this.Z = null; } public static void add( final String...STRINGS ) { Dictionary.ROOT = Dictionary.instantiate( Dictionary.ROOT ); for ( final String STRING : STRINGS ) Dictionary.add( STRING.toUpperCase().toCharArray(), Dictionary.ROOT , 0, STRING.length() - 1 ); } private static void add( final char[] WORD, final Dictionary BRANCH, final int INDEX, final int INDEX_LIMIT ) { Dictionary branch = null; switch ( WORD[ INDEX ] ) { case 'A' : branch = BRANCH.A = Dictionary.instantiate( BRANCH.A ); break; case 'B' : branch = BRANCH.B = Dictionary.instantiate( BRANCH.B ); break; case 'C' : branch = BRANCH.C = Dictionary.instantiate( BRANCH.C ); break; case 'D' : branch = BRANCH.D = Dictionary.instantiate( BRANCH.D ); break; case 'E' : branch = BRANCH.E = Dictionary.instantiate( BRANCH.E ); break; case 'F' : branch = BRANCH.F = Dictionary.instantiate( BRANCH.F ); break; case 'G' : branch = BRANCH.G = Dictionary.instantiate( BRANCH.G ); break; case 'H' : branch = BRANCH.H = Dictionary.instantiate( BRANCH.H ); break; case 'I' : branch = BRANCH.I = Dictionary.instantiate( BRANCH.I ); break; case 'J' : branch = BRANCH.J = Dictionary.instantiate( BRANCH.J ); break; case 'K' : branch = BRANCH.K = Dictionary.instantiate( BRANCH.K ); break; case 'L' : branch = BRANCH.L = Dictionary.instantiate( BRANCH.L ); break; case 'M' : branch = BRANCH.M = Dictionary.instantiate( BRANCH.M ); break; case 'N' : branch = BRANCH.N = Dictionary.instantiate( BRANCH.N ); break; case 'O' : branch = BRANCH.O = Dictionary.instantiate( BRANCH.O ); break; case 'P' : branch = BRANCH.P = Dictionary.instantiate( BRANCH.P ); break; case 'Q' : branch = BRANCH.Q = Dictionary.instantiate( BRANCH.Q ); break; case 'R' : branch = BRANCH.R = Dictionary.instantiate( BRANCH.R ); break; case 'S' : branch = BRANCH.S = Dictionary.instantiate( BRANCH.S ); break; case 'T' : branch = BRANCH.T = Dictionary.instantiate( BRANCH.T ); break; case 'U' : branch = BRANCH.U = Dictionary.instantiate( BRANCH.U ); break; case 'V' : branch = BRANCH.V = Dictionary.instantiate( BRANCH.V ); break; case 'W' : branch = BRANCH.W = Dictionary.instantiate( BRANCH.W ); break; case 'X' : branch = BRANCH.X = Dictionary.instantiate( BRANCH.X ); break; case 'Y' : branch = BRANCH.Y = Dictionary.instantiate( BRANCH.Y ); break; case 'Z' : branch = BRANCH.Z = Dictionary.instantiate( BRANCH.Z ); break; } if ( INDEX == INDEX_LIMIT ) branch.terminus = true; else Dictionary.add( WORD, branch, INDEX + 1, INDEX_LIMIT ); } public static boolean is( final String STRING ) { Dictionary.ROOT = Dictionary.instantiate( Dictionary.ROOT ); return Dictionary.is( STRING.toUpperCase().toCharArray(), Dictionary.ROOT, 0, STRING.length() - 1 ); } private static boolean is( final char[] WORD, final Dictionary BRANCH, final int INDEX, final int INDEX_LIMIT ) { Dictionary branch = null; switch ( WORD[ INDEX ] ) { case 'A' : branch = BRANCH.A; break; case 'B' : branch = BRANCH.B; break; case 'C' : branch = BRANCH.C; break; case 'D' : branch = BRANCH.D; break; case 'E' : branch = BRANCH.E; break; case 'F' : branch = BRANCH.F; break; case 'G' : branch = BRANCH.G; break; case 'H' : branch = BRANCH.H; break; case 'I' : branch = BRANCH.I; break; case 'J' : branch = BRANCH.J; break; case 'K' : branch = BRANCH.K; break; case 'L' : branch = BRANCH.L; break; case 'M' : branch = BRANCH.M; break; case 'N' : branch = BRANCH.N; break; case 'O' : branch = BRANCH.O; break; case 'P' : branch = BRANCH.P; break; case 'Q' : branch = BRANCH.Q; break; case 'R' : branch = BRANCH.R; break; case 'S' : branch = BRANCH.S; break; case 'T' : branch = BRANCH.T; break; case 'U' : branch = BRANCH.U; break; case 'V' : branch = BRANCH.V; break; case 'W' : branch = BRANCH.W; break; case 'X' : branch = BRANCH.X; break; case 'Y' : branch = BRANCH.Y; break; case 'Z' : branch = BRANCH.Z; break; } if ( branch == null ) return false; if ( INDEX == INDEX_LIMIT ) return branch.terminus; else return Dictionary.is( WORD, branch, INDEX + 1, INDEX_LIMIT ); } }

    Read the article

  • Using wildcards in prepared statement - MySQLi

    - by Michael Irwin
    Hi! I'm trying to run the following query, and I'm having trouble with the wildcard. function getStudents() { global $db; $users = array(); $query = $db->prepare("SELECT id, adminRights FROM users WHERE classes LIKE ? && adminRights='student'"); $query->bind_param('s', '%' . $this->className . '%'); $query->execute(); $query->bind_result($uid, $adminRights); while ($query->fetch()) { if (isset($adminRights[$this->className]) && $adminRights[$this->className] == 'student') $users[] = $uid; } $query->close(); return $users; } I'm getting an error that states: Cannot pass parameter 2 by reference. The reason I need to use the wildcard is because the column's data contains serialized arrays. I guess, if there's an easier way to handle this, what could I do? Thanks in advance!

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >