def test_compare(self): u1 = uri.URI("x-HTTP://www.example.com/") u2 = uri.URI("x-http://www.example.com/") self.assertTrue( u1.match(u2) and u2.match(u1), "Equal URIs fail to match") self.assertTrue(u1 == u2, "Equal URIs compare equal") self.assertFalse(u1 != u2, "Equal URIs compare not equal") self.assertTrue(u1 <= u2, "Equal URIs sort less-equal") self.assertTrue(u1 >= u2, "Equal URIs sort greater-equal") self.assertFalse(u1 < u2, "Equal URIs sort less than") self.assertFalse(u1 > u2, "Equal URIs sort greater than") self.assertTrue(hash(u1) == hash(u2), "Equal URIs, equal hash") u2 = uri.URI('hello.xml') self.assertFalse( u1.match(u2) or u2.match(u1), "Mismatched URIs do match") u1 = uri.URI("x-HTTP://www.example.com/") u2 = uri.URI("x-http://www2.example.com/") self.assertFalse( u1.match(u2) or u2.match(u1), "Equal URIs fail to match") self.assertFalse(u1 == u2, "Unequal URIs compare equal") self.assertTrue(u1 != u2, "Unequal URIs compare not-equal") self.assertTrue(u1 <= u2, "Unequal URIs sort less-equal") self.assertFalse(u1 >= u2, "Unequal URIs sort greater-equal") self.assertTrue(u1 < u2, "Unequal URIs sort less than") self.assertFalse(u1 > u2, "Unequal URIs sort greater than") self.assertFalse(hash(u1) == hash(u2), "Unequal URIs, Unequal hash") # check comparison against strings u2 = "x-http://www3.example.com/" self.assertFalse(u1 == u2, "Unequal URIs compare equal") self.assertTrue(u1 != u2, "Unequal URIs compare not-equal") self.assertTrue(u1 <= u2, "Unequal URIs sort less-equal") self.assertFalse(u1 >= u2, "Unequal URIs sort greater-equal") self.assertTrue(u1 < u2, "Unequal URIs sort less than") self.assertFalse(u1 > u2, "Unequal URIs sort greater than")
def __call__(cls, *args, **kwargs): """ Custom class instantiation utilizing instance cache. If a Task has already been instantiated with the same parameters, the previous instance is returned to reduce number of object instances.""" def instantiate(): return super(Register, cls).__call__(*args, **kwargs) h = Register.__instance_cache if h == None: # disabled return instantiate() params = cls.get_params() param_values = cls.get_param_values(params, args, kwargs) k = (cls, tuple(param_values)) try: hash(k) except TypeError: logger.debug("Not all parameter values are hashable so instance isn't coming from the cache") return instantiate() # unhashable types in parameters if k not in h: h[k] = instantiate() return h[k]
def __hash__(self): h = hash(self.__class__) for attr in ("service", "recordType", "shortNames", "guid", "enabled", "enabledForCalendaring"): h = (h + hash(getattr(self, attr))) & sys.maxint return h
def __hash__(self): hashables = (self.address, self.port) result = 0 for value in hashables: result = 33*result + hash(value) return hash(result)
def populate_ds(self, ds): s = self.spectrum name = "const" + str(hash(self)) + "spectrum" ds[name] = (s.r, s.g, s.b, 0.0) if self.k is not None: name = "const" + str(hash(self)) + "k" ds[name] = (self.k, self.k, self.k, 0.0)
def _all_commands(self): path = builtins.__xonsh_env__.get('PATH', []) # did PATH change? path_hash = hash(tuple(path)) cache_valid = path_hash == self._path_checksum self._path_checksum = path_hash # did aliases change? al_hash = hash(tuple(sorted(builtins.aliases.keys()))) self._alias_checksum = al_hash cache_valid = cache_valid and al_hash == self._alias_checksum pm = self._path_mtime # did the contents of any directory in PATH change? for d in filter(os.path.isdir, path): m = os.stat(d).st_mtime if m > pm: pm = m cache_valid = False self._path_mtime = pm if cache_valid: return self._cmds_cache allcmds = set() for d in filter(os.path.isdir, path): allcmds |= set(os.listdir(d)) allcmds |= set(builtins.aliases.keys()) self._cmds_cache = frozenset(allcmds) return self._cmds_cache
def register_handler(self, event_class, handler, context=None, filter=None): """Registers a handler on a specific event type. Multiple handlers may be registered on a single event type and are guaranteed to be called in order of registration. The handler takes two arguments, the event object and the corresponding wavelet. Args: event_class: An event to listen for from the classes defined in the events module. handler: A function handler which takes two arguments, the wavelet for the event and the event object. context: The context to provide for this handler. filter: Depending on the event, a filter can be specified that restricts for which values the event handler will be called from the server. Valuable to restrict the amount of traffic send to the robot. """ payload = (handler, event_class, context, filter) self._handlers.setdefault(event_class.type, []).append(payload) if type(context) == list: context = ','.join(context) self._capability_hash = (self._capability_hash * 13 + hash(ops.PROTOCOL_VERSION) + hash(event_class.type) + hash(context) + hash(filter)) & 0xfffffff
def test_hash_vs_equality(self): # make sure that we satisfy is semantics dtype = self.dtype dtype2 = IntervalDtype('int64') dtype3 = IntervalDtype(dtype2) assert dtype == dtype2 assert dtype2 == dtype assert dtype3 == dtype assert dtype is dtype2 assert dtype2 is dtype3 assert dtype3 is dtype assert hash(dtype) == hash(dtype2) assert hash(dtype) == hash(dtype3) dtype1 = IntervalDtype('interval') dtype2 = IntervalDtype(dtype1) dtype3 = IntervalDtype('interval') assert dtype2 == dtype1 assert dtype2 == dtype2 assert dtype2 == dtype3 assert dtype2 is dtype1 assert dtype2 is dtype2 assert dtype2 is dtype3 assert hash(dtype2) == hash(dtype1) assert hash(dtype2) == hash(dtype2) assert hash(dtype2) == hash(dtype3)
def test_attr_hash(): a1 = SA1(1) a2 = SA1(1) a3 = SA1(3) assert hash(a1) == hash(a2) assert hash(a3) != hash(a1)
def test_eq(self): tlid = 123 track = Track() tl_track1 = TlTrack(tlid=tlid, track=track) tl_track2 = TlTrack(tlid=tlid, track=track) self.assertEqual(tl_track1, tl_track2) self.assertEqual(hash(tl_track1), hash(tl_track2))
def test_curry_comparable(): def foo(a, b, c=1): return a + b + c f1 = curry(foo, 1, c=2) f2 = curry(foo, 1, c=2) g1 = curry(foo, 1, c=3) h1 = curry(foo, c=2) h2 = h1(c=2) h3 = h1() assert f1 == f2 assert not (f1 != f2) assert f1 != g1 assert not (f1 == g1) assert f1 != h1 assert h1 == h2 assert h1 == h3 # test function comparison works def bar(a, b, c=1): return a + b + c b1 = curry(bar, 1, c=2) assert b1 != f1 assert set([f1, f2, g1, h1, h2, h3, b1, b1()]) == set([f1, g1, h1, b1]) # test unhashable input unhash1 = curry(foo, []) assert raises(TypeError, lambda: hash(unhash1)) unhash2 = curry(foo, c=[]) assert raises(TypeError, lambda: hash(unhash2))
def test_eq(self): date = "1977-01-01" artists = [Artist()] album = Album() track1 = Track( uri="uri", name="name", artists=artists, album=album, track_no=1, date=date, length=100, bitrate=100, musicbrainz_id="id", ) track2 = Track( uri="uri", name="name", artists=artists, album=album, track_no=1, date=date, length=100, bitrate=100, musicbrainz_id="id", ) self.assertEqual(track1, track2) self.assertEqual(hash(track1), hash(track2))
def test_ne(self): track1 = Track( uri="uri1", name="name1", artists=[Artist(name="name1")], album=Album(name="name1"), track_no=1, date="1977-01-01", length=100, bitrate=100, musicbrainz_id="id1", ) track2 = Track( uri="uri2", name="name2", artists=[Artist(name="name2")], album=Album(name="name2"), track_no=2, date="1977-01-02", length=200, bitrate=200, musicbrainz_id="id2", ) self.assertNotEqual(track1, track2) self.assertNotEqual(hash(track1), hash(track2))
def test_eq_artists_order(self): artist1 = Artist(name="name1") artist2 = Artist(name="name2") album1 = Album(artists=[artist1, artist2]) album2 = Album(artists=[artist2, artist1]) self.assertEqual(album1, album2) self.assertEqual(hash(album1), hash(album2))
def test_eq_artists_order(self): artist1 = Artist(name="name1") artist2 = Artist(name="name2") track1 = Track(artists=[artist1, artist2]) track2 = Track(artists=[artist2, artist1]) self.assertEqual(track1, track2) self.assertEqual(hash(track1), hash(track2))
def test_check_equality(self, testdir): modcol = testdir.getmodulecol(""" def test_pass(): pass def test_fail(): assert 0 """) fn1 = testdir.collect_by_name(modcol, "test_pass") assert isinstance(fn1, pytest.Function) fn2 = testdir.collect_by_name(modcol, "test_pass") assert isinstance(fn2, pytest.Function) assert fn1 == fn2 assert fn1 != modcol if py.std.sys.version_info < (3, 0): assert cmp(fn1, fn2) == 0 assert hash(fn1) == hash(fn2) fn3 = testdir.collect_by_name(modcol, "test_fail") assert isinstance(fn3, pytest.Function) assert not (fn1 == fn3) assert fn1 != fn3 for fn in fn1,fn2,fn3: assert fn != 3 assert fn != modcol assert fn != [1,2,3] assert [1,2,3] != fn assert modcol != fn
def __hash__(self): "Here we pretend Vecs are immutable so we can form sets of them" h = hash(frozenset(self.D)) for k,v in sorted(self.f.items(), key = lambda x:repr(x[0])): if v != 0: h = hash((h, hash(v))) return h
def test_method(): class C: def method(self): pass method = type(C.method)(id, None, 'abc') AreEqual(method.im_class, 'abc') class myobj: def __init__(self, val): self.val = val self.called = [] def __hash__(self): self.called.append('hash') return hash(self.val) def __eq__(self, other): self.called.append('eq') return self.val == other.val def __call__(*args): pass func1, func2 = myobj(2), myobj(2) inst1, inst2 = myobj(3), myobj(3) method = type(C().method) m1 = method(func1, inst1) m2 = method(func2, inst2) AreEqual(m1, m2) Assert('eq' in func1.called) Assert('eq' in inst1.called) hash(m1) Assert('hash' in func1.called) Assert('hash' in inst1.called)
def test_fractions(self): # check special case for fractions where either the numerator # or the denominator is a multiple of _PyHASH_MODULUS self.assertEqual(hash(F(1, _PyHASH_MODULUS)), _PyHASH_INF) self.assertEqual(hash(F(-1, 3*_PyHASH_MODULUS)), -_PyHASH_INF) self.assertEqual(hash(F(7*_PyHASH_MODULUS, 1)), 0) self.assertEqual(hash(F(-_PyHASH_MODULUS, 1)), 0)
def getID(self,name): if name=='' or name in self.names: self.forId=self.forId+1 id=abs(hash(self.forId)) else: id=str(abs(hash(name))) if not name in self.names: self.names.append(name) return id
def assert_hashable(*args, **kw): """ Verify that each argument is hashable. Passes silently if successful. Raises descriptive TypeError otherwise. Example:: >>> assert_hashable(1, 'foo', bar='baz') >>> assert_hashable(1, [], baz='baz') Traceback (most recent call last): ... TypeError: Argument in position 1 is not hashable: [] >>> assert_hashable(1, 'foo', bar=[]) Traceback (most recent call last): ... TypeError: Keyword argument 'bar' is not hashable: [] """ try: for i, arg in enumerate(args): hash(arg) except TypeError: raise TypeError('Argument in position %d is not hashable: %r' % (i, arg)) try: for key, val in iterate_items(kw): hash(val) except TypeError: raise TypeError('Keyword argument %r is not hashable: %r' % (key, val))
def dot(self): """Output the graphviz script""" out = """ digraph asm_graph { size="80,50"; node [ fontsize = "16", shape = "box" ]; """ all_lbls = {} for lbl in self.nodes(): if lbl not in self._blocks: continue irb = self._blocks[lbl] ir_txt = [str(lbl)] for irs in irb.irs: for l in irs: ir_txt.append(str(l)) ir_txt.append("") ir_txt.append("") all_lbls[hash(lbl)] = "\l\\\n".join(ir_txt) for l, v in all_lbls.items(): out += '%s [label="%s"];\n' % (l, v) for a, b in self.edges(): out += '%s -> %s;\n' % (hash(a), hash(b)) out += '}' return out
def test_UnknownType(self): self._TestCppType(self.tUnknown) self.assertEqual(self.tUnknown, Tf.Type.FindByName('bogus')) self.assertFalse(self.tUnknown.baseTypes) self.assertFalse(self.tUnknown.derivedTypes) self.assertFalse(self.tUnknown.IsA(Tf.Type.GetRoot())) self.assertEqual(hash(self.tUnknown), hash(Tf.Type.FindByName('bogus')))
def __init__(self, name, content, color, symbol): self.name = name self.name_hash = hash(name) self.content = content self.content_hash = hash(content) self.text_color = color self.symbol = symbol
def validate_spec(index, spec): """ Validate the value for a parameter specialization. This validator ensures that the value is hashable and not None. Parameters ---------- index : int The integer index of the parameter being specialized. spec : object The parameter specialization. Returns ------- result : object The validated specialization object. """ if spec is None: msg = "cannot specialize template parameter %d with None" raise TypeError(msg % index) try: hash(spec) except TypeError: msg = "template parameter %d has unhashable type: '%s'" raise TypeError(msg % (index, type(spec).__name__)) return spec
def test_eq(self): c = tflow.tclient_conn() c2 = c.copy() assert c == c assert c != c2 assert c != 42 assert hash(c) != hash(c2)
def testHashability(self): """RDFValue instances need to act as keys in a dict.""" sample1 = self.GenerateSample(1) # Different instances with the same value need to hash to the same. self.assertTrue(hash(sample1) == hash(self.GenerateSample(1))) self.assertTrue(hash(sample1) != hash(self.GenerateSample(2)))
def test_creation(): metaedge_tuples = [ ('compound', 'disease', 'indication', 'both'), ('disease', 'gene', 'association', 'both'), ('compound', 'gene', 'target', 'both'), ] metanode_ids = 'compound', 'disease', 'gene' metagraph = graph.MetaGraph.from_edge_tuples(metaedge_tuples) # check that nodes got added to metagraph_node_dict assert frozenset(metagraph.node_dict) == frozenset(metanode_ids) for metanode in metagraph.node_dict.values(): assert isinstance(metanode, graph.MetaNode) # check that metanode.get_id() and hash(metanode) are working as expected for metanode_id in metanode_ids: metanode = metagraph.node_dict[metanode_id] assert metanode.identifier == metanode_id assert metanode.get_id() == metanode_id assert hash(metanode) == hash(metanode_id) g = graph.Graph(metagraph) ms = g.add_node('disease', 'DOID:2377', 'multiple sclerosis') assert ms.metanode.identifier == 'disease' assert ms.identifier == 'DOID:2377' assert ms.name == 'multiple sclerosis' with pytest.raises(KeyError): # misordered args g.add_node('DOID:2377', 'multiple sclerosis', 'disease')
def scanfiles(self): for root, dirs, files in os.walk("files"): for file_ in files: check = root+"/"+file_ if check not in self.files: try: self.files[check] = hash(open(check).read()) sock = socket.socket() sock.connect((self.host, self.port)) upload.upload(sock, check, self.username, self.password) print "{0} Outgoing file transfer {1}".format(datetime.datetime.now(), check) except Exception, e: #print e del self.files[check] time.sleep(0.5) else: with open(check, 'rb') as file: hashc = hash(file.read()) if hashc != self.files[check]: try: sock = socket.socket() sock.connect((self.host, self.port)) upload.upload(sock, check, self.username, self.password) print "{0} Outgoing file transfer {1}".format(datetime.datetime.now(), check) self.files[check] = hash(open(check).read()) except Exception, e: pass time.sleep(0.5)
def test_make_proxy_disc(self): abc = DiscreteVariable("abc", values="abc", ordered=True) abc1 = abc.make_proxy() abc2 = abc1.make_proxy() self.assertIs(abc.master, abc) self.assertIs(abc1.master, abc) self.assertIs(abc2.master, abc) self.assertEqual(abc, abc1) self.assertEqual(abc, abc2) self.assertEqual(abc1, abc2) self.assertEqual(hash(abc), hash(abc1)) self.assertEqual(hash(abc1), hash(abc2)) abcx = DiscreteVariable("abc", values="abc", ordered=True) self.assertNotEqual(abc, abcx) abc1p = pickle.loads(pickle.dumps(abc1)) self.assertIs(abc1p.master, abc) self.assertEqual(abc1p, abc) abcp, abc1p, abc2p = pickle.loads(pickle.dumps((abc, abc1, abc2))) self.assertIs(abcp.master, abcp.master) self.assertIs(abc1p.master, abcp.master) self.assertIs(abc2p.master, abcp.master) self.assertEqual(abcp, abc1p) self.assertEqual(abcp, abc2p) self.assertEqual(abc1p, abc2p)
ERROR = "Wrong password, try again\n" SUCCESS = "Login successful!\nFlag: sdctf_ok_test\n" PASSWD = "59784015375233083673486266" def hash(data): out = 0 for c in data: out *= 31 out += ord(c) return str(out) with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.bind((HOST, PORT)) s.listen() while True: conn, addr = s.accept() with conn: print('Connected by', addr) conn.sendall("Please enter password below\n".encode('utf-8')) while True: data = conn.recv(1024).decode() if not data: break if hash(data) == PASSWD: conn.sendall(SUCCESS.encode('utf-8')) break else: conn.sendall(ERROR.encode('utf-8'))
def __hash__(self): return hash(self.fullpath())
def __hash__(self): return hash(self.eggs)
def processUniqueID(self): return hash((self.realm.name, self.avatar.name, self.group.name))
def __hash__(self): elements = self.hash_elements return reduce(self.commut_assoc_func, (hash(x) for x in elements), 1)
def __hash__(self): return hash(self.string)
def _get_thread_context(): context = [threading.current_thread()] if greenlet: context.append(greenlet.getcurrent()) return hash(tuple(context))
def __eq__(self, other): return hash(self) == hash(other) if isinstance(other, ConfigOption) else False
def __hash__(self): return hash(self._key)
def __eq__(self, other): return hash(self) == hash(other) if isinstance(other, Manual) else False
def __hash__(self): t, d = self return hash((type(self), t, d.shape, self.sum))
def __hash__(self): return hash((self.ip, self.port, self.id))
def __hash__(self): return hash(self.s, self.i, self.j, self.k)
def __hash__(self): return hash((self.title, self.isbn))
def test_hash_error(self, indices): index = indices with pytest.raises(TypeError, match=("unhashable type: %r" % type(index).__name__)): hash(indices)
def hash_shard(word): """Assign data to servers using Python's built-in hash() function.""" return 'server%d' % (hash(word) % 4)
def block6(block5): # graph should look like this: 5 <- 6 return Block(hash(block5) + 1, {hash(block5)})
def __hash__(self): return hash(type(self))
def block4(genesis, block3): # graph should look like this: 0 <- 4 return Block(hash(block3) + 1, {hash(genesis)})
def block7(block3, block6): # graph should look like this: 3 <- 7 return Block(hash(block6) + 1, {hash(block3)})
def block2(genesis, block1): # graph should look like this: 0 <- 2 return Block(hash(block1) + 1, {hash(genesis)})
def block5(block4): # graph should look like this: 4 <- 5 return Block(hash(block4) + 1, {hash(block4)})
def block9(block8): # graph should look like this: 8 <- 9 return Block(hash(block8) + 1, {hash(block8)})
def block3(block1, block2): # graph should look like this: 1, 2 <- 3 return Block(hash(block2) + 1, {hash(block1), hash(block2)})
def test_tensor_hashing(): # Tensors are unhashable with pytest.raises(TypeError, match="unhashable"): hash(pa.Tensor.from_numpy(np.arange(10)))
def block1(genesis): # graph should look like this: 0 <- 1 return Block(hash(genesis) + 1, {hash(genesis)})
def __hash__(self): """Override the default hash behavior (that returns the id or the object)""" return hash(tuple([self.type, self.dangling_ptr]))
def block8(block7): # graph should look like this: 7 <- 8 return Block(hash(block7) + 1, {hash(block7)})
def __hash__(self): """Override the default hash behavior (that returns the id or the object)""" return hash(tuple(sorted(self.__dict__.items())))
def __hash__(self): """Override the default hash behavior (that returns the id or the object)""" return hash((self.dangling_ptr, self.free, self.use))