Menu
  • HOME
  • TAGS

2 join conditions codeigniter giving error

codeigniter,join,condition

This is wrong in your query $this->db->join('documents as D', 'D.name="declaration"','left'); you can compare column using where clause public function get_all_orders($user_id){ $this->db->select('ordersheader.*, customer.name as customerName,documents.date_make'); $this->db->from('ordersheader'); $this->db->join('customer', 'ordersheader.idCustomer = customer.idCustomer'); $this->db->join('documents', 'ordersheader.idOrder = documents.idOrder','left'); // $this->db->join('documents as D',...

T-SQL conditional AND statement

sql-server,tsql,condition,table-valued-parameters,sql-in

This version assumes that results should still be returned even when @tvp is empty. It says that @tvp is either empty or t.foo1 is IN @tvp. WHERE t.foo4 = @var AND ( NOT EXISTS (SELECT 1 FROM @tvp) OR t.foo1 IN (SELECT @tvp.foo1 FROM @tvp) ) ...

Regexp split string with additional conditions

python,regex,split,condition

Use a negative lookahead assertion based regex. >>> a = 'text1, text2 (subtext1, subtext2), text3' >>> re.split(r',(?![^()]*\))', a) ['text1', ' text2 (subtext1, subtext2)', ' text3'] >>> re.split(r',\s*(?![^()]*\))', a) ['text1', 'text2 (subtext1, subtext2)', 'text3'] DEMO OR Positive lookahead based regex. >>> re.split(r',\s*(?=[^()]*(?:\(|$))', a) ['text1', 'text2 (subtext1, subtext2)', 'text3'] ...

C conditional increment

c,condition,increment,temporary

Yes, b=0 now. And the decrement is permanent within the scope of the function you have defined b in.

Sum of one column in special condition [closed]

c#,sql,sum,condition

Try this: UPDATE table1 SET table1.field = (SELECT SUM(table2.column2) FROM table2 WHERE table2.fk_table1 = table1.id AND table2.column3 = 1) <-- Usually true = 1, false = 0 and tinyint or equivalent type is the used type. ...

How to implement a search in multiple fields based on condition(s)

java,hibernate,if-statement,condition,hibernate-criteria

I really hate this, I see this often, but I guess my point was not clear enough, so I will answer my question on my own, sorry! A friend of mine asked me: "Can't you use a list of fields, instead of passing them seriatim? Well, I checked this and...

preg_match only show replacement if found

php,regex,condition

I'd merge the 2 optional groups into 1 and use a 2nd preg_replace to add double quotation marks around the attribute values inside opening tags. We cannot do it in 1 go as the replacement pattern is different for tags with attributes. $input = preg_replace('/\{(\/)?'.$tag.'( [a-z]*\=[a-zA-Z0-9\.\:\/]*)?\}/', '<$1' . $tag ....

Retrieve a value from an array and make a condition

php,arrays,condition

Your array values (the color names) include single quotes, which you need to include when you search for a value: if(in_array("'white'", $colors) { // ... } ...

MSSQL Select rows not matching criteria

sql-server,select,condition

Do it the other way around. For each row in the second table, check if the same product and version exists in the first table. SELECT * FROM table2 WHERE NOT EXISTS (SELECT 1 FROM table1 WHERE table1.ProductName LIKE '%' + table2.ProductName + '%' AND table1.version <> table2.ProductVersion) ...

MySQL SELECT email where field contains a value

mysql,sql,condition

This will do the work assuming number of newsletter can't be higher than 9: SELECT email FROM users WHERE newsletters LIKE '%2%' If you'd like to have more of them then table normalization would be very helpful. EDIT: @sgeddes in comments has great proposition to make it working for any...

How to check if specific resource already exists in CloudFormation script

amazon-web-services,automation,condition,amazon-cloudformation

There is no obvious way to do this, unless you create the template dynamically with an explicit check. Stacks created from the same template are independent entities, and if you create a stack that contains a bucket, delete the stack while retaining the bucket, and then create a new stack...

How to remove all empty tag with conditons in XSL

xml,xslt,tags,condition,xmlns

First of all, you need to correct your XMLs to be valid. I hope, that you meant <cEAN/> by </cEAN> as I don't see any start tag for that. And there can be no @priority in xsl:preserve-space element. If my assumptions are correct, it is the expected behavior. An element...

typoscript condition on get parameter

parameters,get,condition,typoscript

It looks like it's impossible for included files: https://forge.typo3.org/issues/29583...

Hibernate HQL query with condition on second table

oracle,hibernate,hql,condition,one-to-many

The contract of league.getTeams() is to return the teams of the league. And the method will always return that, whatever the way you found the league. Your query returns all the leagues which have at least a team starting with S. The query you need is something like select l,...

C++: Checking if user input is one of the characters A, W, or D

python,c++,validation,loops,condition

You're checking a char against a string, have you tried classificationCode != 'b' ...

Better way to check that multiple variables doesn't have any duplicated value

c#,.net,condition

I'd probably use LINQ with this, which of course requires putting them into a collection. public static bool HasDuplicates<T>(params T[] arr) { return arr.Distinct().Count() != arr.Length; } Of course, you'd call this as follows: if(!HasDuplicates(option1 ,option2, option3, option4)) { // Code } There might be a better way to run...

VBA lookup for approximate value

vba,match,condition,criteria,vlookup

This should work (I decided not to use worksheetfunction.vlookup): Sub MyVlookup2() Dim myrange As Range Dim i As Long, j As Long Dim lastrow As Long Dim lastrow2 As Long Dim diff As Double Const tolerance As Long = 100 Set myrange = Range("D:G") lastrow = Sheets("Sheet1").Range("B" & Rows.Count).End(xlUp).Row lastrow2...

Dynamical SUMIF command

excel,sum,condition

You can do this easily by using an absolute reference for the starting point of a SUM and using a relative reference for the end point. When copied down, this formulas works fine. =IF(SUM($A$1:A1)<$D$1,"x","") Results ...

Using counter in condition in python

python,if-statement,condition

i = i + 5 is always true unless previous value of i is -5. However, if i = i + 5 is invalid syntax. i == i + 5 is always false. In if flag == True portion explicit comparing with True is redundant. if flag is sufficient. Now...

how to calculate the mean with conditions? [duplicate]

r,condition,mean

Here's a quick data.table solution (assuming coef is a) library(data.table) setDT(df)[, .(MeanASmall = mean(b[-40 <= a & a < 0]), MeanABig = mean(b[0 <= a & a <= 40]))] # MeanASmall MeanABig # 1: 33.96727 89.46 If a range is limited, you could do this quickly with base R too...

python 3.4 condition involving byte literal returns false instead of true

python,mysql,condition,pymysql

You're comparing bytes and unicode and this is bound to always compare to False in Python 3. Some references: http://scikit-bio.org/docs/0.1.3/development/py3.html#gotchas http://lucumr.pocoo.org/2013/7/2/the-updated-guide-to-unicode/ The solution is not to call encode() on your empty string on the right hand side: Python 3.4.2 (default, Oct 8 2014, 10:45:20) [GCC 4.9.1] on linux Type "help",...

PHP condition with IF working incorrect [duplicate]

php,if-statement,upload,condition

your code is returning a 0 when evaluating the string position for the file "phpminiadmin.php" and thus "==" interprets that as FALSE. As an example try using the filename, "aphpminiadmin.php". Your code will then work correctly because strpos returns a 1 which is clearly not false. Thus, the change that...

.htaccess multiple rewrite condtion - using first condition matched parts in second condition

.htaccess,rewrite,condition

You can combine both conditions into one and use a back-reference to earlier captured group like this: RewriteCond %{HTTP_HOST}:%{REQUEST_URI} ^([^.]+)\.[^:]+:(?!/\1/).*$ Your .htaccess can be this: RewriteEngine On RewriteBase /assets/ RewriteCond %{HTTP_HOST}:%{REQUEST_URI} ^([^.]+)\.[^:]+:/assets/(?!\1/).*$ RewriteRule ^(.*)$ %1/dam/collection/a.txt? [L,R=302] ...

WiX: Install component based on ComboBox selection

combobox,wix,condition

The property needs to be public (upper-case) and the comparison needs to be done inside a CDATA. You could use the case-insensitive comparison ~=. <Component Id="ComponentRed" Guid="*" Directory="INSTALLFOLDER"> <File Id="R" Name="red.txt" Source="red.txt" /> <Condition> <![CDATA[OPTION~="Red"]]> </Condition> </Component> <Control Id="MyComboBox" Type="ComboBox" X="20" Y="140" Width="56" Height="17" Property="OPTION"> <ComboBox Property="OPTION"> <ListItem Text="Red" Value="Red"...

How do I query a table with conditions from related table with Laravel 5

laravel,eloquent,condition,relationship

That's what whereHas is for: $Videos = \App\Models\Video::with('user')->whereHas('user', function($q){ $q->where('name','=','Max'); })->get(); ...

Parse error: syntax error, unexpected 'if' (T_IF), expecting ')'

php,arrays,if-statement,condition

Thanks for everyone $content['custom_fields'] = array( array( "key" => "_yoast_wpseo_focuskw", "value" => $_POST["title"] ), array( "key" => "_yoast_wpseo_metadesc", "value" => $_POST["titleenfa"] ), array( "key" => "_yoast_wpseo_metakeywords", "value" => $_POST["metakey"] ) ); if($_POST["link128"]){ array_push($content['custom_fields'], array( "key" => "_link128", "value" => "field_54b398292c295" ) ); array_push($content['custom_fields'], array( "key" => "link128", "value" => $_POST["link128"]...

Python Reuse a Variable in the Else Block of an If-Else Statement

python,python-3.x,if-statement,condition

When you call getSrc a second time, the value of source that was created the first time has long since gone out of scope and been garbage collected. To prevent this, try making source an attribute of the function the same way you did for has_been_called. def getSrc(): if getSrc.has_been_called...

Using R, return column numbers where a condition is met

r,numbers,condition

You can try with apply by rows: a<-c(0, 0 ,0 ,0 ,0, 0, 0, 0, 0 , 0 , 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 , 0) b<-c(0, 0 ,0 ,1 ,0, 0, 0, 0, 0 , 1 , 0, 0, 0, 0,...

SQL query with condition

sql,sql-server,condition

You can use the CASE statement in your SELECT: SELECT CASE WHEN SOI_IMA_RecordID IS NULL OR SOI_LineNbrTypeCode = 'GL Acct' THEN SOI_MiscLineDescription ELSE IMA_ItemName END ItemName, -- ... FROM WSI_SOH SOH INNER JOIN SalesOrderDelivery SOD ON SOH.SOH_SOD_RecordID = SOD.SOD_RecordID INNER JOIN SalesOrder SO ON SO.SOM_RecordID = SOD.SOD_SOM_RecordID INNER JOIN SalesOrderLine...

How To Convert Array To XML With Condition On PHP

php,arrays,xml,condition

You can use SimpleXML:get more help from here with proper discussion in comments. for your customized way try this.it should solve your problem: <?php $test_array=Array ( '1' => Array ( 'id' => 1, 'name' => 'INTERNET', 'download' => Array ( '0' => Array ( 'name' => 'DOWNLOAD', 'value' => 1024...

Python Pandas: How to use 'where' and 'isin' with two conditions?

python,pandas,group-by,condition

Lets break down your huge statement a bit: a['tag'] = np.where(((a['match_x'] == a['match_y']) & (a.groupby(['group', 'match_x','match_y'])['group'].count() == 1)),'TP', 'FN') Lifting out the mask: mask = ((a['match_x'] == a['match_y']) & (a.groupby(['group', 'match_x','match_y'])['group'].count() == 1)) a['tag'] = np.where(mask,'TP', 'FN') Breaking down the mask: mask_x_y_equal = a['match_x'] == a['match_y'] single_line = a.groupby(['group', 'match_x','match_y']).size()...

sql left join returns

sql,left-join,condition,records

As soon as you put a condition in the WHERE clause that references the right table and doesn't accommodate the NULLs that will be produced when the join is unsuccessful, you've transformed it (effectively) back into an INNER JOIN. Try: where B.fixed = 'b580' OR B.fixed IS NULL Or add...

Excel IF AND OR condition together

excel,if-statement,condition

Your parenthesis are unbalanced. Try: =IF(OR(AND(B2>=Sheet3!$B$4,B2<=Sheet3!$C$4),AND(B2>=Sheet3!B6,B2<=Sheet3!C6)),"Blue","Grey") ...

If condition in linq

c#,linq,if-statement,condition

You just need to add it as part of the existing conditional. You can't add an if statement in the middle. In other words, something like: X.FormulaCode.Contains(formualcode) && X.BaseCode.Contains(txtBase.Text) && (RBstatus.SelectedValue == "Any" || X.Status.Contains(RBstatus.SelectedValue)) Alternatively, since these are all logical ANDs, you can simply chain the Where clauses, i.e.:...

LINQ to SQL: How to create something like conditional include?

.net,linq,entity-framework,include,condition

If you are only trying to get the events where userID ==1, you can use the following. This will give you only the event you need from the Event Collection for the user. User u = new User() { UserId = 60 }; Event e1 = new Event() { EventId...

counting unique values with it's associated count and total number of values

javascript,jquery,loops,condition

You could start by creating an object like this: var map = {}; for (var i = 0, count = items.length; i < count; i++) { map[items[i]] = (map[items[i]] || 0) + magnitude[i]; } jsfiddle You can view the values like this: for (var item in map) { console.log(item +...

java code: if statement not the expected output [duplicate]

java,if-statement,condition

First part: When you write 6/100*y, it's equal to (6/100)*y. But the expression 6/100 is integer division, which is equal to 0. Thus 0*y = 0. What you want to do is change 6/100 to 0.06, and 4/100 to 0.04. Second part: The correct syntax is System.out.println("YOUr salary is: "...

is it possible to write regular expression in $cond in MongoDB

regex,mongodb,condition

There is an open JIRA issue for this SERVER-8892 - Use $regex as the expression in a $cond. However, as a workaround, use the following aggregation pipeline. It uses the $substr operator in the $project operator stage to extract the part of the URL and acts as a workaround for...

How do you start a function at a certain time in Python?

python,multithreading,events,time,condition

There are several ways -- some are more easily portable to different operating systems than others. Generally, what you could do is: spawn a new thread for every task in each thread, get the current time, and time.sleep() for the remaining time That works, but it's not extremely accurate. You...

mod_rewrite RewriteCond falsly doesn't match pattern

regex,mod-rewrite,condition

Problem is in the 2nd rule, it should be %{REQUEST_URI} instead of ${REQUEST_URI} RewriteCond %{REQUEST_URI} a RewriteRule .? - [E=tpl:presentation] Or better just: RewriteRule a - [E=tpl:presentation] ...

ruby // present or nil

ruby,syntax,condition

You can use || like this: val = params[:page] || nil If params[:page] is nil or false, val will be nil. In all other cases it will be the value of params[:page]....

Copy subdirectories if they contain a specific file in Ant

xml,recursion,ant,condition

I don't think there exist a predefined property in ant because your requirements are very specific. You may use <foreach> task from ant-contrib and write a recursive target which performs a copy. Or you may implement the recursive solution in javascript using <script language="javascript"> . In this case you don't...

Assing to data.frame bases on a vector value leaving the rest untouched

r,data.frame,condition

If you subset a vector by logical vector cond, positions where cond==TRUE is returned. So you can do a partial assignment as, y <- rep(3, 7) z <- rep(3, 7) y[cond] <- x[cond] * df1$n[cond] z[cond] <- v[cond] * df1$n[cond] + df2$n[cond] cbind(y, z) # y z #[1,] 332592 674203...

Matching a pattern with `match()` with extra condition

r,match,condition

This works: fixedTrue <- function(x, y) { toChange <- which(match(x, exact_orig) == match(y, exact_flag)) x[toChange] <- exact_change[match(x[toChange], exact_orig)] } Amended to check positions in flag and orig the same Slightly closer to original: fixedTrue <- function(x, y) { m <- match(x, exact_orig); n <- match(y, exact_flag) x[which(m == n)] <-...

Java: if, switch or question mark double point

java,if-statement,switch-statement,condition

Looking at your code , With any modern compiler all of the above conditionals compile into the same instructions. Focus on readability and maintainability of your code. They have negligible effect on performance You can use ternary in places where you can't use if-else or switch for example System.out.println ("Good...

How to autowire properties bean from Condition

java,spring,initialization,condition,autowired

If we have a look at java docs for Condition interface - Conditions must follow the same restrictions as BeanFactoryPostProcessor and take care to never interact with bean instances. The restrictions are (from java docs of BeanFactoryPostProcessor) A BeanFactoryPostProcessor may interact with and modify bean definitions, but never bean instances....

Select from table where some WHERE condition missing

php,mysql,sql,sorting,condition

You can use the following code to generate your SQL query $param=Array(); ## associate query parameters to sql column $keys=Array("room" => "kk", "status" => "sold"); ## generate parameter list foreach ($keys as $k=>$v) if (isset($_GET[$k])&&($_GET[$k]!='all')) $param[$v]=$_GET[$k]; ## generate query $query="SELECT DISTINCT flatnetto FROM flat WHERE ". implode(" = ? AND...

MySQL SUM of field with conditon, IF(SUM(bill_1) IS NULL, '99', SUM(bill_1)) AS tot_bill_1

mysql,if-statement,join,sum,condition

You can do this using subquery: SELECT sum_bill1, sum_bill2, (sum_bill1 + sum_bill2) AS total FROM (SELECT COALESCE(sum(bill1), 99) AS sum_bill1, COALESCE(sum(bill2), 10) AS sum_bill2 FROM billings) t ...

Selection Condition Array In PHP

php,arrays,if-statement,conditional,condition

So with your data you have many possibilities how to organize that: 1st just check null: elseif (!($data['DOWNLOAD']==null && $data['UPLOAD']==null)) { $product[$idx][0]['attributeName'] = 'DOWNLOAD'; $product[$idx][0]['attributeValue'] = $data['DOWNLOAD']; $product[$idx][1]['attributeName'] = 'UPLOAD'; $product[$idx][1]['attributeValue'] = $data['UPLOAD']; } 2nd Check current parent name so: if($data['PARENT'] == 0) { $idx++; $product[$idx]['id'] = $data['ID']; $product[$idx]['name'] =...

MySQL Conditional count based on a value in another column

mysql,count,distinct,condition

One approach is to use a correlated subquery. Just get the list of ranks and then use a correlated subquery to get the count you are looking for: SELECT r.rank, (SELECT COUNT(DISTINCT t2.id) FROM myTable t2 WHERE t2.rank >= r.rank ) as cnt FROM (SELECT DISTINCT rank FROM myTable) r;...

R sorting using simple codes

r,sorting,date,condition

As I understand your question: df <- data.frame(Ticketid = c('a1','b1','c1','a1','d1','e1','b1','a1','b1','b1'), Creation_Date = as.Date(c('01-02-2015','03-02-2015','03-02-2015','03-02-2015','03-02-2015','03-02-2015','11-02-2015','11-02-2015','14-02-2015','27-02-2015'), format = '%d-%m-%Y'), Location = c('A','B','C','D','A','A','B','C','F','E'), Person = c('John','Jack','Mint','Manu', 'Somu','John', 'Jack', 'Mint','John','John') ) Ticketid Creation_Date Location Person 1 a1 2015-02-01 A John 2 b1 2015-02-03 B Jack 3 c1 2015-02-03 C...

How does Python evaluate multiple conditions in or statement?

python,condition,boolean-logic

or and and both use short-circuiting; they will only evaluate as many conditions as necessary to determine a result. So, if 'string1' in a returns True, 'string2' in a will never be touched.

Objective C: -1 < 0 return false

objective-c,condition

Thats because count is NSUInteger property. Therefore it will never be -1 in your case.And in your second case you're assigning maxIndex to int, which then gives you -1. So try this to clearly understand whats happening. int count = 0; NSUInteger maxIndex = [json[@"images"] count] - 1; for (UIView...

Filter and conditions

mysql,list,condition,exists

you can write your own function CREATE DEFINER=`root`@`localhost` FUNCTION `filter_clients`(InString Varchar(1000)) RETURNS varchar(1000) CHARSET utf8 BEGIN # loop to divide string list by comma # select for each string segment # add result to Outstring.i RETURN OutString; END and call it later with SELECT filter_clients('123456, 1234658, 145678') I wouldn't do...

SQL Repeated Condition in Two Tables

sql,variables,coding-style,condition

you can achieve it like this DECLARE @AccountId int; @AccountID=20; DELETE FROM Table_A WHERE FunctionId IN (Select FunctionId FROM Table_B WHERE [email protected]); DELETE FROM Table_B WHERE [email protected]; ...

How to create a new variable with values from different variables if another variable equals a set value in R?

r,conditional,condition,subset

I was told the problem with my code is that I needed to put indexing on either side. Without the indexing on the right side, it does not know which row to apply the value from. So the correct code in this case would be: df$new[df$date=='a' & !is.na(df$date)] <- df$va[df$date=='a'...

If : (Why is there no value assigned?)

python,variables,if-statement,branch,condition

I tried the following snipped and it worked. Code: word = "PythonWizard" print word begin = int(raw_input("Begin:")) if begin: begin = int(begin) end = int(raw_input("End:")) print "word[", begin,":",end,"] ", print word[begin:end] raw_input("\n\nPress the Enter Key to exit.") Output: ...

PHP - How can regex replace a string by condition

php,regex,replace,condition

Regex: (?s)(?<=\{literal\}).*?(?=\{\/literal\})(*SKIP)(*F)|([{}]) Replacement string: \1\1 DEMO...

R Date not in character list

r,date,condition

You can try running this, without transforming the list to characters: df[!(df$date %in% datestoremove[[1]]),] ...

python 2.7 chained conditions If Else not working. What's wrong?

python,python-2.7,if-statement,condition

elif answer == "yes" or answer == "y": elif answer == "No" or answer == "n": Using elif answer == "yes" or "y": etc.. you are basically checking if bool("n") not comparing if answer is equal to "n" so your statements will always evaluate to True: any non empty string...

Conditional execution of resources

chef,condition,chain

What I would do (warning: this is untested code): node.runstate['my_hook']['retries']=10 webhooks_request "Action 1" do uri "example.net/data1" post_data ({ 'value1' => '1', 'value2' => '2'}) expected_response_codes [ 200, 201 ] action :post notifies :run, "ruby_block[Parse Response]", :immediately end ruby_block "Parse Response" do action :nothing block do #Parse the result from action...

How to swap the lines in a file that match a condition using Shell script

unix,match,condition,swap,lines

Here is a simple Python script which implements what I think you are trying to describe. from sys import stdin keep = "A" kept = [] for line in stdin: line = line.rstrip("\r\n") pattern = line[27:28] # print("## keep %s, pattern %s, %s" % (keep, pattern, line)) if pattern !=...

How to combine Conditions in jOOQ

java,sql,condition,jooq

This was a low-hanging fruit that had been overlooked in the API for quite a while and will be included (finally) in jOOQ 3.6: #3904 In the mean time you'll have to resort to writing your own method: static Condition and(Collection<? extends Condition> conditions) { Condition result = DSL.trueCondition(); for...

Can I assume NULL value in comparison as the false?

c,pointers,comparison,condition,null-pointer

Yes. You can use the macro NULL in this way. It is a null pointer constant which is equal to 0. comp.lang.c FAQ list ยท Question 5.3: When C requires the Boolean value of an expression, a false value is inferred when the expression compares equal to zero, and a...

Create an object upon a certain condition

javascript,constructor,condition

if not valid delete the object Don't. Better, test the email address to be valid before trying to create the user. or return nothing You can't really. Returning nothing from a constructor is effectively quite impossible, except you throw an exception. Use an extra factory function instead: function isValidEmail(str)...

What condition do I have to specify to run installation sequence during install and uninstall too?

installation,windows-installer,condition,installshield,uninstall

The scenario pair of "install and uninstall" is somewhat underspecified, so I would probably go with no condition, or the condition 1. Except you're talking about reboots, which should be avoided whenever possible. One way to limit it slightly is to avoid running the action during maintenance that does not...

How do I create a loop which checks these values? [closed]

java,loops,substring,condition

Check idno % 10000 to get the value of the last four digits. Given that your ID number is stored as an integer: int idno = ...; // some ID number You can use this comparison: if (idno % 10000 >= 5000) { System.out.println("Male"); } else { System.out.println("Female"); } The...

How many conditions can an if check for

java,if-statement,condition

There isn't a limitation to the amounth of conditional statements in an if. Also, there's no performance improvements in either of the two blocks. The biggest difference between the two is that you don't have control over which condition failed with the first one. Example: if(a==1 && b==1) { //do...

Python, appending to a list using conditions

python,list,condition

You could use another variable to keep the value of the last index in A that had a value of 1, and update it when the condition is met: temp = 0 for index, value in enumerate(A): if value == 1: C.append(B[index]) temp = index else: C.append(B[temp]) enumerate() gives you...

What condition is false in a multiple conditions if statement

javascript,if-statement,condition

Since the conditions are mutually exclusive, you can just use an else if without nesting. if (condition1 && condition2 && condition3) { doSomething(); } else if (!condition1) { doWhatIDoWhenC1isFalse(); } // add more else-if conditions as needed If only one of your conditions can be false at a time (or...

Change date format in cakePHP query

sql,datetime,cakephp,condition

$date = `2015-01-24`; $res = $this->RoomBookingData->find( 'first', array( 'conditions' => array( DATE($cond['RoomBookingData.checkin_time']) => $date ), 'order' => 'RoomBookingData.checkin_time DESC' ) ); ...

Grails hibernate create criteria multiple AND OR Conditions

hibernate,gorm,condition,createcriteria

I was able to resolve this with introduction of parenthesis def c = Domain.createCriteria() c.list(max: map.max ?: 10, offset: map.offset ?: 0) { { "colStatus" in status "code" in codes } ( { or { ilike("pCode", pCode) ilike("pDesc", pCode) } } ) ( { or { ilike("eCode", eCode) ilike("eDesc", eCode)...

How to check user entered date is greater than 32 days from current date in java

java,validation,date,condition,jodatime

The universal type DateTime is not suitable for a date-only task. You should therefore choose the type LocalDate in the Joda-Time-library. Then you can use this constructor. Note that you need to specify the timezone because the current date is not the same date all around in the world at...

Regex : conditions in captured variables

regex,perl,expression,condition

Since you want to check line 1 & 2, then 2 & 3, you need to prevent the regex engine from consuming the 2nd line by placing the regex to match the second line in a look-ahead: while ( $data =~ m/(\d+);(Opt|Fab);(.+);(\d{2});(.+);(.+);(.+)\n(?=(\d+);(Opt|Fab);.+;\d{2};.+;(.+);(.+)\n)/g ) { I didn't think too much when...

How to create nested list using special condition in python

python,list,nested,condition

You can apply list on each items: newPlist.append(list(items)) For example, the first list(items) will evaluate to: [['x1', 'y2', 'str_1'], ['x2', 'y2', 'str_1'], ['x3', 'y3', 'str_1']] and so on. Note that since each items is a generator, you will need to remove the printing loop to avoid consuming the generator's content,...

Matlab: using a string as condition for if statement

string,matlab,if-statement,condition

I think this is what you want: cond = 'a==1'; a=1; if eval(cond) b=0; end However, eval is evil. Try not to use it if possible: http://blogs.mathworks.com/loren/2005/12/28/evading-eval/...

Check the conditions every time after function has been called

javascript,function,condition

If I understand it correctly, you want to trigger the change event when you dynamically change the value? Easy. var elem = document.getElementById('productName'); //Do what you need to do to change value. var event = new Event('change'); // Create a new event elem.dispatchEvent(event); // Fire the event on the element....

How to apply If Then to a range of cells using VBA

vba,condition

Dim lastRow As Integer Dim i As Integer 'lastRow is the amount of rows in columns 1 (dynamic) lastRow = Cells(Rows.Count, 1).End(xlUp).Row For i = 1 To lastRow If Cells(i, 1).Value = 1 Then Cells(i, 1).Offset(0, 1).Value = "Comment ONE" ElseIf Cells(i, 1).Value = 2 Then Cells(i, 1).Offset(0, 1).Value =...

MySQL Query with Inner Join and multiple conditions

php,mysql,select,condition

To add the condition "1.) Greater than or Less than an ID (posts.id)", you can just add the condition into the query at the end of the WHERE clause using the AND operator. The condition itself is (using greater than as an example): posts.id > $n where $n is some...

Change condition in LINQ by another condition

c#,linq,condition

Check for the the outcome of condition node.Image.Tag == null being the same as the outcome of treeSelected.Image.Tag == null: radNode = tree.Find(node => node.Level == 0 && ((node.Image.Tag == null) == (treeSelectedNode.Image.Tag == null)) && node.Text.Equals(treeSelectedNode.Text)) Update Addressing @KhanTo's performance concern, in part: Boolean selectedImgTagIsNull = treeSelected.Image.Tag == null;...

Use NOT Equal condition in sql?

sql-server,tsql,condition,where

Your query doesn't really make sense. Grouping happens after WHERE clause, so you're basically getting all orders that have ActivityID ==1 (because if activity Id is 1 there it's always not equal to 4). After WHERE clause is applied you end up with following rows: OrderID ActivityID 1 1 2...

Condition for clicking on canvas shapes?

javascript,canvas,condition

When your turnclicking variable becomes 3+, this part: while (circle = circles[i++]) { context.beginPath(); context.arc(circle.x, circle.y, circle.radius, 0, 2 * Math.PI); if (context.isPointInPath(x, y) && (circle.clicked && (cnt == 0))) { cnt++; console.log("Cnt1: " + cnt); break; } else { alert("You can't go there! " + (circle.clicked && (cnt ==...

Excel: conditional formatting, check if column contains text from other sheet

excel,condition,conditional-formatting

This will do the trick. You will have to fix the cell references to match your sheet. Also make sure you have the order of the rules correctly and stop processing more rules if there is a match. The concatenate adds first and lastname columns in first sheet Sheet2!$a$1:$a$6 is...

What _L1 : _L2: mean? [closed]

java,android,logic,condition

These _L1:, _L2:, etc denote labels. They are essentially markers in your code at which the runtime might decide to shift its execution. For instance, a loop can be defined as: int x = 0 Label1: if (x < 10) { ... x++; goto Label1 } This would be similar...

need help on condition in android

android,if-statement,condition

do you mean that you need to add an if statement in this lines?: catch (Exception e) { Toast.makeText(getApplicationContext(), "SMS faild, please try again.", Toast.LENGTH_LONG).show(); e.printStackTrace(); } Please add the statement where it is not compiling....

Replace the characters in every line of a file, if it match a condition - Unix

unix,replace,sed,match,condition

There is no need to loop through the file with a bash loop. sed alone can handle it: $ sed -r '/^.{14}R.{12}D/s/(.{52}).{4}/\10000/' file 05196220141228R201412241308D201412200055SA1155WE130800001300SL07Y051 05196220141228R201412241308A201412220350SA0731SU1950LAX C00020202020 05196220141228R201412241308D201412200055SA1155WE130800005300SL07Y051 05196220141228N201412241308A201412240007TU0548WE1107MEL C00000000015 07054820141228N201412220850D201412180300TH1400MO085000040300UL180001 This uses the expression sed '/pattern/s/X/Y/' file:...

for each loop: how to step out of conditions

loops,vbscript,condition

Use else as follows: for each file in folder.files if (filename = "foo.bar") then log.writeline("found foo.bar -> delete!") fs.deletefile (folder & file.name), true 'exit for else if (isNumeric(firstPosition)) then if (isNumeric(secondPosition)) then log.writeline("2 numbers seen -> alright!") else log.writeline("Filename is corrupt!") fs.copyFile file, errorFolder, true fs.deleteFile file, true 'exit for...

Wix: Run custom action based on condition

wix,windows-installer,conditional,condition,custom-action

You need to specify the condition inside the Custom element which runs your custom action. (This allows you to run the custom action multiple times in different locations in your sequence and with different conditions each time if desired). Example: <InstallExecuteSequence> <Custom Action="CreateRegistryEntries" After="CostInitialize"> NOT Installed AND NOT PATCH </Custom>...

Classic ASP Vbscript Conditional Statement for Time() not giving correct results

time,vbscript,asp-classic,condition

FormatDateTime() returns a string: >> WScript.Echo TypeName(FormatDateTime("12:00:00 PM")) >> String So your if CurrentDateCurrentTime < startDateStartTime then compares a string starting with "5" to a string starting with "1". You need to compare (variables of sub-type) Date(s)....

How to set the condition in my if statement, if the user has to type in a whole number? C# [closed]

c#,if-statement,condition

Divide it by 1 and if the remainder is 0, it is a whole number: if ((numberofRoses % 1) == 0) { } You can also parse the number as an int using Int32.TryParse(), which would be more effective: int roses = 0; if (int.TryParse(numberofRoses, out roses) { //"roses" is...

if condition always returns true (Java)

java,date,if-statement,condition

You are testing the month field. In case 1 the month is always 1. switch (month) { case 1: //mount = 1 !! if (month == 1 ||... // } ...

Excel adding data based on current data

excel,excel-vba,data,add,condition

This is exactly what vlookup is used for =VLOOKUP(H1, items!A:B,2,FALSE) Put this formula into I1 on the sales sheet and drag it down, if the items sheet is not in the same workbook , you will need to modify the reference to point to it, you could obviously write a...

How to use objects within if statements - Javascript

javascript,arrays,condition

I may be misunderstanding you, but...sounds like you could just use a map? var map = { 1: 'A', 2: 'B', 3: 'C' }; if (map.hasOwnProperty(incomingNum)) { $('div#').html(map[incomingNum)); } ...

Communication between threads in Java without lock

java,multithreading,condition,reentrantlock

(1) await() is usually used in a loop; not doing so is a sign of bug. while( some condition not met ) cond.await(); (2) unlock() should be in a finally block (3) signal() only signals currently waiting threads; the signal is lost if there's no thread waiting. lock.lock(); cond.signal(); //...

How to filter table with conditions stored as parameters in another table?

sql,sql-server,parameters,filter,condition

Not a lot of detail here but something like this? select b.Columns from TableB b join TableA a on a.MaxID <= b.ID where a.FilterType = 1 ...

WIX. How to not reinstall a feature during repair?

wix,condition,reinstall

This works for me: <Feature Id="aFeature" Title="A Features" Level="1"> <ComponentRef Id="aComponent" /> <Condition Level="0"> <![CDATA[REINSTALL<>""]]> </Condition> </Feature> This way during Repair the feature is ignored and not touched, but normally uninstalled ...

How to use AND operator for comparison in javascript?

javascript,html,string,if-statement,condition

Your code, onclick=match() should have quotes (i.e. onclick="match()"), though you'd be better off using the standard of attaching a click event in your javascript. Further, as pointed out by Teemu above, 'popwindow' is not a function unless you have specified it elsewhere in your script. I have a feeling your...

How to order SQL query result on condition?

sql,postgresql,order,condition

Use CASE expression in ORDER BY clause: SELECT category FROM ( SELECT DISTINCT category FROM merchant ) t ORDER BY CASE WHEN category = 'General' THEN 0 ELSE 1 END, category ASC CASE guarantees that rows with General will be sorted first. The second argument orders the rest of the...

Triple Conditioned selection of data in r

r,selection,condition

I post a solution. The trick for this kind of problem is to find an unique identifier, in my case merging the columns example$behavior and example$event_type will provide unique cases, the rest is matter of subsetting and looping. The reproducible example is given in the question. example$beh_eve <- paste(example$behavior,"_",example$event_type,sep="") start<-which(...

What does this if assignment/statement mean in C++

c++,if-statement,condition,variable-assignment,conditional-statements

That's called a ternary operator, and they're kinda weird. They're a shorthand for an if-statement. The format is: condition ? if-true : if-false In this case, the condition is is byte[0] == '0'. If true, temp.byte[0] is set to '1', otherwise temp.byte[0] is set to '0'....