Menu
  • HOME
  • TAGS

Conditional merging of row in R

r,merge,conditional

As lukeA points out, I just forgot about aggregate function that works perfectly in this case. aggregate(label~file, sample, paste, collapse = " ") ...

Conditional with statement in Python

python,conditional,indentation,conditional-statements,with-statement

If you want to avoid duplicating code, you could do something like: class dummy_context_mgr(): def __enter__(self): return None def __exit__(self): return False with get_stuff() if needs_with() else dummy_context_mgr() as gs: # do stuff involving gs or not or make get_stuff() return different things based on needs_with()....

Creating a subset in R using a double loop [closed]

r,loops,double,conditional,subset

Or simply with base R aggregate(Julian_Day ~., df, min) # Year Id Julian_Day # 1 1901 1 40 # 2 1968 1 200 # 3 1901 5 56 Or library(dplyr) df %>% group_by(Id, Year) %>% summarise(Julian_Day = min(Julian_Day)) # Source: local data frame [3 x 3] # Groups: Id #...

Rails 4 validation conditional on value of a hidden field

ruby-on-rails,validation,conditional,hidden-field

You should do <%= f.hidden_field :update_type, :value => "email_only or password_only" %> ...

Looping through array and grouping data based on a criteria in perl [closed]

arrays,perl,loops,conditional,grouping

You can use the following as a start. I assumed, the data parts are split by single spaces, as given in your example and that data is in a file called "data.txt". The result is an array of arrays that contain the elements that are to be grouped together. #!/usr/bin/perl...

Why does (( s )) do a variable lookup, but not [[ s ]]?

linux,bash,shell,conditional

(( )) is a math context; explicit $s aren't needed in a math context (since nothing but numbers are valid there, any token started with a non-numeric character can be assumed to be a variable name -- and will be treated as 0 should that variable be nonexistent/empty), but are...

Adding to variable value on condition in Javascript

javascript,jquery,variables,if-statement,conditional

Only some modifications need to be made in order to get things to work: First one, there's a typo here: if(document.getElementById('leather).checked == true) { You missed a ' so substitute it by: if(document.getElementById('leather').checked == true) { Second, define the var total out of the functions and make it available to...

Conditionally removing duplicate rows from a data frame

r,data.frame,duplicates,conditional

Looks like a job for aggregate(). # Input data frame df <- data.frame(Gene=c("AKT", "MYC", "MYC", "RAS", "RAS", "RAS", "TP53"), Expression=c(3, 2, 6, 1, -4, -1, -3)) # Maximum absolute value of Expression by Gene maxabs <- with(df, aggregate(Expression, list(Gene=Gene), FUN=function(x) max(abs(x)))) # Combine with original data frame df <- merge(df,...

Storing reference (hash?) to the node for conditional manipulation

performance,xslt,conditional

The answer is "Yes". You simply need to change your check3 variable to this: <xsl:variable name="check3" select="$externalFile//i[@attibute = $variable]" /> This way you are referencign the i node in the external file directly, rather than getting the text value of it (which is what xsl:value-of will do)...

Conditional group by join in R

r,join,conditional

Here's a possible solution using data.table rolling joins library(data.table) dt1 <- as.data.table(vecA) ## convert to `data.table` object dt2 <- as.data.table(vecB) ## convert to `data.table` object setkey(dt2) # key in order to perform a binary join res <- dt2[dt1, vecB, roll = -Inf, by = .EACHI] # run the inner join...

ASP.NET MVC: Is there a syntax to acces a project conditional compile symobl in web.config

syntax,compilation,web-config,asp.net-mvc-5,conditional

The .config files are not part of the build, so I am uncertain what you hope to achieve by doing conditions there that can't be done with a config transform. XML is markup - it doesn't contain any behavior by itself. For that, you need a transform engine of some...

change value in numpy array based on presence in another array

python,numpy,conditional

a in b here will always be False, but you can use np.in1d to remove by value: >>> np.in1d(a,b) array([False, False, False, False, False, True, True, True, False, False], dtype=bool) >>> a[np.in1d(a,b)] = 0 >>> a array([0, 1, 2, 3, 4, 0, 0, 0, 8, 9]) Or where, if you...

PHP Database Query: How to return the results from a while loop to a Javascript Variable?

javascript,php,mysql,conditional

If you want to output the PHP variable in a JavaScript variable you could do something like this - echo '<script>var name+' . $row['pkid'] . ' = ' .$row['fname'] . ';</script>'; This would give you a uniquely named variable for each row....

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'] =...

SQL Conditional aggregation

sql,oracle,conditional,aggregation

The determination of whether the number should be treated as positive or negative needs to happen inside of your aggregation SUM(). So: select sum(case when type = 1 OR type = 2 then value else - value end) from table t group by year; Because both 1 and 2 are...

How do I properly use conditonal execution to draw a circle based on input?

javascript,html,colors,conditional,execution

Take a look at this Jsfiddle. You need to define your fields as input type="number". Then read the input, calculate them and based on what the result is, pass a different color string to your animate function, which now takes a parameter color. You also need to really learn to...

Elastic Search : General and conditional filters

elasticsearch,conditional,apply,exists

Try this { "query": { "filtered": { "query": { "match_all": {} }, "filter": { "bool": { "must": [ { "range": { "date": { "from": "2015-06-01", "to": "2015-06-30" } } }, { "bool": { "should": [ { "missing": { "field": "groups" } }, { "bool": { "must": { "term": { "groups.sex":...

Passing JSP Parameters, then checking if they exist

java,jsp,parameters,conditional,parameter-passing

Is that all you have in your include.jsp file? If yes, then add this to the top of the file: <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> The jsp prefix is predefined but JSTL's c prefix is not. Your server might not recognize <c:if>s as server side tags (because of the missing...

Conditionals operation helps in php

php,if-statement,conditional

First of all this the if elseif statement syntax. if($condition1){ // code if the first condition is true }elseif($condition2){ // code if the first condition is false and the second one is true }else{ // code if both the first and second condition are false } it is described in...

Conditional query in ElasticSearch?

elasticsearch,conditional

A thousand tanks to @Andrei Stefan. The difference between update 2 is I had to delete "Mail" from the first "should" query. { "query": { "filtered": { "query": { "match_all": [] }, "filter": { "bool": { "should": [ { "terms": { "type": [ "Video" ] } }, { "bool": {...

Deleting rows in R conditionally

r,conditional,delete-row

Try aggregate(Number~ID, df1, FUN=min) Or library(data.table) setDT(df1)[, list(Number=min(Number)), by = ID] Or from @David Arenburgs' comments unique(setorder(setDT(df1), Number), by = "ID") Or library(dplyr) df1 %>% group_by(ID) %>% summarise(Number= min(Number)) Or library(sqldf) sqldf('select ID, min(Number) as Number from df1 group by ID') Update If there are multiple columns and you want...

Join statement with condition in sql

sql,join,conditional

Sounds fairly straightforward, since they're both numbers. Since you're using an inner join, you can either put the criteria in the join: SELECT * FROM [ChileCSVimports].[dbo].[tLocation] a JOIN AIRGeography..tGeography b ON a.GeographySID = b.GeographySID AND ABS(a.Latitude - b.Latitude) < 0.0002 AND ABS(a.Longitude - b.Longitude) < 0.0002 ... or in a...

Macro for run-once conditioning

c,if-statement,macros,conditional

I guess you're saying you want the macro to somehow automatically track which bit of your bitmask contains the flag for the current test. You could do it like this: #define CHECKSUM(d) static d checksum_boolean; \ d checksum_mask #define CHECKSUM_START do { checksum_mask = 1; } while (0) #define CHECKSUM_IF...

Using Razor Syntax within JavaScript Conditional Statment

javascript,c#,asp.net-mvc,razor,conditional

If the property isbool, you can check in razor if condition following way: <script type="text/javascript"> @if (Model.SomeCondition){ @:Do Something(); } </script> or: <script type="text/javascript"> @if (Model.SomeCondition){ <text> Do Something(); </text> } </script> ...

Python AND OR statements

python,if-statement,conditional

Unless the output from the first line of code is "ar" or "fr" (or something else not in the if-elif conditions), you are over-writing the opt variable. Consider re-naming the 'new' opt to something else, like follows: opt = child.get('desc') extent = child.get('extent') if opt == 'es': opt2 = "ESP:"...

Wordpress Multisite Conditionals?

php,wordpress,conditional,multisite

Behind the scenes in WordPress multi-site, each "site" is actually called a "blog" (the "site" is the overall network.) Each of your different blogs will have a different ID. You can fetch the ID using get_current_blog_id. To make the code easier to read, though, I'd probably use get_blog_details, which returns...

Conditional statement produces unwanted action in Android App

java,android,if-statement,conditional

Change: if(p1 == p2 || p1 == p3 || p1 == p4){ Toast.makeText(getApplicationContext(), p1 + " It's a tie.", Toast.LENGTH_SHORT).show(); }else{ Toast.makeText(getApplicationContext(), p1 + " You chose the winner!", Toast.LENGTH_SHORT).show(); } to if(p1 > p2 && p1 > p3 && p1 > p4){ Toast.makeText(getApplicationContext(), p1 + " You chose the...

Keep the second occurrence in a column in R

r,conditional,subset,find-occurrences

Here's another possible data.table solution library(data.table) setDT(df1)[, list(Value = c("uncensored", "censored"), Time = c(Time[match("uncensored", Value)], Time[(.N - match("uncensored", rev(Value))) + 2L])), by = ID] # ID Value Time # 1: 1 uncensored 3 # 2: 1 censored 5 # 3: 2 uncensored 2 # 4: 2 censored 5 Or similarly,...

Racket/Scheme: How to avoid repeating function call in cond

scheme,conditional,racket

The correct solution is to use cond's => form: (cond ((regexp-match #rx"start" "startofstring") => (lambda (match) (set! lst (cons match lst)))) ...) (Note that I renamed your list variable to lst to avoid shadowing the built-in list procedure.) If you have many patterns, and the same action for multiple patterns,...

swift conditional function return

ios,function,swift,return,conditional

To explain @MidhunMP's answer, right now your code is able to end without any return value. For example look at this code, which is similar to yours: func myFunc() -> Int { let myNumber = random() % 3 if myNumber == 0 { return 0 } else if myNumber ==...

ActiveRecord conditional order clause

activerecord,order,conditional

I ended up with the following (plain SQL, not yet translated to AR): SELECT * FROM tasks ORDER BY due_at <= Now() DESC, CASE due_at <= Now() WHEN true THEN priority END ASC, CASE due_at <= Now() WHEN true THEN due_at END ASC, CASE due_at <= Now() WHEN false THEN...

How to set a conditional based on multiple models?

ruby-on-rails,ruby,model-view-controller,notifications,conditional

First of all, according with MVC, you shouldn't make SQL queries in the view's: <% if Comment.find_by(notification.comment_id) == Habit.find(params[:habit_id]) %> bad practice! You should make the Query in the controller and then using the instance variable of the controller(the variable with the @) in the view. Second, params[:habit_id] will only...

C# conditional statements in menuitem in asp.net

c#,asp.net,conditional,menuitem

I personally do not like mixing C# code in mark up. It is really fragile. Instead, you can create entire menu from code-behind in your scenario. ASPX <asp:Menu ID="MyMenu" runat="server" DynamichorizonalOffset="2" ForeColor="#000E8F" StaticSubMenuIndent="10px" Width="50%" CssClass="verticalmenu" Font-Size="11pt" OnMenuItemClick="MyMenu_MenuItemClick"> <DynamicMenuStyle CssClass="IE8Fix" VerticalPadding="2px" /> <DynamicMenuItemStyle CssClass="horizonalmenu" VerticalPadding="5px" /> <StaticMenuItemStyle...

fill values of a column with values from another column (but not on the same row), conditionally, in R

r,loops,conditional

With plyr, supposing you only have 2 lines per id: df = data.frame(id=12:15, fight_id=c(1,1,2,2), v3=c(1,0,0,1)) # id fight_id v3 #1 12 1 1 #2 13 1 0 #3 14 2 0 #4 15 2 1 library(plyr) ldply(split(df, df$fight_id), function(u) transform(u, opp=rev(u$id))) # .id id fight_id v3 opp #1 1 12...

Rails validations if condition

ruby-on-rails,ruby-on-rails-4,conditional

You can do this validate :biggerThan, if: Proc.new{ |test| test.firstvalue.present? and test.secondvalue.present? } It would be good if you add numericality validations also validates :firstvalue, numericality: true validates :secondvalue, numericality: true ...

MySQL Conditional Left Join With Default

mysql,left-join,conditional

SqlFiddle Demo select * from client, preference where preference.clientID in (select MAX(preference.ClientID) from preference where preference.ClientID = client.ClientID OR preference.ClientID = 0) or select client.name, MAX(preference.ClientID) from client left join preference on preference.ClientID = client.ClientID OR preference.ClientID = 0 group by client.name ...

How to set font-weight of a column text to bold based on another column value in Telerik Grid

telerik,formatting,conditional,client-templates

I modified my code to the following with help from the post: Telerik MVC Grid making a Column Red Color based on Other Column Value .Columns(columns => {columns.Bound(d => d.IsTrue).Width(0); columns.Bound(d => d.Name).Title("Name).Width(200).HtmlAttributes(new { style = "font-weight:normal;" }); }).CellAction(cell => { if (cell.Column.Title == "Name"){ var item = cell.DataItem; if(item.IsTrue)...

How to use contional statements with Java scanner

java,conditional

To do || you can do String line = scanner.nextLine(); if (line.equals(x) || line.equals(a)) { The && doesn't make sense unless x.equals(a) in which case you can compare it with x...

highlight “partial” duplicates across entire sheet in Google Sheets using conditional formatting

formatting,duplicates,conditional,highlight,partial

Thanks to a genius over at the Google Product Support Forums named Isai Alvarado I finally have the solution... =if(C2<>"",ArrayFormula(countif(left($C$2:$Z$18,4),left(C2,4)))>1) I hope this helps anyone else trying to highlight partial duplicates across multiple columns. ...

Polling an API for JSON until a specific key is found

jquery,ajax,asynchronous,conditional

I figured it out, with help from How to call a function within $(document).ready from outside it function getResults() { $.ajax( { url: "/api/v1/analysis/{{jobID}}", dataType: 'json', error: function(data) { // Do nothing / Terminate this function }, success: function(data) { if (data.status == 'queued') { // Wait 1.5 seconds and...

Chance of a conditional occurring in Swift: Xcode

xcode,swift,if-statement,conditional,percentage

You can use arc4random_uniform to create a read only computed property to generate a random number and return a boolean value based on its result. If the number generated it is equal to 1 it will return true, if it is equal to 0 it will return false. Combined with...

Thymeleaf compare #locale expression object with string

conditional,locale,thymeleaf,spring-el

This is a issue that I told to the guys of thymeleaf time ago. You need to resolve first the #locale before comparing it with "en". You can do that adding 2 underscore at the beggining and end to the expresion that you want to resolve first. In your case...

Is There Anything Like a Templatized Case-Statement

c++,templates,conditional,case-statement,nested-if

I had to do something like this once so I wrote a small wrapper to acheive the result neatly. You could use it as follows (see here for a test) template<class T> typename static_switch<sizeof(T) ,int // default case ,static_case<sizeof(char),char> ,static_case<sizeof(short),short> ,static_case<sizeof(long),long> >::type foo(T bar){ ... } Behind the scenes it...

How to write a conditional on two variables (columns) in Pandas

python,pandas,conditional

You can consider using nested np.where() conditions for if Logins == 0 & Card > 0, then 0, if Logins > 0 and Card == 0, then 1, else NaN. In [81]: np.where(((sample['Logins']==0) & (sample['Card']>0)), 0, np.where(((sample['Logins']>0) & (sample['Card']==0)), 1, pd.np.nan)) Out[81]: array([ nan, nan, nan, nan, nan, nan, 0.])...

C Program - Basic Calculator

c,while-loop,char,conditional

You need to consume the trailling newline, enter remains in the stdin buffer ready to be read by the next scanf. Change scanf("%c", &yes); to scanf(" %c", &yes); ...

google adsense conditional in wordpress

wordpress,conditional

Assuming you want to hide the Adsense block on page ID 29460, Page ID 32349, the 404 page and the preview, you should use && instead of ||: <?php if ( !is_page(array('29460', '32349')) && !is_404() && !is_preview() ) :?> //GOOGLE ADSENSE CODE BLOCK <?php endif;?> ...

Conditional subtraction Part 2

r,conditional,multiplication

We paste the 'Channel' and substring of 'Hour' column together ('nm1'), concatenate the 'TV1Slope' and 'TV5Slope' vectors ('TV15'), match the 'nm1 vector with names of 'TV15' after removing the 'Slope' substring with sub, and get the corresponding 'TV15' value. Subset the columns with names starting with 'cols' using grep, do...

Replace an entry in a pandas DataFrame using a conditional statement

python,pandas,conditional

Use np.where to set your data based on a simple boolean criteria: In [3]: df = pd.DataFrame({'uld':np.random.randn(10)}) df Out[3]: uld 0 0.939662 1 -0.009132 2 -0.209096 3 -0.502926 4 0.587249 5 0.375806 6 -0.140995 7 0.002854 8 -0.875326 9 0.148876 In [4]: df['uld'] = np.where(df['uld'] > 0, 1, 0) df...

Show text for post with specific date and specific category in Wordpress

php,wordpress,date,conditional

Check the below code . Here I had used category 'Uncategorized' .you can use your tag there. hope this will help. add this code in your functions.php add_filter( 'the_content', 'check_cat_date' ); function check_cat_date($content){ $date = '2015-06-01'; $pub_Date =the_date( 'Y-m-d', '' ,'', $echo=false ); $pub_Date = (string)$pub_Date; $posted_date = strtotime($pub_Date); $flag_date...

Bash conditional statement

bash,conditional

You are missing a semicolon or a line jump before the then keyword. Beware also that Bash uses > to compare strings, not numbers. For numeric comparison you should be using either -gt or the Bash specific (( arithmetic expression evaluator. For instance: #!/bin/bash MAX=35000000000 if (( $(du -sb ~/MEGA...

Selecting rows which have a similar value for a particular column which occurs n times each month

mysql,date,select,conditional

You're trying to group your rows into months. The best way to do this is to start with an expression that will take any date and convert it to the first day of the month in which it occurs. That expression is. DATE(DATE_FORMAT(dates, '%Y-%m-01')) Next, you use this expression in...

Reguralexpresion which accepts valid float numbers [PHP]

php,regex,preg-match,conditional

All you need is play with capture grouping .You can use the following regex : ^(([1-9]+|0|[1-9]+?0)([.,][0-9]{0,4})?)$ Demo Also note that [^0] is an incorrect regex because it will match everything except 0 so it will match characters or ......

Conditional Order by multiple columns Mysql

mysql,sql-order-by,conditional

I tried using CASE but it didn't work as per my liking, got a simpler solution to work. Select * from mytable order by Condition1 Desc, condition2 desc, condition3 desc ...

Conditionally comment html script statement across mulitple websites

html,regex,bash,scripting,conditional

You could do this with Perl (where the script you want to comment has stuff in it): $ cat test.xml <html> <script> stuff </script> <script> other things </script> <body> <h1>Hello, world!</h1> </body> </html> $ perl -0pe 's/<script([^>]*>.*?stuff.*?)<\/script>/<!-- script\1<\/script -->/smg' test.xml <html> <!-- script> stuff </script --> <script> other things </script>...

C++ nested conditional operator order of evaluation

c++,order,conditional,operator-keyword,evaluation

n3376 5.16/1 Conditional expressions group right-to-left. The first expression is contextually converted to bool (Clause 4). It is evaluated and if it is true, the result of the conditional expression is the value of the second expression, otherwise that of the third expression. Only one of the second and third...

Create a Triangular Matrix from a Vector performing sequential operations

r,for-loop,matrix,vector,conditional

Using sapply and ifelse : sapply(head(vv[vv>0],-1),function(y)ifelse(vv-y>0,vv-y,NA)) You loop over the positive values (you should also remove the last element), then you extract each value from the original vector. I used ifelse to replace negative values. # [,1] [,2] [,3] [,4] [,5] # [1,] NA NA NA NA NA # [2,]...

Conditional Order of Operations in C#

c#,python,order,conditional

It is the order of precedence. In fact many languages have such rules implemented not just python. The one that you are looking for can be found in Microsoft MSDN Here is the link Operators are listed in descending order of precedence. If several operators appear on the same line...

Kendo ui grid if else condition

javascript,if-statement,kendo-grid,conditional

You can handle it in grid databound event too.Check this fiddle: http://jsfiddle.net/Sowjanya51/krszen9a/ You can modify the databound instead of looping through all the cell collection if(dataItem.OrderType == 'OrderType20') ...

Conditional copying (nonempty text field) with a variable range

vba,variables,range,conditional,copying

You may need to change where it is being pasted in the Schedule sheet as I do not know where ActiveCell is... but this should do the job. Dim lngRowSearch As Long lngRowSearch = 3 With Sheets("Add") Do lngRowSearch = lngRowSearch + 1 Loop Until .Cells(lngRowSearch + 1, 3) =...

Create conditional for COUNT

sql-server,count,conditional,having

you can use case statement to return the correct label, SELECT ColumnaA, case when count(*) > 5 then '>5' else cast(count(*) as varchar(4)) end as visits from tableA group by ColumnA order by ColumnA ...

how to limit users to only one comment and rating per Item?

javascript,angularjs,conditional

Mongoose/mongo makes this super easy to do. All you would need to do is something like this in your server side route for creating comments. Comment.findOne({userId : request.auth.credentials._id}, function(err,data) { if (err) { // If err (doesn't find a comment made by that user) // Then create one } else...

Change each list item background color conditionally JQuery Mobile

javascript,jquery,listview,jquery-mobile,conditional

You can create CSS classes for each of the background colors e.g.: .vegano { background-color: #ABDD87 !important; } .dudoso { background-color: #F5CB98 !important; } .novegano { background-color: #F47D75 !important; } Then in the script when you are iterating the data, add the appropriate class to the anchor within the LI...

C compound conditional not working as expected (value mysteriously reassigned to other value) - possible gcc bug

c,conditional

I re-wrote your expression with indenting and comments so that it can be traced. t-(t^14)==2? /*True */ db,t=1 /*else */ : /*False*/ t==1? /*True */ db,t=41 /*else */ : /*False*/ t==41? /*True */ db,t=0 /*else */ : /*False*/ t==0? /*True */ exit(0) /*else */ : /*False*/ 0; Now a trace-through:...

Gnuplot: Conditional splot of a function

conditional,gnuplot

This is not a 3-dimensional plot because you only have one independent variable. The value of y is fixed by x+y-1=0. Therefore, you have to plot f(x,y)=exp(-(x**2+y**2)) evaluated at f(x,1-x): f(x,y)=exp(-(x**2+y**2)) plot f(x,1-x) w l Now, of course the above graph is the projection of your curve onto the XZ...

Cassandra CQL3 conditional insert/update

cassandra,nosql,conditional,updates,cql3

What version of cassandra are you running? Support for non-equal conditions with LWTs was added in 2.1.1 via CASSANDRA-6839: cqlsh:test> UPDATE events SET first_occurrence = 123456 WHERE event_name='some_event' IF first_occurrence > 1; [applied] ----------- True ...

ssrs iif conditional sum based on dense rank

reporting-services,sum,expression,conditional,aggregation

Assuming Fields!Dense_Rank.Value refers to a column in your dataset called Dense_Rank (naming fields after t-sql functions is not generally advised, as this may lead to confusion), I think what you are trying to achieve is the following: =sum( IIF ( (Fields!Dense_Rank.Value=1 Or Fields!Dense_Rank.Value Is Nothing), Fields!TotalCalls.Value, 0 ) ) ...

change color on recordset return using php [closed]

php,html,mysql,colors,conditional

Might be this way can help.... CSS .complete { background: green; } .pending { background: orange; } php $status_class =""; if($row_Recordset1['status'] == "complete"){ $status_class = "complete"; }else if($row_Recordset1['status'] == "pending"){ $status_class = "pending"; } HTML <td class='<?=$status_class;?>'><?php echo $row_Recordset1['status']; ?> </td> ...

Returning a value from a function within a for-loop

javascript,function,loops,dom,conditional

You need to A set numbers in the loop and you need to B return container from your function, for (var i = 50, numbers = ""; i < limit; i += 50) { numbers = insertVal(i, numbers); // A } document.getElementsByClassName("width")[0].innerHTML = numbers; function insertVal(i, container) { if (i...

Compare multiple values in one condition [duplicate]

c#,variables,if-statement,conditional

You can create an usefull extension function: public static bool EqualsAll<T>(this T val, params T[] values) { return values.All(v => v.Equals(val)); } call it like: bool res = 123.EqualsAll(int1,int2,int3); ...

Excel SUMIFS with OR, IF, and multiple criteria

excel,syntax,conditional,sumifs

You will be better off creating an extra column with a formula containing all the logic and simply returning 1 or 0, then using that as the basis of the SUM. Something like: =IF(OR(freq = "monthly" , AND(freq = "annually", mod = true) , AND(freq = "other", mod = true),...

.NET use IIF to assign value to different variables

.net,vb.net,conditional,variable-assignment,iif

What you're asking to do would have been possible in a language that supports pointer types (such as C/C++, or C# in unsafe mode) with dereferencing; VB.NET doesn't do that. The best you got to leverage is local variables, reference types, and (perhaps) ByRef. If it's a Class, its instantiation...

Javascript var === 2 && console.log('true'). How does this work?

javascript,conditional

This (mis)uses the boolean handling of JavaScript; because of the lazy evaluation of expressions, console.log('true') is only run, when someVar === 2 was previously evaluated as true. This behaviour is called Short-circuit evaluation. Other use-cases By the way, this type of coding has legit use cases. My favourite is the...

C - preprocessors multiple macros

c,gcc,macros,conditional,preprocessor-directive

You can use this syntax: #if defined(PLOT) || defined(GRAPH) ...

ng-repeat except value 2

angularjs,conditional,ng-repeat

use ngIf because the ngIf differs from ngShow and ngHide in that ngIf completely removes and recreates the element in the DOM rather than changing its visibility via the display css property. <div ng-repeat="element in data.arrayElement" ng-if="element.val !== 2"> ...

Searching python lists with loops and conditionals

python,python-2.7,loops,conditional

It is difficult to understand your desired output, but this is my best guess: In [39]: a = [1,1,3,4,4,6] b = [20150602, 20150603, 20150604, 20150605, 20150606, 20150607] c = zip(a, b) print c for i in range(0, len(c)-1): if c[i][0] == c[i+1][0] and c[i+1][1] - c[i][1] <= 3: print c[i]...

One liner conditional, multiple variables and check that all of them are not false?

python,if-statement,conditional,conditional-statements

Use a simple generator expression and all(): if all(d.get(k) for k in keys): Example: keys = ['proxy_host', 'proxy_port', 'proxy_protocol'] if all(settings.get(k) for k in keys): print("Settings good!") else: print("Missing setting!") ...

can cljc single-file macro definitions to work with clojurescript?

clojure,macros,conditional,clojurescript,reader

Yes, there is a way for a single file construction. (ns cljc.core #?(:cljs (:require-macros [cljc.core :refer [list-macro]]))) #?(:clj (defmacro list-macro [x y] ;; ... Assumedly one of the next CLJS compiler versions will do the import automatically....

How to check nextInt from Scanner without consuming the int itself

java,conditional,java.util.scanner

I believe that you do need the input.next() call despite what Vivin says. If you can't read an integer from the next line of stdin then you will end up in an infinite loop. Furthermore, you should handle the case where you run out of lines of stdin to process,...

Why can't I replace if statement with conditional operator (?:)?

java,if-statement,conditional,ternary-operator

The syntax is: condition ? value1 : value2; not condition ? statement1 : statement2; What you mean is: preferredClass = (preferredClass == PlaneClass.FIRST_CLASS ? PlaneClass.ECONOMY_CLASS : PlaneClass.FIRST_CLASS); ...

Conditional Logic for links in ACF

php,wordpress,if-statement,conditional,acf

You should use get_sub_field() to determine whether or not a link exists, and then use a conditional. Something like: <div class="small-12 columns"> <h2>Show Information</h2> <?php if( have_rows('show_information') ): ?> <?php while( have_rows('show_information') ): the_row(); ?> <p> <?php if ( get_sub_field('show_link') ) { echo '<a href="' . get_sub_field('show_link') . get_sub_field('show_pdf') ....

conditional Operator ? : type evaluation

java,conditional

Java only allows assignments and calls where a statement is expected, not arbitrary expressions. From section 14.8 of the JLS: Certain kinds of expressions may be used as statements by following them with semicolons: ExpressionStatement: StatementExpression ; StatementExpression: Assignment PreIncrementExpression PreDecrementExpression PostIncrementExpression PostDecrementExpression MethodInvocation ClassInstanceCreationExpression The ternary operator (ConditionalExpression) is...

Java and and or operator not working

java,operators,conditional

wrap them in parentheses if ( (uAnswer1.equals(answerB1) || uAnswer1.equals(answerB2) || uAnswer1.equals(answerB3)|| uAnswer1.equals(answerB4)) && (uAnswer2.equals(answerS1)|| uAnswer2.equals(answerS2)) ) or even make a HashSet of correct answers and do this will be clean and will be efficient too answers1Set.contains(uAnswer1) && answers2Set.contains(uAnswer2) ...

Boo Language Calculation on Web Drop Down List

if-statement,conditional,boo

A few pointers: It appears that for both pairs, the is?????Hidden and corresponding is?????Mandatory will always be opposite values. If so, you don't need two separate boolean variables to track them. If you're going to end up with a lot of blocks that look basically like this one, the proper...

Combining two for-loops that share similar properties

javascript,loops,dom,conditional

This produce the same result document.addEventListener("DOMContentLoaded", function() { var horizontal = document.getElementsByClassName("rule--horizontal")[0], vertical = document.getElementsByClassName("rule--vertical")[0]; var a = screen.width > screen.height ? screen.width : screen.height; for (var i = 50; i < a; i+= 50) { if (i % 100 === 0) { if(i < screen.width)horizontal.innerHTML += "<span class='num num--visible'>"...

Exclude subsequent duplicated rows

r,conditional,duplicate-data

rle() is a nice function that identifies runs of identical values, but it can be kind of a pain to wrestle it's output into a usable form. Here's a relatively painless incantation that works in your case. df[sequence(rle(df$VALUE)$lengths) == 1, ] # NAME VALUE # 1 Prb1 0.05 # 4...

How to unnest a nested cell array?

arrays,matlab,conditional,cell

First, you should never call a variable cell, since it is the name of a built-in Matlab function. This is bad, you should be punished for this :-) Let's say you have replaced all cell's by C. Then, you should initially define C by C = cell(0,3); and replace all...

Settings global conditional variables in Go

variables,go,conditional

I'm not sure what problem you had, your code from the OP is valid, also you can have it in one line like: var myvarbool, _ = strconv.ParseBool(os.Getenv("MYVAR")) playground...

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>...

change the state of a textbox depending on which view is called

textbox,asp.net-mvc-5,conditional,enable-if

Try to add something like this in your tag: @('Condition Here') ? disabled:"disabled" : "" Or: object mode = ('Condition Here') ? null : new {disabled = "disabled" }; @Html.TextBoxFor(x => x.YourPropertyHere, mode) ...

(Excel) Conditional Formatting based on Adjacent Cell Value

excel,formatting,conditional

You need to take out the $ signs before the row numbers in the formula....and the row number used in the formula should correspond to the first row of data, so if you are applying this to the ("applies to") range $B$2:$B$5 it must be this formula =$B2>$C2 by using...

DELETE FROM Table WHERE 'RANK' > 1

sql,sql-server,delete,conditional,rank

From the looks of it, you want to delete duplicate entries for Name and Product leaving the newest one. You can simplify your query with this: SELECT *, RN = ROW_NUMBER() OVER(PARTITION BY Name, Product ORDER BY [Date] DESC) FROM Config You can then put it in a CTE and...

MATLAB find array element and conditionally add to a constant

arrays,matlab,conditional,addition

The behaviour you are looking for is called (phase) unwrapping and there's a built in function unwrap for that res = unwrap(angles / 90 * pi) / pi * 90 Note that unwrap works in radians and for jumps of +/-pi and not 2*pi as you request, hence I'm intentionally...