w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Check a condition before each line of code without multiple IF statements?
No - the condition will be checked once and then the entire block executed. Another option might be to inject bailouts in the block: if (condition) { DoSomething(); if(!condition) return; DoSomethingElse(); if(!condition) return; DoAnotherThing(); } Another way is if the functions could be parameterized so that you could put them in a loop: foreach (varmyParam in parameters) { if(condition) DoSomething(myParam); } Edit After thinking a bit more this may be your best option: List<Action> funcs = new List<Action> {DoSomething, DoSomethingElse, DoAnotherThing}; foreach( Action a in funcs) { if(condition) a(); } That requires that all of the methods have the same signature (in your case return void with no parameters) but it's a bit clea

Categories : C#

PHP SQL, Getting a multiple data from multiple table with multiple condition in PHP
Make a condition for job_taker and users like job_taker.user_id=users.user_id Query, $data_query ="SELECT users.user_name, jobs.job_code, jobs.job_desc, jobs.job_client, jobs.job_year, jobs.job_month, jobs.job_category, job_taker.job_hours FROM jobs,job_taker,users WHERE jobs.job_id = job_taker.job_id AND users.user_id ='$uid' AND job_taker.user_id=users.user_id ORDER BY 'login.jobs.job_id' DESC";

Categories : PHP

IF condition not met but code still being triggered
This logic will never be true: if(orderFileCreationStatus.SpecialMeasureFileStatus != orderFileCreationStatus.SpecialMeasureFileStatus) You're comparing the value type to itself, which will always be true, and then negating that true to false at all times.

Categories : C#

How it can be a race condition. Or it is something wrong with my code
newsocket_fd may be modified (or worse, destroyed and re-created) before the new thread reads it from the pointer you gave it. This is definitely a race condition. The easiest fix is simply not sharing the same variable between threads. If you absolutely must do it for some reason or other, then you must ensure it won't be modified before the thread is done reading it, using some synchronization object (condition).

Categories : C++

Why is this code not causing a race condition?
The answer is in the question itself. It's a race condition : You can't guarantee that it will ever occur no matter HOW many times threads you try to throw at it or times you try to run it. That's why it's a race condition. It's non-deterministic Assuming uniform probability distribution for this isn't even remotely correct unless you can show why. You aren't flipping a coin here. The code could run for months before the race is exposed, I've seen this very thing happen many times. That's why race conditions are hard to solve and important to prevent. Secondly you aren't seeding any amount of random noise into the scenario. If you say had each thread's run function sleep a random amount of time first so that they actually were likely to coincide with one another this would be more inte

Categories : Java

c# code to fire a keyevent when the condition is true.
In order to put "A" into the NotePad you can do Find out NotePad Edit Window (assuming notepad.exe is executing) Send WM_CHAR message to the window found The code can be like that Required Native API declarations: internal delegate Boolean EnumerationCallback(IntPtr handle, IntPtr parameter); [DllImport("User32.dll", CallingConvention = CallingConvention.Winapi, EntryPoint = "EnumWindows", CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern Boolean EnumWindows(EnumerationCallback lpEnumFunc, IntPtr lParam); [DllImport("User32.dll", CallingConvention = CallingConvention.Winapi, EntryPoint = "EnumChildWindows", CharSet

Categories : C#

Adding a condition/filter to this LINQ to XML code
If the conditions are limited to equal. Dictionary<string, string> conditions = new Dictionary<string, string> { { "name", "John" } }; XDocument document = XDocument.Load(new StringReader(xmlString)); var booms = from boomElement in document.Descendants("boom") where conditions.All(condition => (string)boomElement.Element(condition.Key) == condition.Value) // Where is used to filter the result let boomChildren = (from boomElementChild in boomElement.Elements() select String.Format("{0}: {1}", boomElementChild.Name.LocalName, boomElementChild.Value)) select String.Join(Environment.NewLine, boomChildre

Categories : C#

If condition not working in HTML page with C# code
You need to start with @... @foreach (Message userMessage in UserMessages) { and... @if(userMessage.Message.MessageText.Length <= 10) { Without it at the start, the if( is still treated as HTML. The @ symbol identifies the start of your Razor syntax (i.e. C# code) and will continue to be a razor code block until an appropriate terminator has been reached. There are a number of ways to move it back to HTML, the one most commonly seen in your example is to include a html tag, such as <td>. Here is the complete version of your code, hopefully it will help you understand how it should work: <table> //due to the table tag, we are current inside HTML //so we need to use the @ symbol to move back to razor syntax @foreach (Message userMessage in UserMessages) {

Categories : C#

c# code to fire a key generation when condition is true
SendKeys can be used to send a keystroke to the active application: SendKeys.Send("{F6}"); Note, though, that this should only be used as a last resort, if there is no other way to remotely control another application. Direct interfaces (e.g. COM automation) are usually more reliable and robust.

Categories : C#

How do you combine a multiple condition
This is a job for an 'or' statement: if( !$.trim( $('#name').html() ).length || !$.trim( $('#date').html() ).length ) { $("#lastUpdate").css('display', 'none'); } Although you can probably eliminate the .length part, since empty strings evaluate to false when converted to Boolean: if ( !$.trim( $('#name').html() ) || !$.trim( $('#date').html() ) ) { $("#lastUpdate").css('display', 'none'); }

Categories : Jquery

Doctrine multiple where condition
For first one change your where clause like, ->where('e.id IN (:ids)') ->setParameter('ids', $ids) Where $ids = array('10','100',''); And to use and condition for your second query it should be something like, $qry = $this->manager()->create() ->select('e') ->from($this->entity, 'e') ->where('e.source_id = :id') ->andWhere('source_name=?', 'test') ->andWhere('source_val=?', '30')

Categories : PHP

LINQ multiple and or condition
You got a small typo: you used the single equals (=, used for assignment) instead of the double equals (==, equality). Here's the fix: d.DecommissionDate == Convert.ToDateTime("1900-01-01")

Categories : C#

skipping if statement if condition met and continue executing the code below php
I typically set some sort of marker, such as: <?php if (i>4) { //if this condition met skip other if statements and move on $skip=1; } if (i>7 && !$skip) { //skip this ?> <?php move here and execute the code ?>

Categories : PHP

Why this code become an infinite loop without using lambda as condition parameter
In the last code sample, a<3 is evaluated when the line calling my_while is run. As a has just been set to 0 in the line before, a<3 evaluates to true (0 being less than 3). This means that inside my_while, cond is set to true. It continues to be true because a<3 is never reevaluated, even though a is changed. Thus the while loop keeps looping. Using the lambda and .calling it on every iteration of the loop ensure that the condition a<3 is evaluated for each loop, allowing the while loop to stop when a<3 no longer evaluates to true.

Categories : Ruby

Code skips the loop even though the condition evaluates to true
You have return ans inside your loop. So at that point the function will exit, and the print will never be reached. If ans is really -13.2119 then it does enter the loop, it just doesn't perform everything in it because of the return. Even if you remove the return ans line inside the loop, there is also return x_01 at its end. So in that case the loop will run at most once, which will make it the same as an if statement.

Categories : Python

Is there any sane way to watch for a condition when debugging Perl code?
I don't believe there is anything built into the debugger that will do this but I rolled my own tied scalar class and set a breakpoint on the "ScalarSnoop::STORE" subroutine. Here's the class: package ScalarSnoop; use strict; use base qw(Tie::Scalar); sub TIESCALAR { my $class = shift; my $value = shift; return bless $value, $class; } sub FETCH { my $self = shift; return $$self; } sub STORE { my $self = shift; my $newvalue = shift; $$self = $newvalue; } 1; And here is a script that uses it: #!/usr/bin/env perl use v5.14.0; use strict; use warnings; use lib qw(.); use ScalarSnoop; my ($first, $second, $third); tie $second, 'ScalarSnoop'; $first = 'hey'; $second = 'there'; $third = 'dude'; # Changing the iterator variable changes the original since # it is an

Categories : Perl

Java compiler code optimization breaches if condition?
I'm not sure that I fully understand the problem, but what's sure is that you have a race condition in your code, since your code basically does if (count < max) { count++; If two threads first check, in parallel, if the max has been reached, and then, in parallel, increment the count, then of course the max value will be implemented twice even if you have only one slot left: thread A, check value, value = 9, enter if block thread B, check value, value = 9, enter if block thread A, increment, value = 10 thread B, increment, value = 11 And I'm not surprised it happens when the increment is at position B rather than at position A, since there is a much longer time-frame during which the count has still not be incremented, and another thread might thus enter the if block. To mak

Categories : Java

Condition append depending on image class, how do I code?
You want to use the .hasClass() method. if($("[id^='img']").hasClass("browbandtable1")){ //Your Code here } Edit: I may have misunderstood at first, what you probably want to do is pick your elements in your selector, so $("[id^='img'].browbandtable").append('<img class="browbandtable" src="images/none.png" width="40" height="39">'); $("[id^='img.browbandtable1']").append('<img class="browbandtable1" src="images/none1.png" width="18" height="18">'); This will select only the elements which have an id starting with image, AND that have the particular class name.

Categories : Jquery

Relationship on the basis of Condition in Entity Framework Code First
It's been a while since I did EF Code First, but I believe this should (more or less) do the trick (given that it's a new database you want to make): abstract class Party { int Field1 {get;set;} int Field2 {get;set;} virtual ICollection<PartyType1Party> Parties {get;} } class Person { string Name {get;set;} int Age {get;set;} } class OrganizationParty { int Something {get;set;} int OtherThing {get;set;} virtual ICollection<PartyType2Party> Parties {get;} } class PartyType1Party : Party { Person OrganizerOrSomeRandomPropertyName {get;set;} } class PartyType2Party : Party { OrganizationPart Organization {get;set;} } class Context : DbContext { DbSet<Party> Parties {get;set;} DbSet<Person> Persons {get;set;} D

Categories : C#

Multiple condition in Join Magento
I found the answer myself, It turnout to be very easy $collection = Mage::getModel('module/model_name')->getCollection(); $collection->getSelect()->join( array('table_alias'=>$this->getTable('module/table_name')), 'main_table.foreign_id = table_alias.primary_key and table_alias.columnname = ".."' , array('table_alias.*'));

Categories : Magento

SQL: how to select multiple rows given condition
No record has 2 values of pageid. You probably want: SELECT userid FROM table_name WHERE pageid=100 OR pageid=101 In a cleaner version, you can use: SELECT userid FROM table_name WHERE pageid IN (100,101) UPDATE: Based on the question edit, Here is the answer: SELECT userid FROM table_name WHERE pageid IN (100,101) GROUP BY userid HAVING COUNT(DISTINCT pageid) = 2 Explanation: First of all, the WHERE clause filter out all data except pageid not equal to 101 or 102. Then, By grouping userid, we have a list of unique userid having DISTINCT pageid = 2, which means contain ONLY 1 pageid = 101 and 1 pageid = 102

Categories : SQL

Evaluating multiple variable together in if condition
the only way this would work is if abc was a boolean (and it wouldn't do what you're hoping it would do, it would simply test if abc == true). There is no way to compare one thing to multiple things in Java.

Categories : Java

SQL - Getting a value from one of multiple sources based on condition
You don't need a stored procedure for this. The following query will do what you need: It's left-joining TransactionTable on EmployeeMasterTable directly and through UserMasterTable, then selecting the Ename from the proper joined employee table based on the status criterion SELECT t.*, CASE WHEN t.status = 0 THEN e0.Ename ELSE e1.Ename END AS Ename FROM TransactionTable AS t LEFT JOIN EmployeeMasterTable AS e0 ON t.Ecode = e1.Ecode LEFT JOIN UserMasterTable AS u ON t.PAICID = u.Uid LEFT JOIN EmployeeMasterTable AS e1 ON u.Ecode = e1.Ecode WHERE TBarcode = 1234 If you do need it in a stored procedure, reference the docs for your DBMS on how to do so. It'l probably be something like CREATE PROCEDURE MyProcedure (IN iTBarcode IN

Categories : SQL

How to run if/else condition for multiple selectbox choices?
I made a fork of your jsFiddle with some fixes. You had some syntax errors in the HTML and the javascript. Change the button HTML like so: <input type="button" value="write" /> EDITED...a more reliable way to do it: $(function() { function write() { var select = $('#box1'); var ctext = ''; select.find('optgroup').each(function() { var el = $(this); if (el.find('option:selected').length) { ctext += " - " + el.attr('label') + " - "; var items = []; el.find('option:selected').each(function() { items.push($(this).text()); }); ctext += items.join(',') + " "; } }); $('#text').val(ctext); re

Categories : Jquery

SQL multiple columns in single WHERE condition
Whilst the other post shows you how to do an IN query with multiple columns, this does not indicate that it is possible with other operators such as BETWEEN. As far as I know, the only way to achieve what you want it the way you show at the beginning of your question, with 3 BETWEEN statements :( Sucks I know but that's SQL

Categories : SQL

Query with multiple LIKE with AND condition using REGEXP
Can your keyword field contain multiple values (devices)? Like ipad;iphone;nokia? If so, this is bad practice. It violates First Normal Form, and it's a symptom of bad table design. Still, the way you did it with multiple LIKE and AND clauses should work. Converting this to REGEXP syntax is not easy in MySQL, and definitely not worth the trouble. See this post for more details.

Categories : Mysql

multiple condition in single linq
Using FirstOrDefault in combination with Any: Dim tags = {"FtpHeader","MailHeader","GoogleHeader","NetworkHeader"} Dim xCheckTag = If(tags.FirstOrDefault(Function(tag) Sheet1.Rows.OfType(Of Row).Any(Function(xTag) xTag.Tag = tag)), String.Empty)

Categories : Vb.Net

multiple join on @OneToMany with condition on each
Something like the following should work. SELECT product FROM Product product join product.servingTimeAvailablities as servingTimeAvailablities join product.styles as styles join product.locationAvailabilites as locationAvailabilites WHERE servingTimeAvailablities.someProperty = :somePropertyValue1 AND styles.someProperty = :somePropertyValue2 AND locationAvailabilites.someProperty = :somePropertyValue3 I don't know the internals of your objects, which is why I used 'someProperty' as a field name. You should replace it with the proper field name that you want to match. I also used 'join' as the join type for the example. You should replace that with the join type that you want to use (e.g. inner join, left outer join, etc). Let me know if that works for you. I H

Categories : Java

SQL Join with multiple row condition in second table
SELECT columns FROM table1 a, table2 B WHERE a.pid = B.pid AND a.keyval = 45 AND a.status = 1 AND ( (B.mode = 2 AND B.modeval = 5) OR (B.mode = 3 AND B.modeval = 6) )

Categories : SQL

If condition for multiple search input in PHP
<?php // Check if form was submitted if(!isset($_POST['search']) { // Display the form } else { // Form was submitted, check if values are empty if(trim($_POST['category1'])=="" ) { // One or more value is empty, do something } else if (trim($_POST['category2'])=="") { // Process form } } ?>

Categories : PHP

adding check condition to code every time page is visited
just try $(document).ready(function(){ var str="<!--"; if($("a.video-in-link").indexOf(str)==-1) { //not found //then add comment and href } else { //found } } if u have multiple href then $("a.video-in-link").each(function() { var item=$(this); if($(item).indexOf(str)==-1) { } });

Categories : Jquery

If validation condition is met, then run main chat code after clicking button
you can try to use only one $("#sendMessage").click // main chat code $(function () { var IWannaChat = $.connection.myChatHub; IWannaChat.client.addMessage = function (message) { $('#listMessages').append('<li>' + message + '</li>'); }; $("#sendMessage").click(function () { if ($.trim($("#ideaBody").val()).length === 0) { alert('empty'); return false; } if ($.trim($("#ideaBody").val()) === $("#ideaBody").data('default')) { alert('default'); return false; } else{ IWannaChat.server.send($('#ideaBody').val()); } }); $.connection.hub.start(); }); // handling default values and validation $(function () { $('#ideaTitle, #ideaBody').each(function () {

Categories : Jquery

How do i write code in ASP.NET MVC to check whether user accepeted terms and condition
I think this is what you want to do. you can post back data or use jquery to post to a action to check and if the terms are accepted and then enable the submit button for a better user experience. Whichever way you choose, you can do something like this. var dataEntityModel = new YoursEntities(); AppTerm currentTerm = dataEntityModel.Appterms.ToList(). where(x=>x.GatewayUserId == yourCurrentUserID && x.termid == yourTermId).FirstOrDefault(); if(currentTerm.TermsAccepted == true) { } else { RedirectToAction("action","controller"); }

Categories : Asp Net Mvc

Select Condition Based on Multiple rows
You should be able to use the following query to get the result: select patid from tablea where name in ('A', 'B') group by patid having count(distinct name) = 2; See SQL Fiddle with Demo

Categories : SQL

select multiple rows with condition for one row mysql
try this: SELECT e.*, d.date FROM events e JOIN event_dates d ON e.id = d.event_id WHERE d.date BETWEEN {d '2013-08-01'} and {d '2013-08-31'} AND d.place_id = 1 But I have a doubt. If you have more days with place_id = 1 you want to show your event more times?

Categories : Mysql

Jquery condition check for multiple checkboxes
You can //get all the checked inputs with name skills var checked = $('input[name="skills"]:checked'); //number of checked items var checkedlength = checked.length; //an array containing values of all checked inputs var values = checked.map(function(){ return this.value }).get();

Categories : Jquery

Mysql : SELECT multiple with different condition of selection for each
You can use a CASE expression inside of your aggregate function to convert the rows of data into columns: SELECT country, sum(case when date = 2012 then 1 else 0 end) `2012`, sum(case when date = 2013 then 1 else 0 end) `2013` FROM yourtable GROUP BY Country; See SQL Fiddle with Demo. If you have an unknown number of years, or you want to implement a range of dates, then you can use a prepared statement to generate dynamic SQL: SET @sql = NULL; SELECT GROUP_CONCAT(DISTINCT CONCAT( 'sum(CASE WHEN date = ', date, ' THEN 1 else 0 END) AS `', date, '`' ) ) INTO @sql FROM yourtable; SET @sql = CONCAT('SELECT country, ', @sql, ' from yourtable group by country'); PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE

Categories : Mysql

MongoDB query with condition on multiple records
I don't think it's possible with one query. But you can get all B you want with aggregate and then query database for that B: db.test1.aggregate( [ {$group: {_id: "$B", count: {$sum:1}}}, {$match: {count:1}} ] ) will return you all B for which there only one record in your collection.

Categories : Mongodb

nested IFs or multiple condition in single IF - perl
&& short-circuits. It only evaluates its RHS operand if needed. If it's LHS operand returns something false, && will that value. For example, use feature qw( say ); sub f1 { say "1"; 1 } sub f2 { say "2"; 0 } sub f3 { say "3"; 0 } sub f4 { say "4"; 0 } 1 if f1() && f2() && f3() && f4(); Output: 1 2 So the following two lines are basically the same: if (/abc/) { if (!/def/) { ... } } if (/abc/ && !/def/) { ... } In fact, if compiles into an and operator, so the above are very close to (/abc/ and !/def/) and do { ... }; (/abc/ && !/def/) and do { ... };

Categories : Perl

count with where clause multiple condition on same table
In most versions of SQL, you would use window/analytic functions: select ProductId, ProductName, ProductType, ProductSize, count(*) over (partition by producttype, productsize) from products p The problem with your query is that you are not giving the table names aliases. So an expression like ProductSize=(products.productSize) is not correlated with the outer query. It is actually equivalent to ProductSize = ProductSize on the inner query. You could fix that by just putting from Products p in the inner query. However, the window function approach is better in databases that support it (most of them).

Categories : SQL



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.