w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Obtaining the hash of a file using the stream capabilities of crypto module (ie: without hash.update and hash.digest)
From the quoted snippet in the question: [the Hash class] It is a stream that is both readable and writable. The written data is used to compute the hash. Once the writable side of the stream is ended, use the read() method to get the computed hash digest. So what you need to hash some text is: var crypto = require('crypto'); // change to 'md5' if you want an MD5 hash var hash = crypto.createHash('sha1'); // change to 'binary' if you want a binary hash. hash.setEncoding('hex'); // the text that you want to hash hash.write('hello world'); // very important! You cannot read from the stream until you have called end() hash.end(); // and now you get the resulting hash var sha1sum = hash.read(); If you want to get the hash of a file, the best way is create a ReadStream from th

Categories : Node Js

In a file/array, search for hash key, and replace it with the hash value, do this for all hash keys/values
You exhaust your file the first time through your loop using the initial $find and $replace key/value pair. There are two potential solutions: Open the file for reading during each iteration of your while loop (expensive) Move the foreach loop to the outside of the while and iterate the hash each time (less expensive) example: REPLACE: for my $line (@gtfarray) { while(my ($find, $replace) = each %hash) { if($line =~ s/$find/$replace/g) { push @newgtf, $line; next REPLACE; # skip to next iteration } } # if there was no replacement, push the old line push @newgtf, $line }

Categories : Perl

How do I print a hash of hash to a table in an ASCII file?
Based on "What is the “right” way to iterate through an array in Ruby?": puts "*" * <number of asterisks> puts "| No | Mode |..." puts "*" * <number of asterisks> number = 1 for mode in h.keys.sort first = true for subkey in mode.keys.sort if first puts "| #{number.inspect} | #{h[mode].inspect} | #{subkey.inspect} |..." first = false else puts "| | | #{subkey.inspect} |..." end puts "-" * <number of dashes> end number += 1 end

Categories : Ruby

run javascript function by url hash
Make sure to check the runtime versions that your host is using and that they comply with the ones you have locally. Usually, a host will run a version of a software that is often outdated in order to accommodate older websites. (ex. running PHP 4 instead of PHP 5).

Categories : Javascript

Using an Element as the key to a Hash in JavaScript
In JavaScript until ES 6, only strings can be used as a key. If you want to use DOM elements, either use two linked lists, or the WeakMap object. A bonus of the latter method is that it does not cause memory leaks. Applied to your example: var hash = new WeakMap(); hash.set(document.getElementById('foo'), 'bar'); hash.get(document.getElementById('foo')); // returns 'bar' As of writing, WeakMap is only supported by the following browsers: Firefox 6 Chrome 19 (disabled by default, see instructions to enable) Opera 15 (disabled by default, start Opera with --js-flags=--harmony to enable it). Internet Explorer 11 (confirmed to exist in leaked build) In all other browsers, WeakMap support can be achieved by loading the WeakMap.js polyfill.

Categories : Javascript

Hash Tables in javascript
Your final object structure would look like this: { 'scholar': [], 'contributor': [] } To build this, iterate through the names array and build the final result as you go: if the final result contains the key, push the corresponding date on to its value otherwise set a new key to an array containing its corresponding date. something like: var resultVal = {}; for(var i = 0; i < names.length; ++i) { if(resultVal[names[i]]) { resultVal[names[i]].push(dates[i]); } else { resultVal[names[i]] = [dates[i]]; } } Accessing the result - iterating through all values: for(var key in resultVal) { var dates = resultVal[key]; for(var i = 0; i < dates.length; ++i) { // you logic here for each date console.log("resultVal[" + key + "]

Categories : Javascript

Digitally sign a hash value of a file directly instead of file
Well, it is of course possible to pass the hash to the client and sign it there, but the devil is in details -- in case of such distributed signing you need to design a really secure way to pass the hash and the signature and to sign it securely on the client side. Also you need to have the code on the server that will let you calculate the hash, pass it to the client and then embed the signature to the signing format of your choice. Our company has developed a Distributed Cryptography add-on to our SecureBlackbox product that addresses all of the above problems. For details you are welcome to check this answer on StackOverflow.

Categories : Java

javascript hash table pattern?
hasOwnProperty is correct but use Object.prototype.hasOwnProperty. Because if the property isn't "b" but "hasOwnProperty" you will probably get an error saying hasOwnProperty isn't a function. This is a neat little gotcha.

Categories : Javascript

Javascript. Convert MD5 hash into an integer
That looks like a hexadecimal number, so you could try using the parseInt function and pass in a base of sixteen: var num = parseInt(string, 16);

Categories : Javascript

Autohotkey Add Javascript Hash To Local URL
A_Desktop is the full path to your desktop ie. C:UsersusernameDesktop Try removing the file: in front. EDIT: This worked for me in Chrome and IE. It looks like you may not have had the right number of slashes as well as in the incorrect direction. #w:: Run % "file:///" . RegExReplace(A_Desktop " est.html?" clipboard, "(\)", "/") Return

Categories : Javascript

Passing hash data to javascript
There is no structure like that: { question_id: 14 => { club_id: 11 => { choice_id: 21 => 7, choice_id: 22 => 8 } You're trying to associate a hash value with further values, which is an invalid structure. One way to achieve a semantic structure (meaning a structure which reflects the actual relationships of your counts and id's to each other) for your data so you can pass it to the browser via JSON would be to build a hash like the following: { questions: [ { id: 14, clubs: [ { id: 11, choices: [ { id: 21, count: 7 }, { id: 22, count: 8 } ] } ] } ] }

Categories : Javascript

JavaScript window #hash actions
First your condition is wrong:- if(window.location.hash = "#Form"){alert("hi");} to if(window.location.hash == "#Form"){alert("hi");} Other thing you need to bind hashchange event. Not all browsers support this event. In that case you need to check hash changes using setInterval function of javascript.

Categories : Javascript

Javascript md5 hash of image to compare with Java
Finally got it! Thanks guys for your help and comments. For anyone else who stumbles upon this: Eventually found an MD5 script at: http://blog.faultylabs.com/?d=md5 that will allow me to pass in an arraybuffer and that resolved it. Or at least, gave me the desired result, Sounds like there is just a lot more trial and error with javascript as everything is handled a bit differently to other languages. Thanks again.

Categories : Java

How do I reload a page with an additional hash using javascript?
Try - location.reload(true); after you've changed the url - window.location.href = "http://www.mydomain.com/page1#test"; location.reload(true); Check out this example from MDN.

Categories : Javascript

Javascript cryptographic-hash-protected loader
If the CDN server is sending CORS headers, you can retrieve the file with XHR and verify the contents before evaluating it. Note that this is a big change from how the script element is usually executed synchronously: <script src="//google.com/jquery"></script> <script>//jQuery is available</script> The above will no longer be possible so if you have already written lots of code under the traditional sequential synchronous assumptions it might not be feasible If the CDN server is not sending CORS headers it is not possible to look at the contents. And I suppose any workarounds for this would defeat the purpose.

Categories : Javascript

Empty anchor tag value using hash or javascript in Angular
According to the AngularJS docs for the A directive, you should be using href="". The reasoning for this is to allow easy creation of action links with ngClick directive without changing the location or causing page reloads, e.g.: <a href="" ng-click="model.$save()">Save</a>

Categories : Angularjs

How to load hash in a loop using objects as keys in JavaScript?
Object keys in JavaScript can only be strings. This means that if you pass something that is not a string, it gets converted to a string. Since you're using objects that don't "override" Object.toString, they'll all have the same string representation (it's "[object Object]"), which is why the hash always refers to the last key used. More here: Strange equality issue with Javascript object properties

Categories : Javascript

Pass JavaScript object/hash to Handlebars helper?
Solved. I did this: Helper: Handlebars.registerHelper('textField', function(options) { var attributes = []; for (var attributeName in options.hash) { attributes.push(attributeName + '="' + options.hash[attributeName] + '"'); } return new Handlebars.SafeString('<input type="text" ' + attributes.join(' ') + ' />'); }); And the template: <label>Label here</label> {{textField id="text_field_1" class="some-class" size="30" data-something="data value"}} <p>Help text here.</p> Per the documentation (bottom of the page), you can pass in a variable number of parameters to a helper method, and they will be available in options.hash (assuming "options" is a parameter to your helper method). And what's also nice about this is that you can us

Categories : Javascript

Security in a Javascript based app -refreshing a users hash
Basicallly on the clients side you shouldnt have anything except hash. On the server side this hash must be associated with user it belongs to, expire time and anything else you need. Send this hash with each request, and on server side validate it. When it expires you have to send (server) appropriate headers like 401 - Unauthorized. Client have to understand that response and try to exchange hash to new one. And finally when client gets new valid hash it can resume sending requests. ... and you shouldnt check expire time at client, this job for server. thanks.

Categories : Javascript

How to extract Unique keys from a Hash Table in Javascript
something like this should do you right: Array.prototype.unique=function unique(){var r=this;var t=[];var mx=r.length;for (var z=0; z< mx; z++){if(t.indexOf(r[z])==-1){t[t.length]=r[z];}}return t;}; //ex usage: var name2=[1,2,3,4,3,2,1] name2.unique().map(function(key){ // write name in the side panel. // $('div.hidden').append('<p>' + key + '</p>').css("color", "white"); return key; }); // == [1,2,3,4] NOTE that the variable name "name" cannot bind to Array.prototype for some weird reason, but (almost) any other name will work. answer updated, tested. works on any array of primitives.

Categories : Javascript

Are there other ways to pass parameters to javascript other than document.location.hash?
The query string can also be used for this. Here's a little helper: var getQueryValue = (function () { var populated, queryArray = []; return function (key) { populated || populate(); return queryArray[key]; } function populate () { var pair, chunks, l, i = 0, queryString = window.location.href.split('?')[1]; populated = true; if ( ! queryString ) return; chunks = queryString.split('&'); l = chunks.length; for ( ; i < l; i++ ) { pair = chunks[i].split('='); queryArray[ pair[0] ] = pair[1]; } } }()); Use it as follows: var page = getQueryValue('page');

Categories : Javascript

Javascript RegEx pattern to have only alphanumeric and hash(#) symbol in the middle
You can use this: /^[a-z0-9]+#[a-z0-9]+$/i or this if you want an optional hash symbol: /^[a-z0-9]+#?[a-z0-9]+$/i or this for multiple hash symbol: /^[a-z0-9]+[a-z0-9#]+[a-z0-9]+$/i To check only one character (in cases # is optional): 2) /^[a-z0-9]+(?:#[a-z0-9]+)?$/i 3) /^[a-z0-9]+(?:[a-z0-9#]+[a-z0-9]+)?$/i

Categories : Regex

Remove hash from URL, load the page at hash-less URL, then add hash to URL without reloading the page
Before page loads, check URL and if it has #/, remove it. Not possible. The fragment id is not sent to the server, so you can only access it with client side code and that requires the page to load (or at least to start loading). Load page located at hash-less url Redisplay the url with #/, without reloading the page Use XMLHttpRequest to get the data, DOM to change the document to use it, and the history API to change the URL in the address bar.

Categories : Javascript

How can I replace hash tag on keydown event like twitter or facebook. javascript // jquery
You could save and restore the selection range by character index so long as the text content is remaining the same. I've provided simple functions to do this here: http://stackoverflow.com/a/17694760/96100

Categories : Javascript

download a file with php and hash
It's impossibly to tell you without the source code e.g. sha1("Test Message") gives you 35ee8386410d41d14b3f779fc95f4695f4851682 but sha256("Vote this up") gives you 65e03c456bcc3d71dde6b28d441f5a933f6f0eaf6222e578612f2982759378ed totally different... unless you're hidden function add's "65e03c456bcc3d71dde6b28dxxxxxxxxxxxxxxxxxxxxxxxxxx" (where xxxxxxxxxxxxxxxxxxxxxxxxxx is a bunch of numbers I can't be arsed to work out) to each hash... then sha1("Test Message") gives you 65e03c456bcc3d71dde6b28d441f5a933f6f0eaf6222e578612f2982759378ed

Categories : PHP

How to put data from CSV file to Perl hash
Huh? Why so complicated? First, we fetch the header outside of the loop: my $headers = $csv->getline($fh) or die "no header"; Assign these to be the column names: $csv->column_names(@$headers); Then, each call to getline_hr will provide a hashref: while (my $hashref = $csv->getline_hr($fh)) { push @$result, $hashref; } We can also use getline_hr_all: $result = $csv->getline_hr_all($fh); In other words, it ain't complex, most pieces are already provided by Text::CSV, and it can be done in very few lines. Also, a module like this seems to already exist: Text::CSV::Slurp. (note: reverse dependency search through metacpan is awesome)

Categories : Perl

Hash a file in Windows Store App c#
In Windows 8(Metro) hashing algorithm are under Windows.Security.Cryptography.Core. Check this link, it contains simple example of how to hash string in C#/Metro. http://msdn.microsoft.com/en-us/library/windows/apps/windows.security.cryptography.core.hashalgorithmnames.md5

Categories : C#

Split a complex file into a hash
OK I have it (almost). The only problem is it is adding a at the end of each value. puts 'Primer 3 hash' primer3 = {} while line = gets do key, value = line.split(/=/) puts key puts value primer3[key.downcase] = value end puts primer3 {"sequence_id"=>"example ", "sequence_template"=>"GTAGTCAGTAGACNATGACNACTGACGATGCAGACNACACACACACACACAGCACACAGGTATTAGTGGGCCATTCGATCCCGACCCAAATCGATAGCTACGATGACG ", "sequence_target"=>"37,21 ", "primer_task"=>"pick_detection_primers ", "primer_pick_left_primer"=>"1 ", "primer_pick_internal_oligo"=>"1 ", "primer_pick_right_primer"=>"1 ", "primer_opt_size"=>"18 ", "primer_min_size"=>"15 ", "primer_max_size"=>"21 ", "primer_max_ns_accepted"=>"1 ", "primer_product_size_range"=>"75-100 ", "p3_file_flag"=>"1 ", "se

Categories : Ruby

How to mock a hash with string keys in rspec which comes from a webservice in the new hash notation of ruby
If the hash is a string key, you're not able to use the new notation. Only with symbols. In the case that you'd really like to access using symbols, one option is to import Rails ActiveSupport and use their Indifferent Access functions. It adds another dependency to manage, but can help keep your code cleaner too.

Categories : Ruby

Ruby on Rails sorting hash of hashes based on value of child hash
There are two problems here: Enumerable#sort_by does not modify in place. You need to reassign the return value to @payrolls. You're constructing a Hash, not a HashWithIndifferentAccess. Since you're using string keys, you need to be consistent about that. Your #sort_by sorts by a symbol key. Try this: @payrolls = @payrolls.sort_by { |_, v| v['money_earned'] } Just to add some more information: The return value of this expression is actually not even a Hash. Here's an example: 1.9.3p392 :012 > { a: { q: 1 }, c: { q: 3 }, b: { q: 2 } }.sort_by { |_, v| v[:q] } => [[:a, {:q=>1}], [:b, {:q=>2}], [:c, {:q=>3}]] The cool part is that your view code will work anyway with no modification, even if it gets an array of arrays!

Categories : Ruby On Rails

Is a cryptographic hash susceptible to clustering on a hash table of non-prime modulus?
A cryptographic hash function should certainly be uniformly distributed in any modulus, prime or composite. If there were significant clustering for any modulus value, that would reduce the function's collision-resistance. The "usual advice" about using primes does not expect the prime to be 2, or any other smallish number. On the whole, the problem with using a composite is not so much that it's composite as that it has a small prime divisor, like 2.

Categories : Database

C++ hash function, how is the original haser i.e. hash implemented
A hash function must be deterministic -- i.e., the same input must always produce the same result. Generally speaking, you want the hash function to produce all outputs with about equal probability for arbitrary inputs (but while desirable, this is no mandatory -- and for any given hash function, there will always be an arbitrary number of inputs that produce identical outputs). Generally speaking, you want the hashing function to be fast, and to depend (to at least some degree) on the entirety of the input. A fairly frequently seen pattern is: start with some semi-random input. Combine one byte of input with the current value. Do something that will move the bits around (multiplication, rotation, etc.) Repeat for all bytes of the input.

Categories : C++

Flatten Hash while Iterating over hash's array elements. Ruby
This is long and complicated, but at least it works: my_hash = {:x => 333, :y => 13, :z => [1,2,{:zz => [40,50]},[10,20]], :a => {:o => "1", :p => "2"}} # Create Recursive function to get values: def advance_hash_flattener(input, parent=[]) case input when Hash then input.flat_map{|key, val| advance_hash_flattener(val, parent+[key])} when Array then input.flat_map{|x| advance_hash_flattener(x, parent)} else [parent.join('_>'), input] end end #Some small transformations for the last step: first_step = advance_hash_flattener(my_hash) .each_slice(2) .group_by{|x| x.first} .map{|x| [x.first, x.last.map(&:last)]} p first_step #=> [["x", [333]], ["y", [13]], ["z", [1, 2, 10, 20]], ["z_>zz", [40, 50]], ["a_>o", ["1"]], ["a_&

Categories : Ruby

How to deal with potential errors while accessing a hash inside a hash?
Use Hash#fetch with default value. h = {:a => 2} h.fetch(:b,"not present") # => "not present" h.fetch(:a,"not present") # => 2 Without default value it will throw KeyError. h = {:a => 2} h.fetch(:b) # ~> -:2:in `fetch': key not found: :b (KeyError) But with nested Hash like your one you can use : h = {:a => {:b => 3}} val = h[:a][:b] rescue nil # => 3 val = h[:a][:c] rescue nil # => nil val = h[:c][:b] rescue nil # => nil

Categories : Ruby

syntax for accessing hash param in hash of hashes when using foreach
The expression $export_types{$key}{label} assumes that there is a hash %export_types. This is not the case. If you had a use strict in scope, you would have been alerted to this fact. Because $export_types is a hash reference, we have to dereference it before using the subscript operator to access some value. Either $export_types->{$key}{label} or $$export_types{$key}{label} (I prefer the former).

Categories : HTML

How do I have Ruby YAML dump a Hash subclass as a simple Hash?
You can achieve this with the (poorly documented) encode_with and represent_map methods. To customise the YAML serialisation of an object you provide it with an encode_with method which accepts a coder object, one of the methods on which is represent_map. class Foo < Hash # other methods ... def encode_with coder coder.represent_map nil, self end end Now YAML.dump will just output your object as a normal hash. However There is a bit of a problem because there is a bug that will cause this to fail and is only fixed in the latest Gem version of Psych. It is not fixed in the current latest Ruby version (ruby 2.0.0p247). It is fixed in Ruby trunk so later patch releases should be okay. In order to use this you will have to make sure you are using the latest Psych Gem, rat

Categories : Ruby

Convert collection of hash maps to a csv file
Use data.json to convert the json to a sequence of clojure maps. Use map destructuring to convert to a sequence of strings: (map #(let [{a :a b :b c :c d :d} %] (str a "," b "," c "," d, " ")) <your sequence of clojure maps>). Dump the sequence of strings to a file

Categories : Clojure

Embed git hash into python file when installing
Another, possibly simpler way to do it, using gitpython, as in dd/setup.py: def git_version(version): try: import git repo = git.Repo('.git') except ImportError: print('gitpython not found: Assume release.') return '' try: repo.git.status() except git.GitCommandNotFound: print('git not found: Assume release.') return '' sha = repo.head.commit.hexsha if repo.is_dirty(): return '.dev0+{sha}.dirty'.format(sha=sha) # commit is clean # is it release of `version` ? try: tag = repo.git.describe( match='v[0-9]*', exact_match=True, tags=True, dirty=True) assert tag[1:] == version, (tag, version) return '' except git.GitCommandError: return

Categories : Python

How to read and calculate hash of file on the internet
If you pass it through a DigestInputStream, it'll do the MessageDigest and still be usable as an InputStream. DigestInputStream dis = new DigestInputStream(is, MessageDigest.getInstance(SHA1)); BufferedInputStream bis = new BufferedInputStream(dis); BufferedOutputStream bos = new BufferedOutputStream( new FileOutputStream(file.getName())); while ((i = bis.read()) != -1) { bos.write(i); } bos.close(); return dis.getMessageDigest().digest();

Categories : Java

How to convert HTML file into a hash in Perl?
HTML::TreeBuilder::XPath gives you a lot more power than a simple hash would. From the synopsis: use HTML::TreeBuilder::XPath; my $tree = HTML::TreeBuilder::XPath->new; $tree->parse_file( "mypage.html"); my $nb=$tree->findvalue('/html/body//p[@class="section_title"]/span[@class="nb"]'); my $id=$tree->findvalue('/html/body//p[@class="section_title"]/@id'); my $p= $html->findnodes('//p[@id="toto"]')->[0]; my $link_texts= $p->findvalue( './a'); # the texts of all a elements in $p $tree->delete; # to avoid memory leaks, if you parse many HTML documents More on XPath.

Categories : Perl



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