PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label compare. Show all posts
Showing posts with label compare. Show all posts

Monday, November 7, 2022

[FIXED] How can i compare two properties of struct in a single SET?

 November 07, 2022     c++, compare, operator-overloading, set     No comments   

Issue

My code is as below. I have as struct ABC and i have set g_ABCSet to compare the id.

struct ABC
{
CString name;
byte id[2];
}

typedef shared_ptr<ABC> ABC_PTR;

std::set<ABC_PTR, CompareABC> g_ABCSet;

class ComparePager{
public:
    bool operator()(const ABC_PTR& m1, const ABC_PTR& m2) const {
        if (m1->id[0] == m2->id[0]){
            return m1->id[1] < m2->id[1];
        }
        return m1->id[0] < m2->id[0];
    }
}

I try to search in set as below comparing the id

static ABC_PTR ABCptr(new ABC);
//Assume ABCptr have some valid ID 
auto it = g_ABCSet.find(ABCptr);
if (it == g_ABCSet.end())
 {
//not found
}
else
{
 //found one
}

My query here is can i use the same set to compare the "Cstring name" in the ABC struct.

If YES HOW ??

IF NO , DO i need to make same new set ,overlaod operator to comparing Cstring and insert all same pointers to new set also ??


Solution

No you cannot use a single std::set.

Why: Because the set requires the keys to be in 'strict ordering'. Most likely the set uses a tree structure to store it's items and the tree is sorted by the given comparator.

This means also that if you insert multiple items with different names and identical ids, only one items is stored at all (because the Comparator says they are all identical)

You can use std::find_if to search for Cstring name:

CString searchName = "...";
auto it = std::find_if(
  g_ABCSet.begin(), 
  g_ABCSet.end(), 
  [&](const ABC_PTR& ptr) {
     return ptr->name == searchName;
  });

If you have a large set of items in g_ABCSet you should do as you wrote: create a second set with a Comparator for 'name'.

Tip: If you use std::array<byte, 2> id instead of byte id[2] your Comparator could be as simple as

class ComparePager{
public:
    bool operator()(const ABC_PTR& m1, const ABC_PTR& m2) const {
        return m1->id < m2->id;
    }
}

Maybe you better use a std::map<std::array<byte, 2>, ABC_PTR> and another std::map<CString, ABC_PTR> for this job. This needs more memory (mostly because of the CString being copied from the g_ABCSet into the map) but get completly rid of the custom Comparators and you cannot accidentally use the wrong set (with the wrong Comparator)



Answered By - Andreas H.
Answer Checked By - Katrina (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, November 2, 2022

[FIXED] How to compare 2 files fast using .NET?

 November 02, 2022     c#, checksum, compare, file     No comments   

Issue

Typical approaches recommend reading the binary via FileStream and comparing it byte-by-byte.

  • Would a checksum comparison such as CRC be faster?
  • Are there any .NET libraries that can generate a checksum for a file?

Solution

A checksum comparison will most likely be slower than a byte-by-byte comparison.

In order to generate a checksum, you'll need to load each byte of the file, and perform processing on it. You'll then have to do this on the second file. The processing will almost definitely be slower than the comparison check.

As for generating a checksum: You can do this easily with the cryptography classes. Here's a short example of generating an MD5 checksum with C#.

However, a checksum may be faster and make more sense if you can pre-compute the checksum of the "test" or "base" case. If you have an existing file, and you're checking to see if a new file is the same as the existing one, pre-computing the checksum on your "existing" file would mean only needing to do the DiskIO one time, on the new file. This would likely be faster than a byte-by-byte comparison.



Answered By - Reed Copsey
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, October 28, 2022

[FIXED] How to search for empty string/compare two strings in Robot Framework

 October 28, 2022     compare, if-statement, is-empty, robotframework, string     No comments   

Issue

I have read this question

How to test for blank text field when using robotframework-selenium?

as well as the two links to the Robot Framework documentation in the answers but I still don't get how to check if a variable is empty.

I want to do this

if var A equals var B then
   do something
else
   do something else

where A is a string that can both contain something as well as be empty and where B is empty or null.


Solution

can be achieve using many different ways some are as follows, use whichever fits for you

  1. this way you can check two variables equals OR not

    Run Keyword If    '${A}'=='${B}'   do something    ELSE    do something
    
  2. this way you can check if both of your variable are None or not in one go

    Run Keyword If    '${A}'=='None' And '${B}'=='None'    do something
    
  3. using following also you can get if your variables are equal of not if both values are equal it will return true

    Should Be Equal    ${A}    ${B}
    
  4. if both values are NOT equal it will return true.

    Should Not Be Equal   ${A}    ${B}
    

for more information go through this docs

there is also ${EMPTY} variable in robot framework which you can use to check if variable is empty or not



Answered By - Dev
Answer Checked By - Mildred Charles (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, October 24, 2022

[FIXED] How can I compare float values

 October 24, 2022     c, compare, decimal, if-statement     No comments   

Issue

I wrote this little code to get from Fahrenheit to Celcius. I know that when I type "float a = 41.9" the value is 41.90000045 or something. How can I limit the decimal places to only 1 so that my "if-statement" will become true?

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

float FtoC(float a);

int main()
{
    if (FtoC(41.9) == 5.5){
    printf("%f\n", FtoC(41.9));
    }

    return 0;
}


float FtoC(float a){

  float x = (a - 32.0) / 9.0 * 5.0;
   return(x);

}

Solution

You can include math.h lib and use roundf function.

#include <math.h>

float C = roundf(FtoC(41.9)*10.0f)/10.0f;
if ( C == 5.5) {
    printf("%f\n", C);
}


Answered By - Semyon
Answer Checked By - Timothy Miller (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, October 17, 2022

[FIXED] How can I check whether neighbor (previous and next) digits in a row differ in 1 (Python 3)

 October 17, 2022     compare, integer, list, python-3.x     No comments   

Issue

is it possible to create a code(without list comprehensions, please) that will compare whether neighbor (previous and next) digits in a row differ in 1 so if the condition is met returns the row and returns "good", if not met - "bad". Also, the difference between 9 and 0 doesn't consider as 1. Besides, I need to check whether the only one-digit number and return "one digit" then. I see for me just now it's tricky, so please help! For example:

for (12345432): 
    return "good"                                                                  
for (1793):
    return "bad"
for (7):
    return "one digit"                                                                         

`


Solution

Another solution (with check for one digit):

i = 12345432

if i < 10:
    print("One Digit")
else:
    for a, b in zip(str(i), str(i)[1:]):
        if abs(int(a) - int(b)) != 1:
            print("Bad")
            break
    else:
        print("Good")

Prints:

Good


Answered By - Andrej Kesely
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, September 14, 2022

[FIXED] How to save `find -exec` result and used to compare `FILE OWNER`,regardless white space file name?

 September 14, 2022     bash, compare, exec, find, permissions     No comments   

Issue

find . -depth -exec stat --format '%n %U %G' {} + | sort -d > acl_file_old
#some days later,do it again,and then compare
find . -depth -exec stat --format '%n %U %G' {} + | sort -d > acl_file_new
while read FILE OWNER GROUP; do
    while read FILE_NEW OWNER_NEW GROUP_NEW; do
    if [[ $FILE == $FILE_NEW ]]; then
    echo "$FILE"
    break
    done < $result_dir/acl_file_new
done < $result_dir/acl_file_old

Run above bash script,When file name has white space,such as my file here,while read FILE works not well.

I already read similar post1,post2,I know looping over find's output is bad practice.The problem is I need save find -exec result acl_file_old first.

How to save find -exec result and used to compare FILE OWNER,regardless white space file name?


Solution

The read command assigns the words found on the line to the variables.

Note that the last variable is assigned with all the chars remaining up to the end of the line.

The first quick win would be to change the order and make sure that the filename is located at the end with ... -exec stat --format '%U %G %n' {} + ...

Then change the order of the variables to while read -r OWNER GROUP FILE ; do ...

It there are more fancy chars this would be broken anyway. Maybe for (space) it would do the trick ?



Answered By - Jay jargot
Answer Checked By - Robin (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, August 30, 2022

[FIXED] How to show a comparison of 2 html text blocks

 August 30, 2022     compare, comparison, html, pear, php     No comments   

Issue

I need to take two text blocks with html tags and render a comparison - merge the two text blocks and then highlight what was added or removed from one version to the next.

I have used the PEAR Text_Diff class to successfully render comparisons of plain text, but when I try to throw text with html tags in it, it gets UGLY. Because of the word and character-based compare algorithms the class uses, html tags get broken and I end up with ugly stuff like <p><span class="new"> </</span>p>. It slaughters the html.

Is there a way to generate a text comparison while preserving the original valid html markup?

Thanks for the help. I've been working on this for weeks :[

This is the best solution I could think of: find/replace each type of html tag with 1 special non-standard character like the apple logo (opt shift k), render the comparison with this kind of primative markdown, then revert the non-standard characters back into tags. Any feedback?


Solution

The problem seems to be that your diff program should be treating existing HTML tags as atomic tokens rather than as individual characters.

If your engine has the ability to limit itself to working on word boundaries, see if you can override the function that determines word boundaries so it recognizes and treats HTML tags as a single "word".

You could also do as you are saying and create a lookup dictionary of distinct HTML tags that replaces each with a distinct unused Unicode value (I think there are some user-defined ranges you can use). However, if you do this, any changes to markup will be treated as if they were a change to the previous or following word, because the Unicode character will become part of that word to the tokenizer. Adding a space before and after each of your token Unicode characters would keep the HTML tag changes separate from the plain text changes.



Answered By - richardtallent
Answer Checked By - Marie Seifert (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, August 12, 2022

[FIXED] how to check for a value in a list of decimal C#

 August 12, 2022     .net, c#, c#-4.0, compare, decimal     No comments   

Issue

how to check if a decimal value exists in a list of decimal C#.

I want to achieve the following, but I am looking for right way to compare a decimal value from a list of decimals.

decimal value = 100;
List<decimal > Amounts = new List<decimal>() { 20, 30 };
I want to compare if 
Amounts.Any(value)
//do something
else
do something

Solution

You can use the .Find() method from here:

List.Find(Predicate) Method

Example:

decimal valueToFind = 100;
List<decimal> amounts = new List<decimal>() { 20, 30 };
var result = amounts.Find(x => x == valueToFind);

if (result == 0){
    //not found
}
else if (result == valueToFind){
    //found
}


Answered By - troyw1636
Answer Checked By - Timothy Miller (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, August 10, 2022

[FIXED] How to compare decimal values

 August 10, 2022     compare, decimal, ios, objective-c     No comments   

Issue


I have a problem with comparison two decimal values.
I have a text field that contains number like 0.123456 and NSNumber that contains 0.000001.
Maximum fraction digits of both is 6. Minimum - 0
I've tried to do it like that:

NSNumberFormatter *decimalFormatter = [[NSNumberFormatter alloc] init];
[decimalFormatter setNumberStyle: NSNumberFormatterDecimalStyle];
[decimalFormatter setMaximumFractionDigits:6];

double sum = [[decimalFormatter numberFromString:self.summTextField.text] doubleValue];

if (self.minSum != nil) {
    if (sum < [self.minSum doubleValue]) {
        return NO;
    }
}

But i have a problem, that sometimes 0.123456 = 0,123455999... or 0,123456000000...01 For example @0.000001 doubleValue < @0.000001 doubleValue - TRUE.


How can I compare to NSNumber with a fractional part, to be sure that it will be correct?


Thanks in advance.


Solution

You can round your value, if you worried about fractional part... Something like this:

-(double)RoundNormal:(double) value :(int) digit
{
    value = round(value * pow(10, digit));
    return value / pow(10, digit);
}

And then compare it.



Answered By - Konstantin
Answer Checked By - Clifford M. (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, July 20, 2022

[FIXED] How do I take an input, add it to a list, and use loops and if elif else statements to check if any two values are the same?

 July 20, 2022     compare, integer, list, python     No comments   

Issue

I am trying to make a simple program that uses for loops, if-elif-else statements, and input to take three "employees" salaries and compare them to see if A, any of them have the same salary. Or B if non of them have the same salary. So far, this is what I got but both strategies I've tried haven't been successful and I don't understand why :(. All help is appreciated, and spare me for I'm still new to coding and I'm trying to teach myself through these exercises. Thank you kindly!

salarylist = [] 
salarylist = list(map(int, salarylist))


maxLengthList = 3
while len(salarylist) < maxLengthList:
    salary_of_employee = int(input("Enter your salary: "))
    salarylist.append(salary_of_employee)
print("salary of employees are:\n")
print(type(salarylist))
print(salarylist)
print(type(salarylist))
x = salarylist
if salary_of_employee == salarylist[x]:
    print(f"these are the same salary.{salary_of_employee} and {salarylist[x]}")
else:
    print('non of the salaries are the same.')

    
############################################################################   
    
    
empOne = salarylist[0]
empTwo = salarylist[1]
empThree = salarylist[2]

if empOne == salarylist[0]:
    print("these are the same salary.")
elif empTwo == salarylist[1]:
    print('these are the same salary')
elif empThree == salarylist[2]:
    print('these are the same salary')
else:
    print('non of the salaries are the same.')


Solution

I have tried running your code and it gives a horrible error. I clearly understood your desire. Most of your logic don't meet it. So I decided to RE-Code everything based upon your requirements {for loops, if, elif, else statement, 3 employees etc..}

MAX_LEN = 3
COUNTER = 1 
LIST_SAL = []
while MAX_LEN >= COUNTER:
    ASK_SAL = int(input('Enter your salary :'))
    LIST_SAL.append(ASK_SAL)
    COUNTER+=1
print(LIST_SAL)
for check in LIST_SAL:
    if LIST_SAL.count(check)>1:
        print('Same salaries presented in the list')
        break
    else:
        print('Salaries of employees are unique!')
        break 

Okay so .. I created a variable max_len = 3 which is the total number of employees and then I initiated the variable COUNTER to 1 so that it iterates in the while loop and gets incremented by 1 each time. Therafter a variable named ask_sal asks the user for salaries {3 times} and appends each input to the LIST_SAL variable {a list}. And then I printed the list for visualisation.

There after I accessed the elements in the list {list_sal} by a for loop with the variable check which looks for the number of time an element repeats in the list all by the help of count() function Which, IF greater then one prints "SAME salaries presented" OR else prints "Unique salary"..

You might be wondering why have I used 2 break statements.. Well they are used to break the further iteration as the if or else condition are met in the first iteration. If you try removing the break statements, the print function will work the number of times the same salaries occur in the list.

Hope I helped you.. I am too , a newbie in programming yet I love it and practice a lot . Keep grinding and Working hard



Answered By - LunaticXXD10
Answer Checked By - Marilyn (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, July 19, 2022

[FIXED] How to compare integers with accuracy in Python?

 July 19, 2022     colors, compare, integer, python, tuples     No comments   

Issue

I have a tuple for color. For example, (218, 174, 84). The task is to increase each red, green and blue value by some increment and then compare it with an accuracy 1. How can I do this in Pythonic way? Do you know best practices?

Color: (218, 174, 84) Increment: 5

For red value 222, 223, 224 is legal. Green: 178, 179, 180, Blue: 88, 89, 90.


Solution

def valid_color(orig_color, new_color, increment):
    return all(c1 + increment - 1 <= c2 <= c1 + increment + 1 for c1, c2 in zip(orig_color, new_color))

Use zip() to pair up the components of the original color and the color you're comparing with. Then use comparison operators to test that each component is valid.



Answered By - Barmar
Answer Checked By - Cary Denson (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to compare integers with accuracy in Python?

 July 19, 2022     colors, compare, integer, python, tuples     No comments   

Issue

I have a tuple for color. For example, (218, 174, 84). The task is to increase each red, green and blue value by some increment and then compare it with an accuracy 1. How can I do this in Pythonic way? Do you know best practices?

Color: (218, 174, 84) Increment: 5

For red value 222, 223, 224 is legal. Green: 178, 179, 180, Blue: 88, 89, 90.


Solution

def valid_color(orig_color, new_color, increment):
    return all(c1 + increment - 1 <= c2 <= c1 + increment + 1 for c1, c2 in zip(orig_color, new_color))

Use zip() to pair up the components of the original color and the color you're comparing with. Then use comparison operators to test that each component is valid.



Answered By - Barmar
Answer Checked By - Katrina (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to compare 2 integers to see if they are equal?

 July 19, 2022     c++, compare, integer     No comments   

Issue

How do I compare two integers in C++?


I have a user input ID (which is int) and then I have a Contact ID that is part of my Struct. The Contact ID is int also.

I need to compare to see if they are the same, to know that it exists.

I did something like this*:

if(user_input_id.compare(p->id)==0) 
{
}

but I get an error message saying that expression must have class type.

*based on reading this page http://www.cplusplus.com/reference/string/string/compare/


Solution

The function you found is for comparing two std::strings. You don't have std::strings, you have ints. To test if two ints are equal, you just use == like so:

if (user_input_id == p->id) {
  // ...
}

In fact, even if you had two std::strings, you'd most likely want to use == there too.



Answered By - Joseph Mansfield
Answer Checked By - David Marino (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, May 5, 2022

[FIXED] How does comparing images through md5 work?

 May 05, 2022     compare, hash, image, md5, php     No comments   

Issue

Does this method compare the pixel values of the images? I'm guessing it won't work because they are different sizes from each other but what if they are identical, but in different formats? For example, I took a screenshot and saved as a .jpg and another and saved as a .gif.


Solution

An MD5 hash is of the actual binary data, so different formats will have completely different binary data.

so for MD5 hashes to match, they must be identical files. (There are exceptions in fringe cases.)

This is actually one way forensic law enforcement finds data it deems as contraband. (in reference to images)



Answered By - jondavidjohn
Answer Checked By - Marie Seifert (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, February 2, 2022

[FIXED] Compare two database's structure in MySQL

 February 02, 2022     compare, database, localhost, mysql, phpmyadmin     No comments   

Issue

I need compare the structure of two MySQL databases and something show me what is the difference between they.

Anyone knows any way for this?

Thank you in advance.


Solution

If you are looking to confirm the structures are identical, then one rudimentary way to do this is to run a mysqldump --no-data on each database, and then compare the output files, using e.g. diff. That's not necessarily the best way to do it, but if you are just checking to see if there are any differences, then it's workable.

I use a third-party tool (DB Solo) to perform schema compares, this produces output in a much more robust format/interface, and is useful when there are lots of differences and I want to visualize/investigate.

(I have the community edition of SQLyog; I believe the Enterrprise edition has a Schema Synchronization tool.)



Answered By - spencer7593
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, January 14, 2022

[FIXED] Online game using .net technologies

 January 14, 2022     asp.net-mvc-3, compare, lamp, online-game     No comments   

Issue

I am new in game development, but I'm thinking about creating online browser game on asp.net mvc3 using entity framework for ORM data mapping and SQL Server 2008 DB for data data storage. I would like to hear your thoughts about this. What advantages and disadvantages of this approach. Why is it worse than using classic LAMP.


Solution

first of all costs. As I assume you are paying for the licences, second is speed(linux is faster than windows), third portability and safety (apache is more secure than IIS and also faster) and apache/mysql/php can run on windows while IIS and will not work on something else. Overall more Lamp hosters than Windows hosters as far as I know. Then PHP is faster than ASP (execution speed and development speed), cheaper to develop, much more flexible and lighter(even if you use a framework like symphony or Zend). examples: Facebook works with php, Yahoo works with PHP, IBM is befriending PHP . MySQL is fast and easy to maintain. Microsoft Technology is for corporations (As my personal opinion on their technology, I rather keep it to my self, raise your hands IE6 friends). If you are going for PHP or MySql though their flexibility can be tricky, as you can do a lot of things, if you do not master your school theory you might end up with a monster.



Answered By - Catalin Marin
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home
View mobile version

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing