text
stringlengths
48
9.16k
def file_size(file_path): """Returns the byte size of a file at ``file_path``. """ stat = os.stat(file_path) assert stat_fn.S_ISDIR(stat.st_mode) == False return stat.st_size
def _on_word(self, word): self.last_decoder_message = time.time() if word != "<#s>": if len(self.partial_transcript) > 0: self.partial_transcript += " " self.partial_transcript += word logger.debug("%s: Postprocessing partial result.." % self.request_id) processed_tr...
def bin_based_cvm(y_pred, sample_weight, bin_indices): """Cramer-von Mises similarity, quite slow meanwhile""" assert len(y_pred) == len(sample_weight) == len(bin_indices) bin_weights = compute_bin_weights(bin_indices=bin_indices, sample_weight=sample_weight) result = 0. global_data, global_weight,...
def test_expressions(): exprs = [ lambda a, b, c: a + b + c, lambda a, b, c: a - b - c, lambda a, b, c: a * b * c, lambda a, b, c: a / b / c, lambda a, b, c: a + b - c, lambda a, b, c: a - b + c, lambda a, b, c: a + b + (-c), lambda a, b, c: a + b*a + ...
def norm_html_from_html(html): """Normalize (somewhat) Markdown'd HTML. Part of Markdown'ing involves obfuscating email links with randomize encoding. Undo that obfuscation. Also normalize EOLs. """ if not isinstance(html, unicode): html = html.decode('utf-8') html = _markdown_emai...
def require(self, env=None, installer=None): if self.extras and not self.dist: raise UnknownExtra("Can't require() without a distribution", self) reqs = self.dist.requires(self.extras) items = working_set.resolve(reqs, env, installer) list(map(working_set.add, items))
def __setstate__(state): g = globals() for k, v in state.items(): g['_sset_'+_state_vars[k]](k, g[k], v) return state
def __repr__(self): if self.tag==self.__class__.tag: return self.__class__.__name__+"()" else: return self.__class__.__name__+"(tag=%d)"%self.tag
def switch(self, dest, url, rev_options): self.run_command(['switch'] + rev_options + [url, dest])
def name_that_thing(thing): """ Returns either the function/class path or just the object's repr """ # Instance method if hasattr(thing, "im_class"): return name_that_thing(thing.im_class) + "." + thing.im_func.func_name # Other named thing if hasattr(thing, "__name__"): if h...
def stop(self): if self.max is not None: self.update(self.max) self.done = True
def add_filters(self, filterer, filters): """Add filters to a filterer from a list of names.""" for f in filters: try: filterer.addFilter(self.config['filters'][f]) except StandardError as e: raise ValueError('Unable to add filter %r: %s' % (f, e))
def _version2fieldlist(version): if version == '1.0': return _241_FIELDS elif version == '1.1': return _314_FIELDS elif version == '1.2': return _345_FIELDS elif version == '2.0': return _426_FIELDS raise MetadataUnrecognizedVersionError(version)
def _get_index_urls_locations(self, project_name): """Returns the locations found via self.index_urls Checks the url_name on the main (first in the list) index and use this url_name to produce all locations """ def mkurl_pypi_url(url): loc = posixpath.join(url, project_url_name) # ...
@classmethod def run_file_cmd(cls, filename): """ return a 3-tuple of strings containing: the command to run (list) environment variables to be passed to command (dictionary or None) data to be piped into stdin (file-like object or None) """ port_number = str(cls.config.get('port...
def UP(self, n=1): return CSI + str(n) + "A"
def test_pop(self): x = DoubleList() for i in range(5): x.append(i) for i in range(5): a = x.pop() self.assertEqual(a, 5 - i - 1) self.assertEqual(len(x), 5 - i - 1) with self.assertRaises(IndexError): x.pop()
def check_iter_range(self, runs, value): for interval in range(1, len(value)): it = runs.get_run_iterator() for start in range(0, len(value), interval): end = min(start + interval, len(value)) for s, e, style in it.ranges(start, end): for v in value[s:e]: ...
def _parseUserPass(self): try: # Parse out data ver, ulen = struct.unpack('BB', self.buf[:2]) uname, = struct.unpack('%ds' % ulen, self.buf[2:ulen + 2]) plen, = struct.unpack('B', self.buf[ulen + 2]) password, = struct.unpack('%ds' % plen, self.buf[ulen + 3:ulen + 3 + plen]) ...
def summary_pyval_repr(self, max_len=None): """ Return a single-line formatted representation of the Python object described by this C{ValueDoc}. This representation may include data from introspection or parsing, and is authorative as 'the best way to summarize a Python value.' If the represe...
def update(self, dt): if self.is_rotating or self.index_diff: increment = self.direction * self.speed * self.float_increment * dt self.float_index = (self.float_index + increment) % self.num_tiles if self.index_diff: self.index_diff -= abs(increment) if self....
@feature('cxx') @after('apply_lib_vars') def apply_defines_cxx(self): """after uselib is set for CXXDEFINES""" self.defines = getattr(self, 'defines', []) lst = self.to_list(self.defines) + self.to_list(self.env['CXXDEFINES']) milst = [] # now process the local defines for defi in lst: if not defi in milst: ...
def clone(self, env): "" newobj = task_gen(bld=self.bld) for x in self.__dict__: if x in ['env', 'bld']: continue elif x in ["path", "features"]: setattr(newobj, x, getattr(self, x)) else: setattr(newobj, x, copy.copy(getattr(self, x))) newobj.__class__ = self.__class__ if isinstance(env, str): n...
def update_bars(): for bar in bars: old_length = bar.count length = random.randint(MIN_BAR_LENGTH, MAX_BAR_LENGTH) bar.resize(length) vertices = bar.vertices # Update new vertices (overwrite old degenerate) for i in range((old_length - 1) * 2, length * 2): ...
def _reconstruct_sub(self, offset, xstep, ystep): """ Reverse sub filter. """ pixels = self.pixels a_offset = offset offset += self.psize * xstep if xstep == 1: for index in range(self.psize, self.row_bytes): x = pixels[offset] a = pixels[a_offset] ...
def timestamp_to_avbin(timestamp): return int(timestamp * 1000000)
def visit_struct(self, struct): if struct.tag in self.structs: return self.structs.add(struct.tag) base = {True: 'Union', False: 'Structure'}[struct.is_union] print >> self.file, 'class struct_%s(%s):' % (struct.tag, base) print >> self.file, ' __slots__ = [' if not struct.op...
def _u_in(self, u): return u >= 0.0 and u <= 1.0
def destroy(self): '''Release the context. The context will not be useable after being destroyed. Each platform has its own convention for releasing the context and the buffer(s) that depend on it in the correct order; this should never be called by an application. ''' self.detach() i...
def exec_test(self): status = 0 variant = self.env.variant() filename = self.inputs[0].abspath(self.env) try: fu = getattr(self.generator.bld, 'all_test_paths') except AttributeError: fu = os.environ.copy() self.generator.bld.all_test_paths = fu lst = [] for obj in self.generator.bld.all_task_gen: ...
def blit_to_texture(self, target, level, x, y, z): glReadBuffer(self.gl_buffer) glCopyTexSubImage2D(target, level, x - self.anchor_x, y - self.anchor_y, self.x, self.y, self.width, self.height)
def must_introspect(self, name): """ Return C{True} if a module is to be introsepcted with the current settings. @param name: The name of the module to test @type name: L{DottedName} or C{str} """ return self.introspect \ and not self._matches_filter(name, self._introspect_regexp)
def t_error(t): if " " in t.value: idx = t.value.index(" ") error_loc = (t.value[:idx], t.lexer.lexpos, t.lexer.lineno) t.lexer.errors.append(error_loc) t.lexer.skip(idx) else: error_loc = (t.value, t.lexer.lexpos, t.lexer.lineno) t.lexer.errors.append(error_loc) ...
def on_recreate_immediate(self, changes): # The actual _recreate function. if ('context' in changes): self.context.detach() self._create()
def equality_rewrite(node, name, expr, assumed_result): # Get the literal and static compare values static_value = expr.right.value is_static = expr.right.static # Do we 'know' the value to be something # specific, or can we just eliminate a possible value. if expr.type in EQUALITY: kno...
def decorate(func): name = event_name or func.__name__ if name not in GUIEventDispatcher.event_types: raise EventException('Unknown event "%s"' % name) for r in rule.split(','): selector = Selector.from_string(r.strip()) GUIEventDispatcher.set_default_handler(name, selector, func) ...
def is_classmethod(instancemethod): " Determine if an instancemethod is a classmethod. " return instancemethod.im_self is not None
def _propgetpixelwidth(self): return self.width * self._cellwidth
def mean(a, weights=None, dim=None): if dim is not None: out = Array() if weights is None: safe_call(backend.get().af_mean(ct.pointer(out.arr), a.arr, ct.c_int(dim))) else: safe_call(backend.get().af_mean_weighted(ct.pointer(out.arr), a.arr, weights.arr, ct.c_int(dim...
def user_docfields(api_doc, docindex): """ Return a list of user defined fields that can be used for the given object. This list is taken from the given C{api_doc}, and any of its containing C{NamepaceDoc}s. @note: We assume here that a parent's docstring will always be parsed before its c...
def test_last_option_updated_up_releated_api_params(index_data): index_data['aws']['commands'] = ['ec2'] index_data['aws']['children'] = { 'ec2': { 'commands': ['create-tags'], 'argument_metadata': {}, 'arguments': [], 'children': { 'create...
def _set_text_property(self, name, value, allow_utf8=True): atom = xlib.XInternAtom(self._x_display, asbytes(name), False) if not atom: raise XlibException('Undefined atom "%s"' % name) assert type(value) in (str, unicode) property = xlib.XTextProperty() if _have_utf8 and allow_utf8: ...
def savememo(memo,good,bad,skipped): f = open(memo,'w') try: for n,l in [('good',good),('bad',bad),('skipped',skipped)]: print >>f,"%s = [" % n for x in l: print >>f," %r," % x print >>f," ]" finally: f.close()
def __getattr__(self, attr): value = self._d.setdefault(attr, 0) self._d[attr] = value + 1 return Bucket(value)
@iterate(1000) def testRandomContains(self): prefixes = [random_ipv4_prefix() for i in xrange(random.randrange(50))] question = random_ipv4_prefix() answer = any(question in pfx for pfx in prefixes) ipset = IPy.IPSet(prefixes) self.assertEqual(question in ipset, answer, "%s in %s != %s (...
def format_roman(self, case, counter): ones = ['i', 'x', 'c', 'm'] fives = ['v', 'l', 'd'] label, index = '', 0 # This will die of IndexError when counter is too big while counter > 0: counter, x = divmod(counter, 10) if x == 9: label = ones[index] + ones[index+1] + label...
def _propsetpixelheight(self, value): newheight = int(int(value) / self._cellheight) if newheight != self._height: self.resize(newheight=newheight)
def ddpop(self, bl=0): self.formatter.end_paragraph(bl) if self.list_stack: if self.list_stack[-1][0] == 'dd': del self.list_stack[-1] self.formatter.pop_margin()
def parse(self, source): source = prepare_input_source(source) self.prepareParser(source) self._cont_handler.startDocument() # FIXME: what about char-stream? inf = source.getByteStream() buffer = inf.read(16384) while buffer != "": self.feed(buffer) buffer = inf.read(16384)...
def abspath(path): """Return the absolute version of a path.""" if not isabs(path): if isinstance(path, unicode): cwd = os.getcwdu() else: cwd = os.getcwd() path = join(cwd, path) if not splitunc(path)[0] and not splitdrive(path)[0]: # cwd lacks a UNC ...
def test_cmptypes(self): # Built-in tp_compare slots expect their arguments to have the # same type, but a user-defined __coerce__ doesn't have to obey. # SF #980352 evil_coercer = CoerceTo(42) # Make sure these don't crash any more self.assertNotEqual(cmp(u'fish', evil_coercer), 0) self.ass...
def get_qualified_path(name): """ return a more qualified path to name""" import sys import os path = sys.path try: path = [os.path.dirname(__file__)] + path except NameError: pass for dir in path: fullname = os.path.join(dir, name) if os.path.exists(fullname)...
def monkeypatched_call_command(name, *args, **options): # XXX: Find a better way to detect a DB connection using # django-pydobc and do our monkeypatching only in such cases if name == 'loaddata' and Query.__name__ == 'PyOdbcSSQuery': name = 'ss_loaddata' return real_call_command(name, *args, **...
def test_poll(self): p = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(1)"]) count = 0 while p.poll() is None: time.sleep(0.1) count += 1 # We expect that the poll loop probably went around about 10 times, # but, based on system scheduling we ...
def __sub__(self, other): if not isinstance(other, Set): if not isinstance(other, Iterable): return NotImplemented other = self._from_iterable(other) return self._from_iterable(value for value in self if value not in other)
@unittest.skipIf(test_support.is_jython, "FIXME: not working in Jython") def test_contains(self): for c in self.letters: self.assertEqual(c in self.s, c in self.d) # 1 is not weakref'able, but that TypeError is caught by __contains__ self.assertNotIn(1, self.s) self.assertIn(self.obj, self.fs) ...
def strseq(object, convert, join=joinseq): """Recursively walk a sequence, stringifying each element.""" if type(object) in (list, tuple): return join(map(lambda o, c=convert, j=join: strseq(o, c, j), object)) else: return convert(object)
def _cmp_(x, y): xt = (x.getHours(), x.getMinutes(), x.getSeconds()) yt = (y.getHours(), y.getMinutes(), y.getSeconds()) return not xt == yt
def testRegisterResult(self): result = unittest.TestResult() unittest.registerResult(result) for ref in unittest.signals._results: if ref is result: break elif ref is not result: self.fail("odd object in result set") else: self.fail("result not found")
def emit(self, record): """ Emit a record. First check if the underlying file has changed, and if it has, close the old stream and reopen the file to get the current stream. """ if not os.path.exists(self.baseFilename): stat = None changed = 1 else: stat = os.sta...
def handle_close(self): self.close() if test_support.verbose: sys.stdout.write(" server: closed connection %s\n" % self.socket)
def test_setuptools_compat(self): import distutils.core, distutils.extension, distutils.command.build_ext saved_ext = distutils.extension.Extension try: # on some platforms, it loads the deprecated "dl" module test_support.import_module('setuptools_build_ext', deprecated=True) # the...
def test_2(self): hier = [ ("t2", None), ("t2 __init__"+os.extsep+"py", "'doc for t2'"), ("t2 sub", None), ("t2 sub __init__"+os.extsep+"py", ""), ("t2 sub subsub", None), ("t2 sub subsub __init__"+os.extsep+"py", "spam = 1"), ] self.mkhier(hier) import t2.sub import t...
def __eq__(self, other): if isinstance(other, timedelta): return self.__cmp(other) == 0 else: return False
def handle_expt_event(self): # handle_expt_event() is called if there might be an error on the # socket, or if there is OOB data # check for the error condition first err = self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # we can get here when select.select() says tha...
def __eq__(self, other): if isinstance(other, A) and self.x == other.x and self.y == other.y: return True return False
def foo(self): pass fy(C.foo.__name__ == "foo") fy(C().foo.__name__ == "foo") set(C.foo, "__name__", "foo") set(C().foo, "__name__", "foo")
def get_ext_fullname(self, ext_name): """Returns the fullname of a given extension name. Adds the `package.` prefix""" if self.package is None: return ext_name else: return self.package + '.' + ext_name
def formatweekday(self, day, width): """ Returns a formatted week day name. """ if width >= 9: names = day_name else: names = day_abbr return names[day][:width].center(width)
def test_boolean(self): cf = self.fromstring( "[BOOLTEST]\n" "T1=1\n" "T2=TRUE\n" "T3=True\n" "T4=oN\n" "T5=yes\n" "F1=0\n" "F2=FALSE\n" "F3=False\n" "F4=oFF\n" "F5=nO\n" "E1=2\n" "E2=foo\n" "E3=-1\n" ...
def _read(self, size, read_method): """Read size bytes using read_method, honoring start and stop.""" remaining = self._stop - self._pos if remaining <= 0: return '' if size is None or size < 0 or size > remaining: size = remaining return _ProxyFile._read(self, size, read_method)
def replace_header(self, _name, _value): """Replace a header. Replace the first matching header found in the message, retaining header order and case. If no matching header was found, a KeyError is raised. """ _name = _name.lower() for i, (k, v) in zip(range(len(self._headers)), self._head...
def addsitedir(sitedir, known_paths=None): """Add 'sitedir' argument to sys.path if missing and handle .pth files in 'sitedir'""" if known_paths is None: known_paths = _init_pathinfo() reset = 1 else: reset = 0 sitedir, sitedircase = makepath(sitedir) if not sitedircase i...
def ratio(self): """Return a measure of the sequences' similarity (float in [0,1]). Where T is the total number of elements in both sequences, and M is the number of matches, this is 2.0*M / T. Note that this is 1 if the sequences are identical, and 0 if they have nothing in common. .ratio() i...
def __repr__(self): return "<%s testFunc=%s>" % (_strclass(self.__class__), self.__testFunc)
def handle(self): """ Handle multiple requests - each expected to be a 4-byte length, followed by the LogRecord in pickle format. Logs the record according to whatever policy is configured locally. """ while 1: try: chunk = self.connection.recv(4) if len(chunk) < ...
def get_chromecasts(tries=None, retry_wait=None, timeout=None, **filters): """ Searches the network and returns a list of Chromecast objects. Filter is a list of options to filter the chromecasts by. ex: get_chromecasts(friendly_name="Living Room") May return an empty list if no chromecasts were f...
def _call_chain(self, chain, kind, meth_name, *args): # Handlers raise an exception if no one else should try to handle # the request, or return None if they can't but another handler # could. Otherwise, they return the response. handlers = chain.get(kind, ()) for handler in handlers: func ...
def _line_pair_iterator(): """Yields from/to lines of text with a change indication. This function is an iterator. It itself pulls lines from the line iterator. Its difference from that iterator is that this function always yields a pair of from/to text lines (with the change indication). If nec...
def chunk_it(l, chunks): return list(zip(*izip_longest(*[iter(l)] * chunks)))
def default_output_device(): """Return default output device index.""" idx = _pa.Pa_GetDefaultOutputDevice() if idx < 0: raise RuntimeError("No default output device available") return idx
def get_prior_mean(self, node_id, param, settings): if settings.optype == 'class': if node_id == self.root: base = param.base_measure else: base = self.pred_prob[node_id.parent] else: base = None # for settings.settings.smooth_hierarchically = False return...
def func(environ, start_response): content = f(environ, start_response) if 'gzip' in environ.get('HTTP_ACCEPT_ENCODING', ''): if type(content) is list: content = "".join(content) else: #this is a stream content = content.read() sio = StringIO.StringIO(...
def _prune_cond_tree(heads, min_support): merged_before = {} merged_now = {} for key in reversed(heads): (node, head_support) = heads[key] if head_support > 0: visited_parents = {} previous_node = None while node is not None: # If the node ...
def forward(self, input_act): """ Forward propagation. This class is mostly wraps around _forward and does some extra asserts. Child classes should overwrite _forward rather than this method. Parameters ---------- input_act : numpy array, activations from the layer below; shape must either be...
def test_job_run(): expected_rv = 42 job = Job(lambda: expected_rv, Schedule(30)) assert job.run() == expected_rv
def it_should_raise_exception(self): assert self.task.exception() is not None
@app.route('/') def home(): # Code adapted from: http://stackoverflow.com/questions/168409/ image_infos = [] for filename in os.listdir(DATA_DIR): filepath = os.path.join(DATA_DIR, filename) file_stat = os.stat(filepath) if S_ISREG(file_stat[ST_MODE]): image_infos.append(...
def test_supplied_feature_directory_no_steps(self): config = create_mock_config() config.paths = ["features/group1"] config.verbose = True r = runner.Runner(config) fs = FsMock( "features/", "features/group1/", "features/group1/foo.feature", ) with patch("os.path", ...
def __eq__(self, other): if not isinstance(other, Match): return False return (self.func, self.location) == (other.func, other.location)
def it_should_not_try_to_decode_the_body(self): assert self.message.body == self.body
def get_output_shape(self): # output_width = (self.input_shape[1] - self.filter_size + self.stride) // self.stride output_width = self.input_shape[1] // self.stride # because it's a circular convolution, this dimension is just divided by the stride. output_height = (self.input_shape[2] - self.filter_size + ...
def __init__(self, file=None, name=u'', url='', size=None): """Constructor. file: File object. Typically an io.StringIO. name: File basename. url: File URL. """ super(VirtualFile, self).__init__(file, name) self.url = url if size is not None: self._size = si...
@contract def mad(data): """ Calculate the Median Absolute Deviation from the data. :param data: The data to analyze. :type data: list(number) :return: The calculated MAD. :rtype: float """ data_median = median(data) return float(median([abs(data_median - x) for x in data]))
def _add_removed_links(self, section, removed_links): for link in self._get_links(section): if link is None: continue else: link_change = LinkChange( diff=self.docdiff, link_from=link) link_change.save() removed_...
@classmethod def get_by_key(cls, key, content_type=None): if key in _notification_type_cache: return _notification_type_cache[key] try: nt = cls.objects.get(key=key) except cls.DoesNotExist: nt = cls.objects.create(key=key, content_type=content_type) _notification_type_cache[key]...
def escape(): if len(vim.windows) < 2: return cur = vfunc.winnr() for n, w in reversed(list(enumerate(vim.windows, 1))): if not buffer_with_file(w.buffer): if not '[Command Line]'in w.buffer.name: focus_window(n) vim.command('q') if n != ...
def peek(self, offset=0): self.checkPos(self._pos+offset) pos = self._pos + offset return self._src[pos]
def loop(self): """ main game loop. returns the final score. """ pause_key = self.board.PAUSE margins = {'left': 4, 'top': 4, 'bottom': 4} atexit.register(self.showCursor) try: self.hideCursor() while True: self.clearScreen() print(self.__str__(margi...
def spawn_workers(self): """\ Spawn new workers as needed. This is where a worker process leaves the main loop of the master process. """ for i in range(self.num_workers - len(self.WORKERS.keys())): self.spawn_worker()