Menu
  • HOME
  • TAGS

How can I delete duplicate values from a hash of hash

ruby,ruby-on-rails-4,hash

ones_values = {} hash.delete_if do |key, value| ones_values[value["one"]] ? true : (ones_values[value["one"]] = true) && false end ...

Perl: Multiply loops, 1 hash and regex

arrays,regex,perl,hash,perl-data-structures

you need to append the file when you output meaning use ">>" instead of ">" which will overwrite the file. system("chage -l $_ >> $pwdsett_dump") as you are running it in loop you are overwriting each time the loop executes. Use: foreach (@Usernames) { system("chage -l $_ >> $pwdsett_dump") }...

'floor' value of hash?

ruby,hash

Here is a possible implementation class MyHash < Hash attr_writer :floor def [](key) # you can use one of those two lines or your own code in case the floor hasn't been define # raise 'floor value must be defined' if @floor.nil? # super key if @floor.nil? value = (fetch(key)...

Get array of values from array of hashes

ruby,hash

You should flatten the result, to get your desired output : arr.flat_map { |i| i.values } Read flat_map. I don't know actual intention of yours, still if you want to collect all ids, you can write : arr.collect { |h| h[:id] } ...

Hash holding string arrays doesn't read individual strings in Ruby on Rails

ruby-on-rails,arrays,ruby,ruby-on-rails-4,hash

- @in_bottom.each { |in_bottom| @bottom_count[in_bottom] += 1 } + @in_bottom.flatten.each { |in_bottom| @bottom_count[in_bottom] += 1 } See Documentation Array flatten method...

Client side password hash versus plain text

security,hash,passwords,client,password-hash

Most websites will send the password plain-text over an encrypted connection SSL/HTTPS. Hashing the password client-side can be done, but the advantage is small and often client-side languages (JavaScrypt) are slow so you can calculate less rounds in the same time, what weakens the hash. In every case the server...

Element is present but `Set.contains(element)` returns false

java,hash,set,contains,hashset

If you change an element in the Set (in your case the elements are Set<String>, so adding or removing a String will change them), Set.contains(element) may fail to locate it, since the hashCode of the element will be different than what it was when the element was first added to...

Remove an item from each hash in an Array of hashes

arrays,ruby,hash

You can use map and delete this will work the actual instances of the hashes, so the array will be modified. array.each{ |hash| hash.delete('cat') } you can do this to get a new array and keep the first one non touched. new_array = array.map do |hash| new_hash = hash.dup new_hash.delete('cat')...

How to remove duplicate entries from a hash based on a value

ruby-on-rails,ruby,hash

hash_list.to_a .uniq! { |_, v| v['unit_id'] } .to_h But note that, the duplicates are removed only based on the key unit_id. To do it based on multiple keys, hash_list.to_a .uniq! { |_, v| v.values_at('unit_id','_destroy') } .to_h Please have a look at Hash#values_at Output >> hash_list = { "a"=>{"unit_id"=>"43", "dep_id"=>"153", "_destroy"=>"false"},...

PHP password_hash() / bcrypt

php,hash,bcrypt

The salt isn't a secret, it's generally stored in the database with the hash, and could just as well be stored directly in the hash, like password_hash does. The salt creates uniqueness so the hash can't easily be cracked with things like rainbow tables or dictionaries, it doesn't really add...

How does hopscotch hashing actually work?

algorithm,performance,hash,hashtable,hopscotch-hashing

It says find an item whose hash value lies between i and j, but within H-1 of j. It doesn't say find an item whose current location lies between i and j, but within H-1 of j. The d at index 3 has a hash value of 1, which doesn't...

to access a specific key-value pair in hash

perl,hash

foreach (sort keys %hash) { if ($_ eq 1 ) { print "$_ : $hash{$_}"; last; } } Using last will cause your loop to exit as soon as condition is met. I hope this will solve your problem....

Convert md5 in base64 in md5 of 32 characters with PHP

php,hash,md5

base64_decode gets you from base64 back to binary, and then bin2hex converts that to hex: $var = "wPE2JkrsTJxF+KbSDApwYQ=="; echo bin2hex (base64_decode ($var)); // prints c0f136264aec4c9c45f8a6d20c0a7061 ...

How to pass a hash as optional argument to -M in command line

perl,hash,package,command-line-interface

Looking at perlrun use: perl -Mfeature=say "-Mconstant {c1 => 'foo', c2 => 'bar'}" -e"say c1,c2" ...

Perl comparing two hashes

perl,hash,compare

I've found what appears to be multiple bugs in your program. I've reformatted your code and left comments to the precise locations of the bugs below: #!/usr/bin/env perl use strict; use warnings; use autodie; # use 3-arg open open my $file1, '<', 'file1.txt'; # no need to check errors with...

Java Hashing Password Doesn't Match

java,string,hash

I strongly recommend using a library to handle this for you. Consider Apache Commons Codec library: import org.apache.commons.codec.digest.DigestUtils; public class HashTest { public static String cipher(String pwd, String salt) { return DigestUtils.sha256Hex(pwd+salt); } public static void main(String[] args) { String p = "password"; String s = "randomSalt"; String c =...

Hashing passwords even when password is server-generated?

php,mysql,security,hash

Security is something done in layers and each layer is designed to raise the cost of doing something you don't want them to. Do security guards prevent robberies? No, but they raise the cost of committing one to where most people won't bother. Hashes don't prevent people from hacking your...

Cleaner way of mapping a hash in ruby

ruby,hash

That's just the way Ruby's collection framework works. There is one map method in Enumerable which doesn't know anything about hashes or arrays or lists or sets or trees or streams or whatever else you may come up with. All it knows is that there is a method named each...

Sorting a hash in Perl when the keys are dynamic

perl,sorting,hash

This type question might be more suited to the Programmers Stack Exchange site or the Code Review one. Since it is asking about implementation, I think its fine to ask here. The sites tend to have some overlap. As @DondiMichaelStroma pointed out, and as you already know, your code works...

PHP Compare a crypted password from db with an inserted password from a form

php,hash,cryptography,passwords,md5

Don't use MD5. There are plenty of online documents that explain how insecure this is. For example: https://en.wikipedia.org/wiki/MD5 I would recommend using the crypt() function. Read here: http://php.net/crypt A good one to use would be CRYPT_BLOWFISH Here's a function I found a while back, that I use. Unfortunately I can't...

Disable hash randomization from within python program

python,python-3.x,hash

I suspect this isn't possible, unfortunately. Looking at test_hash.py the HashRandomizationTests class and its descendants were added in the commit that introduced this behavior. They test the hashing behavior by modifying the environment and starting a new process with PYTHONHASHSEED explicitly set. You could try to copy that pattern, perhaps....

How to write a hash function for a std::vector>

c++,hash,struct,stl,unordered-set

What you could do is combine the hashes for all the vectors within the matrix. There is an overload of std::hash for std::vector<bool>. If you try something like this size_t hash_vector(const std::vector< std::vector<bool> >& in, size_t seed) { size_t size = in.size(); std::hash< std::vector<bool> > hasher; for (size_t i =...

SHA hash does not seem to be working correctly

java,hash,cryptography

The hashWord method that you posted is not correct, it does not compile (is this your actual code?); it's not returning a value. With this: byte[] digest = MessageDigest.getInstance("SHA-256").digest("password".getBytes("UTF-8")); for (byte b : digest) { System.out.printf("%02x", b); } I do get the expected output: 5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8 The output 113459eb7bb31bddee85ade5230d6ad5d8b2fb52879e00a84ff6ae1067a210d3 is what...

How to dig into an certain hash depth?

perl,hash

I think this does what you need. Essentially it recurses through the hash until it finds a layer where the hash values aren't references. Then it removes the elements from that layer with the keys in @keys use strict; use warnings; use 5.010; use Data::Dump; use List::Util 'any'; my $hash_ref...

passing hash in subroutines

perl,hash,subroutine

This line %hash = {'name' => 'devendra', 'age' => 21}; is attempting to assign an anonymous hash reference to a hash. What you really mean is %hash = ('name' => 'devendra', 'age' => 21); If you had use strict and use warnings you would have seen the message Reference found...

PHP: Password Hashing

php,hash

The first problem is that you're trying to use SQL to look for a hashed password. The standard procedure is to find the user with a given username, and fetch that user's password so you can validate. Your other problem is that call $row['password'] but you haven't actually set it...

Bulk Password Hashing PHP-LOGIN PROJECT code

php,mysql,pdo,hash

<?php // you should put your db connection stuff here require('connect.php'); //you create a new column to store hashed passwords. Good idea if //something goes bad. You should drop the column with the original // passwords once every thing is ok and done. $result = mysqli_query( $conn, 'alter table users...

how to match hash values in two different hashes

ruby,hash

This will return the values which are common in both hashes def games_in_common(friend_hash,other_hash) other_hash.values & friend_hash.values end ...

custom sort method for hashes which will automatically use the approporiate hash

perl,sorting,hash

The sorting subroutine doesn't take parameters normally (i.e. unless prototypes are involved) through @_, but through $a and $b. ref @array can never return anything, as an array is never a reference. Wrapping by another function works, because you populate @_ by parameters to the wrapper. Use a wrapper to...

Error Hashing + Salt password

python,authentication,python-3.x,hash,salt

You can do salt = salt.decode("utf-8") after salt is encoded to convert it to string.

Save the most recent months of a hash

ruby-on-rails,arrays,ruby,hash

Let me start with a quick note on your code snippet: group_by { |t| t.date.to_date.month } Note that grouping objects by a single month does not take a year in count, so it would end summing up amounts for transactions of both 2012 and 2014 years in a one container....

Unable to understand the hash function of Rabin Karp Algorithm explained at topcoder

algorithm,hash,rabin-karp

To me it looks the same as in the theory before. The trick is that they do it in small steps (constructing the polynomial) Consider a very simple example of a string of length 3: We initialize ht = 0. The loop will first get position 0: ht = text[0]...

Iterating through a array of hashes in a hash that has multiple indexes

arrays,perl,loops,hash,hashmap

You do not actually need to loop through keys %details. I take it, you have built the %details hash based on Borodin's suggestion from Extracting data from log file into Perl hash. In this case what you have is not actually an array of hashes but rather a single hash...

What is Fragment URLs and why to use it

php,url,hash,fragment-identifier

A fragment is an internal page reference, sometimes called a named anchor. It usually appears at the end of a URL and begins with a hash (#) character followed by an identifier. It refers to a section within a web page. In HTML documents, the browser looks for an anchor...

How to read data from a different file without using YAML or JSON

ruby,hash

Given that OP said in comments "I'm not against using either of those", let's do it in YAML (which preserves the Ruby object structure best). Save it: @data = { nodes:[ {:label=>"Person", :title=>"title_here", :name=>"name_here"} ] } require 'yaml' File.write('config.yaml', YAML.dump(@data)) This will create config.yaml: --- :nodes: - :label: Person :title:...

Case Statement using || (OR)

ruby,hash,case

You could write : @email.cc_list = case @site_id when /site(1|2)/ then "smail-alias-1" when /site(3|4|5|6)/ then "email-alias-2" when /site(7|8)/ then "email-alias-3" when /site9/ then "email-alias-4" when /site10/ then "email-alias-5" end ...

IDE doesn't recognize the method

c++,dictionary,hash,qt-creator,code-completion

This feature does not seem to be supported by Qt Creator. There's an open issue about it on http://bugreports.qt.io/. It does work when using the ClangCodeModel plugin though. To use it, go to Help > About Plugins and activate the plugin there: Then, enable its use in the options. Tools...

Decoding Hash from JSON-String in Perl

json,perl,hash

Assuming you are using JSON.pm, the documentation says: The opposite of encode_json: expects an UTF-8 (binary) string and tries to parse that as an UTF-8 encoded JSON text, returning the resulting reference. So you are getting back what you put in. You're putting in a hashref and you're getting a...

Difficulties initializing an array in Perl

arrays,perl,hash

$dec_res->{repositories} is clearly an array It isn't. It is an array reference. but @repos is not? It is an array. You are creating a list that is one item long, and that item is the array reference. You then assign the list to the array, so the array holds...

Create hash from variables in loop

ruby-on-rails,arrays,ruby,hash

In your code example, the variables are all declared as being instance variables, because they're prefixed with @. However, the variables within the loop are simply working/temporary variables, not instance variables. Additionally, x.get_some_data is probably not working, since x is just the loop variable and contains 456, abc, etc., and...

How to print value of a hash map according to increasing/decreasing order of key in c++? [on hold]

c++,hash,hashmap

The keys in a std::map are ordered by default (using operator<). You can just iterate over the map: for (std::map<int, int>::iterator i = m.begin(); i != m.end(); i++) { cout << i->second << "\n"; } ...

change value in hash using an array of keys in ruby

arrays,ruby,hash

Use all but the last key to get the most deeply nested Hash, then assign normally using the last key. keys[0...-1].inject(hash, :fetch)[keys.last] = value Ruby doesn't have references so you can't reassign the value directly. Instead you have to reassign the object pointer, which means going up one level of...

Hashing speed - cryptic results (Hashing twice much slower than hashing once)

c#,.net,hash

Your results are most likely caused by disk caching. Assuming both tests operate on the same data, only the first read will result in significant I/O time. IE: Iteration 1, Test 1 : 30 seconds (= 20s disk read, 10s work). Iteration 1, Test 2 : 30 seconds (= 0s...

Merge two arrays of hashes based on comparison of multiple keys

arrays,ruby,hash

This can be done quite cleanly using a few of Ruby's built-in methods. a1 = [{ ID: 12496, name: "Robert", email: "[email protected]" }, { ID: 12497, name: "Lola", email: "[email protected]" }, { ID: 12498, name: "Hank", email: "[email protected]" }] a2 = [{ ID: 12497, name: "Lola", ORDER_NO: 5511427 }, {...

How to generate a Facebook Release Key Hash on Mac?

android,facebook,osx,hash,facebook-sdk-3.0

You are using /Users/vedtam/Desktop as value for the options keystore. It's not correct, you should also specify also the file name, for example: /Users/vedtam/Desktop/production.keystore Once you find the path of your production keystore modify the command like this: keytool -exportcert -alias RELEASE_KEY_ALIAS -keystore /Users/vedtam/Desktop/production.keystore | openssl sha1 -binary | openssl...

Nested Loop in Ruby, Hash and Array

javascript,arrays,ruby,object,hash

It's pretty simple in ruby using map. pCodePrice = { 'GR1' => 3.11, 'SR1' => 5, 'CF1' => 11.23 } => {"GR1"=>3.11, "SR1"=>5, "CF1"=>11.23} basket = ['GR1','SR1','GR1','GR1','CF1'] => ["GR1", "SR1", "GR1", "GR1", "CF1"] total = basket.map { |code| pCodePrice[code] } => [3.11, 5, 3.11, 3.11, 11.23] ...

Calling an object in a search method in rails

ruby-on-rails,arrays,regex,hash

Got the answer. SInce this is using regex you can pull an object by using /#{ object }/ So my code looks like this @insur_transactions = user.transactions.find_all { |t| (t.fetch('name').downcase! =~ /#{user.bill.name}/) } That got it!...

C - operations on bits representing a structure

c,hash,bit-manipulation

Iterate over all the bytes of the struct and XOR each one individually, e.g., void bytexor(unsigned char xor_byte, void *data, size_t size) { unsigned char *p = data; while (size--) { *p++ ^= xor_byte; } } Usage would be: struct triple my_struct; // ... bytexor(0xFF, &my_struct, sizeof my_struct); (Note: This...

Unique hash/index for time interval

database,mongodb,database-design,hash

I am wondering if this constraint can be enforced by a unique index instead of having to build validation in code. Use an unique compound index on the resource id, day and chunk of 30 minutes. Then insert one document for each 30 minutes of period of reservation. For...

Using shared hash in Perl

multithreading,perl,hash,shared

Use shared_clone() when using a variable (anonymous hash in this case) in an assignment.: use threads; use threads::shared; use Data::Dumper; my %h:shared; threads->create(sub{ $h{manager} = shared_clone({ name => 'John', surname => 'Doe', age => 27 }); })->detach; sleep 1; print Dumper \%h; Output: $VAR1 = { 'manager' => { 'surname'...

Generating an MD5 Hash with a char[]

java,security,hash,md5,message-digest

NOTE: The MD5 Hashing Algorithm should never be used for password storage, as it's hashes are easily cracked. However, I will use it for simplicity. The quick/easy/UNSECURE fix would be to convert the char array to a string. However, this is unsecure because strings are immutable and can't be cleared...

Why does my first hash value disappear in Perl?

arrays,perl,hash

Perl hash can only have unique keys, so $wordcount{2} = "apple"; is later overwritten by $wordcount{2} = "cake"; ...

Extracting data from log file into Perl hash

regex,perl,hash

I would write it like this. Using an explicit variable for the file records just makes more noise so I've used Perl's default $_ The expression $details{comp_name} //= $1 etc. assigns the hash element only if it doesn't already have a value You didn't make it clear how you wanted...

Applying Hash Function n times

c,hash

I don't believe you're algorithm is even correct, so measuring its performance is somewhat akin to counting chickens before the hens lay the eggs, much less before the eggs hatch. There is no reason the iterative workload function should exhibit such abysmal performance unless... Your SHA implementation is hideously inefficient...

how can i delete a hash based on multiple values

ruby-on-rails,ruby,hash

Try this: > hash_list.to_a.uniq{|_,v|v["unit_id"] unless v["_destroy"] == "1"}.to_h #=> { "a"=>{"unit_id"=>"43", "dep_id"=>"153", "_destroy"=>"false"}, "b"=>{"unit_id"=>"43", "dep_id"=>"153", "_destroy"=>"1"}, "d"=>{"unit_id"=>"42", "dep_id"=>"154", "_destroy"=>"false"} } This will check for unit_id as uniq and also let appear "_destory" == "1" entries as you have mention. ...

Deriving a variable type based on another variable type in C++

c++,templates,hash

Using template specialization you could do something like: template <typename T> struct hash_type_for; template <> struct hash_type_for<uint16_t> { using type = uint64_t; }; template <> struct hash_type_for<uint32_t> { using type = uint64_t; }; template <typename T> using hash_type_for_t = typename hash_type_for<T>::type; Then use it like this: template<typename T1, typename T2...

Facebook android app error : Invalid key hash

android,hash,facebook-sdk-4.0

As I understand you've got your key hash, but still I'll put here the code for getting it in the console. PackageInfo info; try { info = getPackageManager().getPackageInfo("com.your.project.package", PackageManager.GET_SIGNATURES); for (Signature signature : info.signatures) { MessageDigest md; md = MessageDigest.getInstance("SHA"); md.update(signature.toByteArray()); String something = new String(Base64.encode(md.digest(), 0)); //String something =...

Path reconstruction with Hashing?

java,algorithm,hash

Here's a simple implementation using HashMaps in Java: String[][] paths = { {"P", "B"}, {"B", "M"}, {"O", "P"}, {"M", "Z"}, }; // create a single hash map, mapping start->end HashMap<String, String> end = new HashMap<>(); for(int i = 0; i < paths.length; i++) { end.put(paths[i][0], paths[i][1]); } // find if...

Confusion with std::pairs initialization

c++,qt,hash,unordered-map,std-pair

I don't know anything about QT, but if QHash is anything like unordered_map, then the issue is where you're using operator[]. That function will insert a default-constructed value for a given key if it doesn't exist. In order to do that, the value-type must be default constructible, and: std::pair<const ParticipantNode&,...

Why is the cost of a hash lookup O(1) when evaluating the hash function might take more time than that?

hash,hashtable,big-o,time-complexity

When talking about hashing, we usually measure the performance of a hash table by talking about the expected number of probes that we need to make when searching for an element in the table. In most hashing setups, we can prove that the expected number of probes is O(1). Usually,...

What will happen if they changed PASSWORD_DEFAULT in PHP Password library?

php,hash,passwords,php-password-hash

What would happen is that newly-hashed passwords will be using the new algorithm - obviously. However, you shouldn't be concerned about this, because the whole thing is designed with forward-compatibility in mind - your code won't be broken when the default algorithm changes, as long as you're using the password_*()...

How do I force iron-router to react when the hash has not apparently changed?

hash,meteor,iron-router

Setting window.location.hash to a space rather than an empty string works: Router._scrollToHash = function(hash) { var section = $(hash); if (section.length) { var sectionTop = section.offset().top; $("html, body").animate({ scrollTop: sectionTop }, "slow"); } window.location.hash = ' '; }; Probably setting it to a non-existent hash would also. In addition to...

Hashing Password in ASP.NET and Resolving it In SQL Procedure

asp.net,vb.net,stored-procedures,hash,password-protection

A very simple aproach is to use a MD5 hash. public class MD5 { public static string Hash(string message) { // step 1, calculate MD5 hash from input System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create(); byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(message); byte[] hash = md5.ComputeHash(inputBytes); // step 2, convert byte array to hex string StringBuilder...

Affecting a value to a multilevel hash in one instruction

perl,hash

it would be more effective if you actually passed the keys to it! Let's make it an lvalue sub at the same time. sub dive_val :lvalue { my $p = \shift; $p = \( $$p->{$_} ) for @_; $$p } my %hash; dive_val(\%hash, qw( foo babel )) = 'fish'; dive_val(\%hash,...

Why k and l for LSH used for approximate nearest neighbours?

algorithm,hash,knn,locality-sensitive-hash,approximate-nn-searching

All of the hash functions are in fact used. This makes more sense if you remember that, for example, in the section "Bit sampling for Hamming distance" an individual hash function might simply return a single bit. In fact another example of an LSH hash function is to consider a...

Hash Map entries collision

java,eclipse,dictionary,hash,hashmap

The hashCode of the keys is not used as is. It is applied two transformations (at least based on Java 6 code): static int hash(int h) { // This function ensures that hashCodes that differ only by // constant multiples at each bit position have a bounded // number of...

generating a pseudo unique number(code) based on a sequence of numbers with no repetition within 4 digits

php,math,hash

You can design a custom Linear Congruential Generator that generates random 5-digit numbers and is guaranteed not to repeat until it has generated all of them. An LCG generates random numbers using the following formula: Xn+1 = ((Xn * a) + c) mod m To generate 5-digit numbers m should...

Ruby hash with key as hash and value as array

ruby,hash

Your initial code is equivalent to shop = items.group_by do | i | {'name' => i['name'], 'value' => i['value'] } end To add the color to the key hash, simply do shop = items.group_by do | i | {'name' => i['name'], 'value' => i['value'], 'color' => i['color'] } end Now,...

How to correctly dereference a hash within a foreach loop?

perl,hash

Make sure to use strict, use warnings, and it would be a good idea to avoid the experimental auto-dereferencing. There are several runtime errors in your code that you would have caught with strict mode, for example you try to dereference items3 into an array but it is a hashref,...

Assign hash to array

arrays,ruby,file,hash

You could do: size = Hash[arr.zip(arr_s)] To give you a better idea, in irb, I typed: a = (1..5).to_a => [1, 2, 3, 4, 5] b = ('a'..'e').to_a => ["a", "b", "c", "d", "e"] Then, typing size=Hash[a.zip(b)] Returns {1=>"a", 2=>"b", 3=>"c", 4=>"d", 5=>"e"} So you could do: puts size[1] which...

Convert multilevel hash in simple hash in perl

perl,hash

Assuming my %hash = ( 'MainSlab' => { 'A1' => { 'Slab' => { '49_168' => { 'Amt' => '3000', 'Start' => '49', 'End' => '168' }, 'A2' => ... ); Then: my $hashref = $hash{'MainSlab'}; my $new_hashref = {}; foreach my $ax (keys %$hashref) { foreach my $k (keys...

Order-independant Hash Algorithm

java,algorithm,hash,set

The JDK itself proposes the following solution to this problem. The contract of the java.util.Set interface states: Returns the hash code value for this set. The hash code of a set is defined to be the sum of the hash codes of the elements in the set, where the hash...

How to store database records into hash ruby on rails

mysql,ruby-on-rails,hash

data = Record.limit(1000) # Load no more than a 1000 entries .pluck(:time, :value) # Pick the field values into sub-arrays # it will also `SELECT` only these two # At this point you have [[time1, value1], [time2, value2]] # good already, but we can go further: .to_h # Ruby 2.1+...

Converting hash ruby objects to positive currency

ruby-on-rails,ruby,hash,currency

Numeric.abs() can be applied to ensure a number is positive and Float.round(2) will round a float to 2 decimal places. See ruby-doc.org/core-2.1.4/Numeric.html#method-i-abs and ruby-doc.org/core-2.2.2/Float.html#method-i-round for usage examples. Note that round() will not add trailing zeros since that does not affect numerical value, however trailing zeros can be added by formatting,...

Efficiently checking a hashed password from database

php,mysql,hash,php-password-hash

Basically, your code looks quite okay, except the things already mentioned. As you ask for improvements, especially performance related ones, here we go: Add an index on username If your table gets a lot of entries, remove the index from username, add a new column called hash with an index...

Deterministic hashing of Python 3 strings with adler32

python,python-3.x,hash,zlib

data must be a byte string. If you want to compute a checksum of Unicode data, you will need to encode it to a byte string, and you will need to make sure to stick with a specific encoding. For example, using UTF-8: checksum = zlib.adler32("S89234IX".encode('utf-8')) & 0xffffffff ...

choice between map or unordered_map for keys consisting of calculated double values.

c++,dictionary,hash,unordered-map,comparison-operators

"is it possible to write a Hash function for four doubles (or even just a regular double) that takes a comparison error tolerance into account." No, it is not. That sounds like a very definite statement, how can I be so sure? Let's assume you want a tolerance of 0.00001....

Creating a Hash with keys from an array and empty arrays as the values

arrays,ruby,hash

Using flatten, map [] instead of nil like you tried, then use flatten(1). That eliminates only the first layer of array, so you get ['tag1', [], ...] to pass to Hash[]. > tags = %w[tag1 tag2 tag3] => ["tag1", "tag2", "tag3"] > tags.map {|k| [k, []]}.flatten => ["tag1", "tag2", "tag3"]...

What's going on with this hash? [duplicate]

ruby,hash

Note that all arguments, unlike blocks, are evaluated only once and prior to the method call. In step 1, you are assigning a particular array as the default value. This array instance will be used for the default value of h. Notice that, since you have not set the default...

Ruby access hash within an array within a hash (and add new hash)

arrays,ruby,hash

You can return values for specific key (:a) data[:a] # => [{:label=>"Person", :title=>"Manager", :name=>"Mike Waldo"}, {:label=>"Person", :title=>"Developer", :name=>"Jeff Smith"}] And if you need to save value to :a Hash so you just use data[:a] << {:label => "new label", :name => "new name", :titles => "new title"} # => [{:label=>"Person",...

Spark: Filtering out agregated data?

scala,hash,apache-spark,filtering

There is a way to do it with Spark without the need to bring counts to single machine: //count books by reader using reduceByKey transformation (thus no action yet) // and filter readers with books count > 10 val readersWithLotsOfBooksRDD = data.map(r => (r.reader, 1)).reduceByKey((x, y) => x + y).filter{...

Formating issue with md5deep

batch-file,hash,md5

From http://md5deep.sourceforge.net/md5deep.html: -q Quiet mode. File names are omitted from the output. Each hash is still followed by two spaces before the newline. ...

How can I get the original type of data after being processed by Object as Hash in JavaScript?

javascript,object,hash

it could be easily done, just store object instead of 1 https://jsfiddle.net/uo8v55qf/1/ var singleNumber = function(nums) { var hash = {} for(var i=0;i<nums.length;i++) if (hash.hasOwnProperty(nums[i])) delete hash[nums[i]] else hash[nums[i]] = { value:nums[i], type: typeof nums[i]}; for(var x in hash) return hash[x]; } result = singleNumber(['123',123,'23']); console.log(result); console.log(result.value + ' type:'...

Perl - Hash and the => operator

perl,hash

They are not exactly the same. The "fat comma" does one more thing: it quotes the left hand side operand when it's a bareword. Therefore, undef, 1 is equivalent to undef(), 1 while undef => 1 is equivalent to 'undef', 1 See perlop: The => operator is a synonym for...

NSData dataWithContentsOfFile returns different results on device

ios,iphone,hash,md5,nsdata

I'm going to guess that it's Xcode applying PNGCrush to your image... so it is actually not the same file.

Java HashMap, hashCode() equals() - how to be consistent with multiple keys? [duplicate]

java,hash,hashmap,key

I think your question really goes a long way beyond plain implementation of hashCode - it's really about the design of when two IDs should be considered equal. If you have multiple fields all of which are unique, you're actually in a tricky situation. Ignoring the MAC address part, there's...

Reference RSVP hash from inside the same hash

ember.js,hash

Ember.RSVP.hash() is good to avoid encoding the actual promise order. When order is important you could use promise chaining. model: function(params) { var self = this; return this.store.find('flyer', params.flyer_id).then(function(flyer) { return Ember.RSVP.hash({ flyer: flyer, images: self.store.find('image', flyer.get('imagesID')) }); }); }, In your special case you use route dynamic param params.flyer_id,...

Rails hash key/value created differently in local vs heroku

ruby-on-rails,postgresql,sqlite,heroku,hash

This looks to be a difference in how the pg Gem and underlying libpq driver handle typing vs. the SQLite driver, stemming from a deliberate decision by the driver developers to leave type conversion to the application framework and return everything as a string. By executing raw SQL and going...

Is this a bad practice for storing passwords in PHP?

php,hash,passwords,md5,salt

It is considered bad practice by many. Here are (some of) the reasons: You are using md5, a weak, old, and fast to calculate hash. The salt is generated in a predictable fashion. The salt should be different for every user (even if registered in the same second) and should...

C++: Quickest way to get integer within a range

c++,c,hash,modulo,low-latency

The problem I am facing is that the function returns key as void *. It does not. It returns nothing (void). The hash result is recorded in the buffer you specify (a pointer to) via last argument. For MurmurHash3_x86_32(), it makes the most sense for that to be a...

Perl Variable/Regex Issue, how to use store regex matches in a loop preferably without using hashes

arrays,regex,perl,file,hash

No hashes nor arrays involved, just regular expressions: #! /usr/bin/perl use warnings; use strict; my $entry = 'user entry user entry $number user entry'; while (<DATA>) { if (s/^foo.*?([0-9]{1,9}).*/$entry/) { my $number = $1; s/\$number/$number/; } print; } __DATA__ blah blah durrr foo hello 23425253 whatever something something who cares...