Why 2's compliment is done for checksum calculation? - checksum

Why do we require 2's compliment to be done for the checksum, what would happen if we send it as it is or use 1's compliment.
I know it reduces the use of a subtraction module during verification, but does today's computers really require it?

If by "we" you mean some spec, then it's because it is the spec, and probably made sense when it was written. Changing that spec now for some dubious performance gain would break everything written against the old spec.

Related

Rails 4, is there a gem that validates a user is entering a real name?

I want to make sure that users enter real names for their profile on my website. Is there a gem that will take care of these validations?
You cannot validate a name automatically. What's a real name? How do you define a real name?
The only way to validate identity is to ask for a photo ID and let a human verify it. This is even not a 100%, as there might be some Jason Bourne trying to use your system - so he's not using a "real" name either.
Also consider that there may be laws prohibiting or restring your from asking and storing Photo IDs of your users.
What constitutes a name is purely subjective and thus is not deterministic unless the parameters are explicitly configured within some context. Given the amount of configuration needed to accomplish a task like this I doubt that a general purpose library could reasonably exist that would be little more than a wrapper around some gnarly regular expression. What you could do is write your own regular expression for detecting a real name. Two things will happen, you will learn a lot about regexes and computational theory, and you will create something which will inevitably generate both false positives and false negatives. However its your application so whats in a name is entirely up to you.

Is there a way to preprocess ruby code and find errors that would occur runtime?

We have huge code base and we are generating issues that would have been caught at compile time in type languages such as Java but we are not catching them until runtime in Ruby. This is bad since we generate bugs that most of the time are typos or refactoring that leaves some invalid code.
Example:
def mysuperfunc
# some code goes here
# this was a valid call but not anymore since enforcesecurity
# signature changed
#system.enforcesecurity
end
I mean, IDEs can do it but some guys use ATOM or sublime, so we need something to "compile" and report that kind of issues so they don't reach deployment. What have you been using?
This is generating a little percentage of our bug reports, but since we are forced to produce at a ridiculous pace we don't have 100% code coverage. If there is no tool to help, I'll just make sure everybody uses and IDE and run the reports with tools such as Rubymine.
Our stack includes, rspec, minitest, SimpleCov. We enforce code reviews, multistack deployments (dev, qa, pre-prod, sandbox, prod). And still some issues are reaching higher level and makes us programmers look bad. I'm not looking of magic, just a little automation that might help a bit.
Unfortunately, the Halting Problem, Rice's Theorem, and all the other Undecidability and Uncomputability Results tell us that it is simply impossible in the general case to statically determine any "interesting" property about the runtime behavior of a program. We cannot even statically determine something as simple as "will it halt", so how are we going to determine "is bug-free"?
There are certain things that can be statically determined, and there are certain restricted programs for which some interesting properties can be statically determined, but largely, this is not possible. And even to the small extent that it is possible, it generally requires the language to be specifically designed to be easy to statically analyze (which Ruby isn't).
That being said, there are certain tools that contain certain heuristics to point out code that may have problems. There are certain coding standards that may help avoid bugs, and there are tools to enforce those coding standards. Keywords to search for are "code quality tools", "linter", "static analyzer", etc. You have already been given examples in the other answers and comments, and given those examples and these keywords, you'll likely find more.
However, I also wanted to discuss something you wrote:
we are forced to produce at a ridiculous pace we don't have 100% code coverage
That's a problem, which has to be approached from two sides:
Practice, practice, practice. You need to practice testing and writing high-quality code until it is so naturally to you that not doing it actually ends up being harder and slower. It should become second nature to you, such that under pressure when your mind goes blank, the only thing you know is to write tests and write well-designed, well-factored, high-quality code. Note: I'm talking about deliberate practice, which means setting time aside to really practice … and practice is practice, it's not work, it's not fun, it's not hobby, if you don't delete the code you wrote immediately after you have written it, you are not practicing, you are working.
Sustainable Pace. You should never develop faster than the pace you could sustain indefinitely while still producing well-tested, well-designed, well-factored, high-quality code, having a fulfilling social life, no stress, plenty of free time, etc. This is something that has to be backed and supported and understood by management.
I'm unaware of anything exactly like you want. However, there are a few gems that will analyze code and warn you about some errors and/or bad practices. Try these:
https://github.com/bbatsov/rubocop
https://github.com/railsbp/rails_best_practices
FLAY
https://rubygems.org/gems/flay
Via the repo https://github.com/seattlerb/flay:
DESCRIPTION:
Flay analyzes code for structural similarities. Differences in literal
values, variable, class, method names, whitespace, programming style,
braces vs do/end, etc are all ignored. Making this totally rad.
[FEATURES:]
Reports differences at any level of code.
Adds a score multiplier to identical nodes.
Differences in literal values, variable, class, and method names are ignored.
Differences in whitespace, programming style, braces vs do/end, etc are ignored.
Works across files.
Add the flay-persistent plugin to work across large/many projects.
Run --diff to see an N-way diff of the code.
Provides conservative (default) and --liberal pruning options.
Provides --fuzzy duplication detection.
Language independent: Plugin system allows other languages to be flayed.
Ships with .rb and .erb.
javascript and others will be
available separately.
Includes FlayTask for Rakefiles.
Uses path_expander, so you can use:
dir_arg -- expand a directory automatically
#file_of_args -- persist arguments in a file
-path_to_subtract -- ignore intersecting subsets of
files/directories
Skips files matched via patterns in .flayignore (subset format of .gitignore).
Totally rad.
FLOG
https://rubygems.org/gems/flog
Via the repo https://github.com/seattlerb/flog:
DESCRIPTION:
Flog reports the most tortured code in an easy to read pain report.
The higher the score, the more pain the code is in.
[FEATURES:]
Easy to read reporting of complexity/pain.
Uses path_expander, so you can use:
dir_arg – expand a directory automatically
#file_of_args – persist arguments in a file
-path_to_subtract – ignore intersecting subsets of files/directories
SYNOPSIS:
% ./bin/flog -g lib
Total Flog = 1097.2 (17.4 flog / method)
323.8: Flog total
85.3: Flog#output_details
61.9: Flog#process_iter
53.7: Flog#parse_options
...
There is a ruby gem called guard that does automated testing. You can set your own custom rules.
For example, you can make it where anytime you modify certain files, the test framework will automatically run.
Here is the link for guard

Executing arbitrary functions in Ruby without the security problems of eval

I have a Ruby on Rails app and I need to add some arbitrary 'functions' to the database. These functions need to receive predefined parameters, perform arbitrary logic and arithmetic, and return a number or a string.
My first idea was to add the code to the DB and use eval(code), but I soon realised the security issue with this. I could not find a way of a really sandboxed eval.
I also thought about using a JavaScript interpreter, for example, to have the code in JS and run it it's own context, but it still seems a bit too much and not secure enough.
Is there a way to execute simple arbitrary logic and arithmetic from a string over some variables and return a value?
Run arbitrary code it is a unsafe practice and very difficult to ensure that you control all variables and different scenarios.
You can try to patch all Ruby classes/ modules that can run any malicious code, like IO, Kernel, etc, but in the end you will have many classes patched, very difficult to maintain and will not have sure if it will work safely.
The best solution that I can figure out is to create your own programming language where you can ensure all functions and operations that the user will have access.
Nowadays there are many solutions, paper and examples that makes this task not so difficult, for example Ragel http://www.complang.org/ragel/ that compiles to Ruby.
You can start with few operations (if, arithmetic, logic, etc) and improve it incrementally. In the end, you will have a robust solution that can easily evolve to fit on users needs.
How sophisticated does this code need to be? Or conversely, how arbitrary does it need to be? Hopefully, you don't need to store code.
Instead, keep code in your code, and data in your data. Then simply reference names of procedures. For example:
class User
def contact
case self.prefers_contact_method
when :email
Email.send_to self.email
when :sms
SMS.send_to self.mobile_number
when :call
Phone.place_call self.home_number
end
end
end
Putting executable code in your database is not a good idea. Avoid it at all costs. And if you really need to do it, then maybe you should rethink your approach.
And if you really really need to do this, you need a sandbox. Some environment where you can control what arbitrary code has access to so that there is no dangerous code that is possible to be executed. See: Ruby sandboxing vs. integrating a scripting language
But even so, it's a scary thing to open yourself up to. Tread very carefully with this, and think thoroughly through the security implications.

In RSpec, what's the difference between a mock and a double?

In rspec you can either create a mock or a double. These two seem to be almost the same thing and I can't find anything in the documentation that disambiguates them.
What's the difference?
Both mock and stub are aliases of the more generic double. Like context and describe, they can be used interchangeably to make the intent of the specs more clear. This is described in a lot more detail in The RSpec Book.
The seem to be just aliases since :__declared_as doesn't seem to be used but for messages.
doubles
when we depend on components with nondeterministic characteristics, we may find that files get corrupted, disk fail, networks timeout, and servers go down in the middle of running specs. because these are things that we have no control over, they can lead to inconsistent and surprising results when we run our specs. doubles can disconnect our examples from real implementations of these dependencies.
stub
when the system behaviour based on a sequence. a stub is perfect for this .Because each example can specify a different sequence.example:- In case of random generator, it is clearly a source of non determination. we want to replace the real random generator with stable sequence.
Mocks
some time we need some service from another object that may not yet exist. In cases like this we can introduce mock object. which we can program to behave as the object we are currently expects. so when we focus on interaction mock objects make it much easier to achieve.

Why should I test my HTMLHelpers?

Is there any tangible value in unit testing your own htmlhelpers? Many of these things just spit out a bunch of html markup - there's little if no logic. So, do you just compare one big html string to another? I mean, some of these thing require you to look at the generated markup in a browser to verify it's the output you want.
Seems a little pointless.
Yes.
While there may be little to no logic now, that doesn't mean that there isn't going to be more logic added down the road. When that logic is added, you want to be sure that it doesn't break the existing functionality.
That's one of the reasons that Unit Tests are written.
If you're following Test Driven Development, you write the test first and then write the code to satisfy test.
That's another reason.
You also want to make sure you identify and test any possible edge cases with your Helper (like un-escaped HTML literals, un-encoded special characters, etc).
I guess it depends on how many people will be using/modifying it. I typically create a unit test for an html helper if I know a lot of people could get their hands on it, or if the logic is complex. If I'm going to be the only one using it though, I'm not going to waste my time (or my employer's money).
I can understand you not wanting to write the tests though ... it can be rather annoying to write a few lines of html generation code that requires 5X that amount to test.
it takes a simple input and exposes a simple output. This is a good one for TDD, since the time you were going to spend on build->start site->fix that silly issue->start again->oops, missed this other tiny thing->start ... we are done, happy :). Dev 2 comes along and makes small change to "fix" it for something that wasn't working for then, same cycle goes on and dev 2 didn't notice at the time it broke your other scenarios.
Instead, you v. quickly do the v. simple simple text, y that simple output gave you that simple output you were expecting with all the closing tags and quotes you were expecting.
Having written HTML Helpers for sitemap menus, for example, or buttons for a wizard framework, I can assure you that some Helpers have plenty of logic that needs testing to be reliable, especially if intended to be used by others.
So it depends what you do with them really. And only you know the answer to that.
The general answer is that Html Helpers can be arbitrarily complex (or simple), depending on what you are doing. So the no brainer, as with anything else, is to test when you need to.
Yes, there's value. How much value is to be determined. ;-)
You might start with basic "returns SOMEthing" tests, and not really care WHAT. Basically just quick sanity tests, in case something fundamental breaks. Then as problems crop up, add more details.
Also consider having your tests parse the HTML into DOMs, which are much easier to test against than strings, particularly if you are looking for just some specific bit.
Or... if you have automated tests against the webapp itself, ensure there are tests that look specifically for the output of your helpers.
Yes it should be tested. Basic rule of thumb, if it is not worth testing it is not worth writing.
However, you need to be a bit carefull here when you write your tests. There is a danger that they can be very "brittle".
If you write your tests such that you get back a specific string, and you have some helpers that call other helpers. A change in one of the core helpers could cause very many tests to fail.
So it maybe better to test that you get back a non null value, or that a specific text is contained somewhere in the return value. Rather than testing for an exact string.

Resources