text
stringlengths
48
9.16k
def _readBodyCallback(self, dRes, body): self.busy = False dRes.callback(body) self._processQ()
def listen(self, event, handler): """ Register an event handler. Returns True on success. Event names are defined in `commands`. Handlers must be callable. :param str event: Then event name to listen for. :param callable handler: The callable event handler. """ if event not in self.commands...
def test__path_contained_by(self): p1 = '/foo//bar/baz/../stuff/' p2 = '/a/b/c/d/../../../../foo/bar/stufff' p3 = '/a/b/c/d/../../../../foo/bar/stuff/11' assert not build._path_contained_by(p1, p2) assert build._path_contained_by(p1, p3)
@send_self @catch_errors def run(self, *args, **varargs): this = yield window = sublime.active_window() view = window.active_view() view_name = os.path.split(view.file_name() or view.name())[1] frames = ['Running Nim Check' + f for f in busy_frames] stop_status_loop = loop_status_msg(frames, 0....
def __init__(self, ytid): self.ytid = ytid self.submissions = []
def __reverse_in_node(self, node_data): """Generates a string that matches 'in' node from the regular expression AST. Such node is an alternative between several variants. """ chosen = random.choice(node_data) type_, data = chosen if type_ == 'range': # TODO: add support for negation: [^......
def _build_dict(self): if self.nested_path: self[self.nested_path] = self._nesting() else: self[self.agg_name] = {self.metric: {"field": self.field_name}} if self.metric == "terms": self[self.agg_name][self.metric].update({ "size": self.size, "...
def recognize_sphinx(self, audio_data, language = "en-US", show_all = False): """ Performs speech recognition on ``audio_data`` (an ``AudioData`` instance), using CMU Sphinx. The recognition language is determined by ``language``, an RFC5646 language tag like ``"en-US"`` or ``"en-GB"``, defaulting to US En...
@httpretty.activate def test_queryset_getitem_with_post_query_action(): """ Fetch from QuerySet with __getitem__ and post query action """ # When I create a query block t = QuerySet("localhost", index="bar") # And I have a post query action global my_global_var my_global_var = 1 de...
def test_add_agg_global(): """ Create an aggregations block that is global """ # When add a global agg block t = Aggregations("agg_name", "field_name", "metric", global_name="global_agg") # Then I see correct json results = { "global_agg": { "global": {}, "ag...
def run(self, edit, message, *args, **kwargs): #print('UpdatePanelCommand.run', args, kwargs) #logger.debug('UpdatePanelCommand was triggered with arguments: %s' % (kwargs)) self.view.erase(edit, sublime.Region(0, self.view.size())) self.view.insert(edit, self.view.size(), message) self.view.show(...
@classmethod def create(cls, responseType): return resourceTypes.get(responseType, OEmbedResponse)()
def __call__(self, random, population, args): with self._lock: evaluate_migrant = args.setdefault('evaluate_migrant', False) migrant_index = random.randint(0, len(population) - 1) old_migrant = population[migrant_index] try: migrant = self.migrants.get(block=False) ...
def get_acl_feed(self, uri=None, auth_token=None, **kwargs): """Retrieves the acl feed containing a site's sharing permissions. Args: uri: string (optional) A full URI to query the acl feed. auth_token: (optional) gdata.gauth.ClientLoginToken, AuthSubToken, or OAuthToken which authorizes this clien...
def delete_all(filename): """ Delete all files that `find_all` returns :param filename: the absolute path file name to use :return: None """ for file in find_all(filename): os.remove(file)
def __init__(self, uri=None, address=None, *args, **kwargs): """Constructs a new EmailSettingsDelegation object with the given arguments. Args: uri: string (optional) The uri of this object for HTTP requests. address: string The email address of the delegated user. """ super(EmailSettingsDelegatio...
@classmethod def start(self, view, working_directory, command): logger.debug('TestRunner start requested') if self.worker and self.worker.is_alive(): logger.debug(' |- there is another worker alive...') if (settings.get('test_override')): logger.debug(' |- overriding current worker....
def AuthSubTokenFromHttpBody(http_body): """Extracts the AuthSub token from an HTTP body string. Used to find the new session token after making a request to upgrade a single use AuthSub token. Args: http_body: str The repsonse from the server which contains the AuthSub key. For example, this func...
def addObservable(self, eventTypeId, callbackFunction): """ Add a function that will be invoked when the corresponding event is triggered. Ex: myWidget.addObservable(myWidget.EVENT_BEFORE_NEXT, self.onBeforeNextClicked) :param eventTypeId: public id if the event exposed by the class :param callbackFunct...
def __init__(self, bbio_gpio): self.bbio_gpio = bbio_gpio # Define mapping of Adafruit GPIO library constants to RPi.GPIO constants. self._dir_mapping = { OUT: bbio_gpio.OUT, IN: bbio_gpio.IN } self._pud_mapping = { PUD_OFF: bbio_gpio.PUD_OFF, ...
def retrieve_page_of_org_users(self, customer_id, startKey=None, **kwargs): """Retrieve one page of OrgUsers in the customer's domain. Args: customer_id: string The ID of the Google Apps customer. startKey: The string key to continue for pagination through all OrgUnits. Returns: gdata.apps.organisat...
def test_textfield(self): dickie = Author.objects.create(name="Dickens", bio="Aged 10, bald.") authors = Author.objects.filter(bio__case_exact="Aged 10, bald.") assert list(authors) == [dickie] authors = Author.objects.filter(bio__case_exact="Aged 10, BALD.") assert list(authors) == []
def test_constant(self): # If we keep achieving a rate of 100 rows in 0.5 seconds, it should # recommend that we keep there rate = WeightedAverageRate(0.5) assert rate.update(100, 0.5) == 100 assert rate.update(100, 0.5) == 100 assert rate.update(100, 0.5) == 100
def clean_TaxOverrideType(self): otype = getattr(self, 'TaxOverrideType', None) if otype is None: otype = 'None' if otype not in TaxOverride.OVERRIDE_TYPES: raise AvalaraValidationException(AvalaraException.CODE_BAD_OTYPE, 'TaxOverrideType is not one of the allowed types') setattr(self, ...
def __init__(self, results=None, more=None,): self.results = results self.more = more
def writeList(self, register, data): """Write bytes to the specified register.""" self._bus.write_i2c_block_data(self._address, register, data) self._logger.debug("Wrote to register 0x%02X: %s", register, data)
def callNoduleSegmentationCLI(self, inputVolumeID, maximumRadius, onCLISegmentationFinishedCallback=None): """ Invoke the Lesion Segmentation CLI for the specified volume and fiducials. Note: the fiducials will be retrieved directly from the scene :param inputVolumeID: :return: """ # Try to load...
def test_dumping(self): instance = NullBit1Model(flag=None) data = json.loads(serializers.serialize('json', [instance]))[0] fields = data['fields'] assert fields['flag'] is None
def create_parser(self, prog_name, subcommand): """ Create and return the ``OptionParser`` which will be used to parse the arguments to this command. """ # hack __main__ so --help in dev_appserver_main works OK. sys.modules['__main__'] = dev_appserver_main return super(Command, self).create...
def info_to_dict(value, delimiter = ';'): """ Simple function to convert string to dict """ stat_dict = {} stat_param = itertools.imap(lambda sp: info_to_tuple(sp, "="), info_to_list(value, delimiter)) for g in itertools.groupby(stat_param, lambda x: x[0]): ...
@CommandHelp('Shows the distribution of TTLs for namespaces') def do_time_to_live(self, line): return self._do_distribution('ttl', 'TTL Distribution', 'Seconds')
def items(self, obj): list = [] list.insert(0,obj) for obj in obj.reply_set.all()[:10] : list.append(obj) return list
def try_upload_subtitles(self, params): '''Return True if the subtitle is on database, False if not. ''' self.data = self.xmlrpc.TryUploadSubtitles(self.token, params) return self._get_from_data_or_none('alreadyindb') == 1
def prepare_publication(self, object): return object.publication.name
def compilelib(libpath): version = git_version(libpath) lines = [] lines.append("EESchema-LIBRARY Version 2.3\n") lines.append("#encoding utf-8\n\n") lines.append("#" + "="*78 + "\n") lines.append("# Automatically generated by agg-kicad compile_lib.py\n") lines.append("# on {}\n".format(date...
def assert_raises(self, exc_class, func, *args, **kwargs): '''Like assertRaises() but returns the exception''' try: func(*args, **kwargs) except exc_class as exc: return exc else: raise AssertionError('%s was not raised' % exc_class.__name__)
def _do_default(self, line): self.executeHelp(line)
def filter_features(model_results, significance=0.1): ''' Returns a list of features that are below a given level of significance. Parameters ---------- model_results : Series a pandas series of the results.pvalues of your model significance : float significance level, default a...
def _move_root_node(self, node, target, position): """ Moves root node``node`` to a different tree, inserting it relative to the given ``target`` node as specified by ``position``. ``node`` will be modified to reflect its new tree state in the database. """ left = getattr(node, self.lef...
def revert_to(self, article, revision): (default_revision_manager.get_for_object(article)[revision] .revision.revert())
def test_fqdnurl_validation_without_host(): """ test with empty host FQDN URL """ schema = Schema({"url": FqdnUrl()}) try: schema({"url": 'http://'}) except MultipleInvalid as e: assert_equal(str(e), "expected a Fully qualified domain name URL for dictionary value @ ...
@raise_if_none('cookie', MagicError, 'object has already been closed') @byte_args(positions=[1]) @str_return def id_filename(self, filename): "Return a textual description of the contents of the file" return api.magic_file(self.cookie, filename)
def email(self, comment, content_object, request): moderators = [] chief = settings.EDITORS['chief'] moderators.append(chief) managing = settings.EDITORS['managing'] moderators.append(managing) online_dev = settings.EDITORS['online_dev'] moderators.append(online_dev) multimedia = setting...
def longestConsecutive(self, root): self.longest(root) return self.gmax
def longestPalindrome_TLE(self, s): """ Algorithm: dp, O(n^2) p[i,j] represents weather s[i:j] is palindrome. (incl. i-th while excl. j-th) For example S = "abccb" 01234 p[0,1] = True, p[1,2] = True, etc. since single char is Palindrom p[0,2] = s[0]==s[1], p[0,3] = s[0]...
def __init__(self, source, *args, **kwargs): """Init.""" super(IndexBatchIterator, self).__init__(*args, **kwargs) self.source = source if source is not None: # Tack on (SAMPLE_SIZE-1) copies of the first value so that it is # easy to grab # SAMPLE_SIZE POINTS even from the first...
def asdict(hdr, row, missing=None): flds = [text_type(f) for f in hdr] try: # list comprehension should be faster items = [(flds[i], row[i]) for i in range(len(flds))] except IndexError: # short row, fall back to slower for loop items = list() for i, f in enumerate(fl...
def attribute_text_getter(attr, missing): def _get(v): if len(v) > 1: return tuple(e.get(attr) for e in v) elif len(v) == 1: return v[0].get(attr) else: return missing return _get
def save_to_json(): table = _AGGREGATED_SALES_TABLE with open('{}.json'.format(table), 'w') as f: records = [row for row in scraperwiki.sqlite.select( '* FROM {}'.format(table))] f.write(json.dumps(records, cls=JsonEncoder, indent=1))
def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('unpause_args') oprot.writeFieldStop() ...
def recordtree(table, start='start', stop='stop'): """ Construct an interval tree for the given table, where each node in the tree is a row of the table represented as a record object. """ import intervaltree getstart = attrgetter(start) getstop = attrgetter(stop) tree = intervaltree.I...
def wrapper(*args, **kwargs): current_delay = delay current_try = max_tries while current_try > 0: current_try -= 1 for current_try in range(max_tries): try: return f(*args, **kwargs) except RetryFailed: # Do not sleep after the last retry if c...
def __init__(self, conf={}): logger.info("Creating decoder using conf: %s" % conf) self.create_pipeline(conf) self.outdir = conf.get("out-dir", None) if not os.path.exists(self.outdir): os.makedirs(self.outdir) elif not os.path.isdir(self.outdir): raise Exception("Output directory %s...
def test_parses_data_correctly_when_v2(self): posted_data = [ { "_id": "YnJvd3NlcnMyMDE0LTEwLTE0IDAwOj" "AwOjAwKzAwOjAwTW96aWxsYQ==", "_timestamp": datetime.datetime( 2014, 10, 14, 0, 0, tzinfo=pytz.UTC), "browser": "Mozilla", ...
def _get_route_for(self, action): """Return the complete URL for this action. Basically: - get, update and delete need an id - add and list does not """ route = self._route if action in self._NEED_ID: route += "/<%s>" % self._identifier return route
def dispatch(self, opcode, context): """Dispatches a context on a given opcode. Returns True if the context is done matching, False if it must be resumed when next encountered.""" #if self.executing_contexts.has_key(id(context)): if id(context) in self.executing_contexts: generator = self.execut...
def setEntityResolver(self, resolver): "Register an object to resolve external entities." self._ent_handler = resolver
def secure_connection(self): socket = ssl.wrap_socket(self.socket, suppress_ragged_eofs=False, certfile=CERTFILE, server_side=True, do_handshake_on_connect=False, ssl_version=ssl.PROTOCOL_SSLv23) self.del_channel() self.s...
def op_in(self, ctx): # match set member (or non_member) # <IN> <skip> <set> #self._log(ctx, "OP_IN") self.general_op_in(ctx) return True
def averageWords(text_f="/afs/cs.stanford.edu/u/awni/swbd/data/eval2000/text_ctc"): with open(text_f,'r') as fid: lines = [l.strip().split()[1:] for l in fid.readlines()] numUtts = float(len(lines)) numWords = sum(len(l) for l in lines) return numWords/numUtts
def op_max_until(self, ctx): # maximizing repeat # <REPEAT> <skip> <1=min> <2=max> item <MAX_UNTIL> tail repeat = ctx.state.repeat #print("op_max_until") #, id(ctx.state.repeat)) if repeat is None: #print(id(ctx), id(ctx.state)) raise RuntimeError("Internal re error: MAX_UNTIL withou...
def get_free_nodes(cluster, parallel=True): nodes = [cluster + str(node) for node in CLUSTER_NODES[cluster]] if parallel: is_free = joblib.Parallel(n_jobs=NUM_CPUS)( joblib.delayed(is_node_free)(node) for node in nodes) else: is_free = list() for node in nodes: ...
def test_setup_class(self): class Test(unittest.TestCase): setUpCalled = 0 @classmethod def setUpClass(cls): Test.setUpCalled += 1 unittest.TestCase.setUpClass() def test_one(self): pass def test_two(self): pass result = se...
def emit(self, record): """ Emit a record. If the stream was not opened because 'delay' was specified in the constructor, open it before calling the superclass's emit. """ if self.stream is None: self.stream = self._open() StreamHandler.emit(self, record)
def onkeypress(self, fun, key=None): """Bind fun to key-press event of key if key is given, or to any key-press-event if no key is given. Arguments: fun -- a function with no arguments key -- a string: key (e.g. "a") or key-symbol (e.g. "space") In order to be able to register key-events, Turt...
def __radd__(self, val): return self.val + val
def test_loadTestsFromName__malformed_name(self): loader = unittest.TestLoader() # XXX Should this raise ValueError or ImportError? try: loader.loadTestsFromName('abc () //') except ValueError: pass except ImportError: pass else: self.fail("TestLoader.loadTestsFr...
def test_process_awareness(self): # ensure that the random source differs between # child and parent. read_fd, write_fd = os.pipe() pid = None try: pid = os.fork() if not pid: os.close(read_fd) os.write(write_fd, next(self.r).encode("ascii")) os.cl...
def trace_return(self, frame): self.add_event('return', frame) self.stack.pop()
def test_adding_child_mock(self): for Klass in NonCallableMock, Mock, MagicMock, NonCallableMagicMock: mock = Klass() mock.foo = Mock() mock.foo() self.assertEqual(mock.method_calls, [call.foo()]) self.assertEqual(mock.mock_calls, [call.foo()]) mock = Klass() ...
def put(self, item, block=True, timeout=None): '''Put an item into the queue. If optional args 'block' is true and 'timeout' is None (the default), block if necessary until a free slot is available. If 'timeout' is a non-negative number, it blocks at most 'timeout' seconds and raises the Full excep...
def _test_module_encoding(self, path): path, _ = os.path.splitext(path) path += ".py" with codecs.open(path, 'r', 'utf-8') as f: f.read()
def test_unsupported_auth_basic_handler(self): # While using BasicAuthHandler opener = OpenerDirector() basic_auth_handler = urllib.request.HTTPBasicAuthHandler(None) http_handler = MockHTTPHandler( 401, 'WWW-Authenticate: NTLM\r\n\r\n') opener.add_handler(basic_auth_handler) opener.add_...
def test_iadd(self): super().test_iadd() u = (0, 1) u2 = u u += (2, 3) self.assertTrue(u is not u2)
def addExpectedFailure(self, test, err): super(TextTestResult, self).addExpectedFailure(test, err) if self.showAll: self.stream.writeln("expected failure") elif self.dots: self.stream.write("x") self.stream.flush()
@classmethod def _test_stderr_flush(cls, testfn): sys.stderr = open(testfn, 'w') 1/0 # MARKER
def check_pickle(self, itorg, seq): d = pickle.dumps(itorg) it = pickle.loads(d) # Cannot assert type equality because dict iterators unpickle as list # iterators. # self.assertEqual(type(itorg), type(it)) self.assertTrue(isinstance(it, collections.abc.Iterator)) self.assertEqual(list(it), s...
def test_compare_function_objects(self): f = eval('lambda: None') g = eval('lambda: None') self.assertNotEqual(f, g) f = eval('lambda a: a') g = eval('lambda a: a') self.assertNotEqual(f, g) f = eval('lambda a=1: a') g = eval('lambda a=1: a') self.assertNotEqual(f, g) f = eva...
def test_writable_readonly(self): # Issue #10451: memoryview incorrectly exposes a readonly # buffer as writable causing a segfault if using mmap tp = self.ro_type if tp is None: return b = tp(self._source) m = self._view(b) i = io.BytesIO(b'ZZZZ') self.assertRaises(TypeError, i....
def test_issue14725(self): l = self.connection.Listener() p = self.Process(target=self._test, args=(l.address,)) p.daemon = True p.start() time.sleep(1) # On Windows the client process should by now have connected, # written data and closed the pipe handle by now. This causes # ConnectN...
def test_failing_queue(self): # Test to make sure a queue is functioning correctly. # Done twice to the same instance. q = FailingQueue(QUEUE_SIZE) self.failing_queue_test(q) self.failing_queue_test(q)
def __init__(self, layers, loss): self.layers = layers self.loss = loss self.bprop_until = next((idx for idx, l in enumerate(self.layers) if isinstance(l, ParamMixin)), 0) self.layers[self.bprop_until].bprop_to_x = False self.collection = self.layers self._initialize...
@classmethod def load_item_classes_from_file(cls, f): ''''load json items from a file and return a TaskFactory''' return cls.taskfactory_from_objects(json.load(f))
def train_epoch(self): batch_losses = [] for batch in self.feed.batches(): loss = np.array(ca.mean(self.model.update(*batch))) for param, state in zip(self.params, self.learn_rule_states): self.learn_rule.step(param, state) batch_losses.append(loss) epoch_loss = np.mean(b...
def http_connect(method, params, api_key): conn = httplib.HTTPSConnection("api.africastalking.com") headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "application/json", "ApiKey": api_key } params = urllib.urlencode(params) conn.request(method, PATH, params, headers) res = conn.getrespo...
def y_shape(self, x_shape): return self.conv_op.output_shape(x_shape, self.n_filters, self.filter_shape)
def enable_colors(colors): for i in colors: CONF["COLORS"][i] = colors[i]
def seq_final_arrival(self, seq_num): ''' Returns the time at which the seq number had fully arrived, that is, when all the data before it had also arrived. ''' try: return self.final_arrival_data.find_le(seq_num)[1] except: return None
def set_fathers(self, f): self.fathers.append(f)
def visit_ins(self, ins): return ins.visit(self)
def decode(self, y): self._tmp_y = y x = ca.dot(y, self.weights.array.T) + self.bias_prime.array return self.activation_decode.fprop(x)
def Save(self): """Save this branch back into the configuration. """ if self._config.HasSection('branch', self.name): if self.remote: self._Set('remote', self.remote.name) else: self._Set('remote', None) self._Set('merge', self.merge) else: fd = open(self._config.file, 'ab') try...
def Multiple_lines_are_printed__test(): out = StringIO() csv = Csv( out, ( "a", "b", "c" ) ) csv.line( ( 2, "x", 3.5 ) ) csv.line( ( 4, "y", 5.5 ) ) assert_equal( '''"a", "b", "c" 2, "x", 3.5 4, "y", 5.5 ''', out.getvalue() )
def get_id(self, package_name, rid, locale='\x00\x00'): self._analyse() try: for i in self.values[package_name][locale]["public"]: if i[2] == rid: return i except KeyError: return None
def process_and_show(self): for name, klass in sorted(self.classes.iteritems()): logger.info('Processing class: %s', name) if not isinstance(klass, DvClass): klass = DvClass(klass, self.vma) klass.process() klass.show_source()
def _Load(self): if not self._loaded: m = self.manifestProject b = m.GetBranch(m.CurrentBranch) if b.remote and b.remote.name: m.remote.name = b.remote.name b = b.merge if b is not None and b.startswith(R_HEADS): b = b[len(R_HEADS):] self.branch = b self._ParseManifest(True) ...
def __init__(self, field): self.field = field self.xrefread = set() self.xrefwrite = set()
def convert(self, value, param, ctx): if hasattr(value, 'read') or hasattr(value, 'write'): return value value = os.path.expanduser(value) return super(File, self).convert(value, param, ctx)
def __init__(self, address): """ Args: address: A string or integer representing the IP Additionally, an integer can be passed, so IPv4Address('192.0.2.1') == IPv4Address(3221225985). or, more generally IPv4Address(int(IPv4Address('192.0.2.1'))) == I...
def __contains__(self, dist): """True if `dist` is the active distribution for its project""" return self.by_key.get(dist.key) == dist