text
stringlengths
48
9.16k
def get_tag_revs(self, svn_tag_url): stdout = self.run_command(['ls', '-v', svn_tag_url], show_stdout=False) results = [] for line in stdout.splitlines(): parts = line.split() rev = int(parts[0]) tag = parts[-1].strip('/') results.append((tag, rev)) return results
def _has_marker(keys, markers): for marker in markers: if marker in keys: return True return False
def test_contains_unary_metric(self): ret = parser._contains_unary_metrics(self.unary_conf['metrics']) self.assertTrue(ret)
def _FetchHelper(self, opt, project, lock, fetched, pm, sem): if not project.Sync_NetworkHalf(quiet=opt.quiet): print >>sys.stderr, 'error: Cannot fetch %s' % project.name if opt.force_broken: print >>sys.stderr, 'warn: --force-broken, continuing to sync' else: sem.release() ...
def addInfothisDict (thisNode, cloudElementArea,criteriaB): ''' Purpose:: Update original dictionary node with information Input:: thisNode: a string representing the unique ID of a node cloudElementArea: a floating-point number representing the area of the cloud element criteriaB: a masked array of float...
@user_entities.setter def user_entities(self, user_entities): self._user_entities = user_entities
def generate_evaluation_from_config(config_data): """ Generate an Evaluation object from configuration data. :param config_data: Dictionary of the data parsed from the supplied YAML configuration file. :type config_data: :func:`dict` :returns: An Evaluation object containing the data specified...
def check_message_2(self, sr, color='GREEN'): self.log.write(sr) self.log.write('\n') Utils.pprint(color, sr)
def __new__(self, actions=None): return tuple.__new__(self, actions or [])
def __init__(self, name, id, classes, attribs, pseudos): self.name = name self.id = id self.classes = classes self.attribs = attribs self.pseudos = pseudos
def set_cone_inner_angle(self, cone_inner_angle): context.lock() al.alSourcef(self._al_source, al.AL_CONE_INNER_ANGLE, cone_inner_angle) context.unlock()
def start(self): # Create timer timer = self._timer carbon.InstallEventLoopTimer(self._event_loop, ctypes.c_double(0.1), #? ctypes.c_double(kEventDurationForever), self._timer_func_proc, ...
def deco(func): setattr(task_gen, func.__name__, func) try: for x in Utils.to_list(var): task_gen.mappings[x] = func except: raise Utils.WafError('extension takes either a list or a string %r' % var) task_gen.mapped[func.__name__] = func return func
def is_media(self): t = self._peek() return isinstance(t, AtKeyword) and t == '@media'
def is_charset(self): t = self._peek() return isinstance(t, AtKeyword) and t == '@charset'
def get_scheme_pkgfile(self, scheme): return '-'.join(self.make_fullplatcomponents( self.get_name(), scheme, self.get_version(), )) + '.pkg'
def p_define_function_params(self, p): '''define_function_params : identifier_list_opt | ELLIPSIS | identifier_list ',' ELLIPSIS ''' if len(p) == 2: if p[1] == 'ELLIPSIS': p[0] = ('...',) else: p[0] = p[1] ...
def connect(self, other): return other._connect_line2(self)
def get_set_bits(bytes): bits = set() j = 0 for byte in bytes: for i in range(8): if byte & 1: bits.add(j + i) byte >>= 1 j += 8 return bits
def unindent_docstring(docstring): # [xx] copied from inspect.getdoc(); we can't use inspect.getdoc() # itself, since it expects an object, not a string. if not docstring: return '' lines = docstring.expandtabs().split('\n') # Find minimum indentation of any non-blank lines after first line. ...
@event.default('button') def on_mouse_press(self, x, y, button, modifiers): self.is_pressed = True return event.EVENT_UNHANDLED
def _update_funcid_to_doc(self, profile_stats): """ Update the dictionary mapping from C{pstat.Stat} funciton ids to C{RoutineDoc}s. C{pstat.Stat} function ids are tuples of C{(filename, lineno, funcname)}. """ # Maps (filename, lineno, funcname) -> RoutineDoc for val_doc in self.reachable_...
def report_errors(api_doc, docindex, parse_errors, field_warnings): """A helper function for L{parse_docstring()} that reports any markup warnings and field warnings that we encountered while processing C{api_doc}'s docstring.""" if not parse_errors and not field_warnings: return # Get the name of ...
def create_construction(self, x, y): x, y = (x // hw)*hw, (y // hh)*hh cx, cy = x//hw, y//hh cells = (cx, cy), (cx+1, cy), (cx, cy+1), (cx+1, cy+1) for cell in cells: if self.play_field[cell]: return # check we're not going to block the only path for any enemy if not self....
def __init__(self, factory=None, elements_per_list=0): super(ListFactory, self).__init__() self._factory = factory self._elements_per_list = elements_per_list
def test_dispatch_meta(self): p, t, d, m = self.build_proto() d.inject(3, 0, const.RTMP_DATA, 1, encode_amf('onStatus', None)) self.assertEquals(self.messages, [('meta', 0, 1, ['onStatus', None])])
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 on_mouse_drag(self, x, y, dx, dy, buttons, modifiers): print >> self.file, 'on_mouse_drag(x=%d, y=%d, dx=%d, dy=%d, '\ 'buttons=%s, modifiers=%s)' % ( x, y, dx, dy, mouse.buttons_string(buttons), key.modifiers_string(modifiers))
def get_style(self, attribute): '''Get the document's named style at the caret's current position. If there is a text selection and the style varies over the selection, `pyglet.text.document.STYLE_INDETERMINATE` is returned. :Parameters: `attribute` : str Name of style attribute to...
def __init__(self, *args, **kwargs): super(Window, self).__init__(400, 140, caption='Text entry') self.batch = pyglet.graphics.Batch() self.labels = [ pyglet.text.Label('Name', x=10, y=100, anchor_y='bottom', color=(0, 0, 0, 255), batch=self.batch), pyglet.text.Lab...
def test_waitStatus(self): p, t, dmx, mux = self.build_proto() # wait for event with specific code d = p.waitStatus(1, info1.code) d.addCallback(self.assertEquals, info1) # then wait for any event on message stream 1 d.addCallback(lambda _: p.waitStatus(1, None)) d.addCallback(self.assertE...
def read(self, callback, grpos_range, frames=None): if grpos_range: # here we only handle the case of data shrinking from the # left / earlier side... end_grpos = self._grpos + grpos_range pos = self._pos grpos = self._grpos while 1: idx = pos - self._s.da...
def update(self, dt): self.player.dispatch_events() if self.control is None: # the player update may have resulted in this element being # culled return if not self.control.isVisible(): return t = self.player.time # time display s = int(t) m = t // 60 h...
def get_mipmapped_texture(self): if self._current_mipmap_texture: return self._current_mipmap_texture if not self._have_extension(): # TODO mip-mapped software decoded compressed textures. For now, # just return a non-mipmapped texture. return self.get_texture() texture = ...
def test_send_notrendered(self): message = self._initMessage() message.context = CONTEXT2 message.send() self._assertIsRendered(message, True, SUBJECT2, BODY2)
def test_watching_with_page(self): repos = self.client.repos.watching('tekkub', page=2) eq_(len(repos), 39) eq_(repos[0].name, 'Buffoon')
def quote_string(s): chars = [] for c in s: if c == "\\": c = "\\\\" elif c == "\"": c = "\\\"" chars.append(c) return "\"" + "".join(chars) + "\""
def get_now(): """ Allows to access global request and read a timestamp from query. """ if not get_current_request: return datetime.datetime.now() request = get_current_request() if request: openinghours_now = request.GET.get('openinghours-now') if openinghours_now: ...
def rotatey(self, angle): self *= Matrix4.new_rotatey(angle) return self
def to_plaintext(self, docstring_linker, **options): # [XX] don't cache -- different options might be used!! #if self._plaintext is not None: return self._plaintext if self._tree is None: return '' if 'indent' in options: self._plaintext = to_plaintext(self._tree, ...
def get_preprocessor_define(node, buffer) : """get_preprocessor_define(File, string) -> string""" # Regex the #define. Group 1 is the name, Group 2 is the value define = re.search('#define[\\s]+([^\\s]+)[\\s]+(.+)', buffer) if define : # The whole line is consumed, return an empty string to ind...
def get(self): parent_entity_id = self.get_argument('parent_entity_id', default=None, strip=True) entity_definition_keyname = self.get_argument('entity_definition_keyname', default=None, strip=True) public = True if self.get_argument('public', default=None, strip=True) == 'true' else False user = self....
def __init__(self, f): super(CheckedCall, self).__setattr__("f", f)
def _generate_ascii(self, matrix, foreground, background): """ Generates an identicon "image" in the ASCII format. The image will just output the matrix used to generate the identicon. Arguments: matrix - Matrix describing which blocks in the identicon should be painted with foreground (ba...
def expand(tests): if isinstance(tests, unittest.TestCase): method_name = tests._testMethodName meth = getattr(tests, method_name) if hasattr(meth, 'iterations'): tests = unittest.TestSuite(type(tests)(method_name) for i in xrange(meth.iterations)) else: tests = unitt...
@classmethod def setUpClass(self): with open ("test/snippets/line_01.txt", "r") as myfile: self.string1 = myfile.read() with open ("test/snippets/line_02.txt", "r") as myfile: self.string2 = myfile.read()
def for_address(self, address): if not address: return None func = getattr(settings, 'EASY_MAPS_GEOCODE', None) if func is not None: if not isinstance(func, collections.Callable): func = importpath(func) try: return func(address) except geocode.Error as e: ...
def injectmex86(pid, shellcode): from sys import platform if platform.startswith('win'): print ("\nPtrace not working on windows machines ..\n") return False else: try: from ptrace.debugger.debugger import PtraceDebugger from ptrace.debugger.debugger import P...
def _debugdirtyFn(self, x, y): if self._screendirty[x][y]: return 'D' else: return '.'
def bz2_pack(source): """ Returns 'source' as a bzip2-compressed, self-extracting python script. .. note:: This method uses up more space than the zip_pack method but it has the advantage in that the resulting .py file can still be imported into a python program. """ import...
def test_create_contacts_from_message_field_successfully_creates_contact_object(self): contacts = Contact.create_contacts_from_message_field('to', self.message) self.assertEqual(contacts[0].email, 'ben@npmjs.com')
def get_response(self): """ gets the message type and message from rexster :returns: RexProMessage """ msg_version = self.recv(1) if not msg_version: raise exceptions.RexProConnectionException('socket connection has been closed') if bytearray([msg_version])[0] != 1: raise ex...
def _generate_regions(R, L): n_ini = sum(not parent for parent in R.values()) n_all = len(R) regions = list() for label in R.keys(): i = min(n_all - n_ini + 1, n_all - label) vi = numpy.random.rand() * i regions.append((vi, L[i])) return sorted(regions)
def setup(target, inputFile, N): """Sets up the sort. """ tempOutputFile = getTempFile(rootDir=target.getGlobalTempDir()) target.addChildTargetFn(down, (inputFile, 0, os.path.getsize(inputFile), N, tempOutputFile)) target.setFollowOnFn(cleanup, (tempOutputFile, inputFile))
def main(): num_samples = len(cu.get_dataframe("public_leaderboard.csv")) predictions = np.kron(np.ones((num_samples,5)), np.array(0.2)) cu.write_submission("uniform_benchmark.csv", predictions)
@pytest.yield_fixture() def to_be_deleted(workon_home): envname = 'to_be_deleted' invoke('new', envname, '-d') yield envname assert not (workon_home / envname).exists()
def lost_connection(self, p): """Called by the rpc protocol whenever it loses a connection.""" self.protocols.remove(p)
def get_fieldsets(self, request, obj=None): """ Check `add_fieldsets` and only display those when action is add """ if not obj and hasattr(self, 'add_fieldsets'): return self.add_fieldsets return super(EnhancedModelAdmin, self).get_fieldsets(request, obj)
def __init__(self, loop, factory): self.loop = loop self.factory = factory self.timer = pyev.Timer(2.0, 2.0, loop, self._print_stats)
def get_report(self, config, client, options): username = config.get_server_username() if username is None: username = getpass.getuser() return ReportToDoListMine(client, username=username, projects=self.get_projects(config, options), ...
def NotifySearch(self): """ Send notification of the new Sitemap(s) to the search engines. """ if self._suppress: output.Log('Search engine notification is suppressed.', 1) return output.Log('Notifying search engines.', 1) # Override the urllib's opener class with one that doesn't ignore 404s class ...
@web.removeslash def get(self): menu = self.get_menu() self.json({ 'result': menu, 'time': round(self.request.request_time(), 3), })
def register_publish(username, block_version, async_process=True): """Used in background to know if a user has been reused""" generic_enqueue('biicode.background.worker.worker.register_publish', [username, block_version], async_process=async_process)
def get_user_info(self, access_token): params = {"alt": "json", "access_token": access_token} encoded_params = urllib.urlencode(params) url = 'https://www.googleapis.com/oauth2/v1/userinfo?%s' % encoded_params res = requests.get(url) json = res.json() login = json["email"].split("@")[0].replace(...
def error(self, *args, **kwargs): predictions = self.predictions(*args, **kwargs) error = T.mean((predictions - self.target_var) ** 2) return error
def parse_field(self, field_types): attrs = self.element_start('FIELD') id = int(attrs['ID']) type = field_types[id] value = self.character_data() if type == 'Integer': value = int(value) elif type == 'Float': value = float(value) elif type == 'Address': value = int(v...
def parse_cg_entry(self, lines): if lines[0].startswith("["): self.parse_cycle_entry(lines) else: self.parse_function_entry(lines)
def ratio(self, outevent, inevent): assert outevent not in self assert inevent in self for function in self.functions.itervalues(): assert outevent not in function assert inevent in function function[outevent] = ratio(function[inevent], self[inevent]) for call in function.cal...
def user_popular_links(self, **kwargs): data = self._call_oauth2_metrics("v3/user/popular_links", dict(), **kwargs) return data["popular_links"]
def demultiplex_records(n, records): demux = [[] for _ in xrange(n)] for i, r in records: demux[i].append(r) return demux
def get_colors(self): colors = '' for sym in self.symbols: if self.symbols[sym] > 0: symcolors = re.sub(r'2|P|S|X', '', sym) for symcolor in symcolors: if symcolor not in colors: colors += symcolor # sort so the order is always consistent ...
def fetch_destination(self, address): recipient = unicode(address).strip() # alias match1 = re.match("^(|([\w\-\.]+)@)((\w[\w\-]+\.)+[\w\-]+)$", recipient) # label or alias, with address in brackets match2 = re.match("(.*?)\s*\<([1-9A-HJ-NP-Za-km-z]{26,})\>", ...
def loglkl(self, cosmo, data): # reduced Hubble parameter h = cosmo.h() # WiggleZ specific if self.use_scaling: # angular diameter distance at this redshift, in Mpc d_angular = cosmo.angular_distance(self.redshift) # radial distance at this redshift, in Mpc, is simply 1/H (its...
def set_parameters(self, host, port, protocol, proxy, auto_connect): self.config.set_key('auto_cycle', auto_connect, True) self.config.set_key("proxy", proxy, True) self.config.set_key("protocol", protocol, True) server = ':'.join([ host, port, protocol ]) self.config.set_key("server", server, True...
def check_result (val, func, args): if val == 0: raise ValueError else: return ctypes.c_void_p (val)
def __str__(self): '''String represention of this collection.''' result = [] for key, value in self: result.append('%s = %s' % (key, repr(value))) result.sort() return '\n'.join(result)
def __init__(self, owner=None): self.owner = owner self.editing = False QTreeWidget.__init__(self, owner) self.setColumnCount(3) self.setHeaderLabels([_("Address"), _("Label"), _("Used")]) self.setIndentation(0) self.hide_used = True self.setColumnHidden(2, True)
def get_feature_size(self): size = 0 for vect_rule in self.vect_rules: vect = vect_rule.get('vectorizer') size += len(vect.vocabulary_) return size
def to_str(self): for (path, fp) in self.fingerprints.fingerprints.iteritems(): if not fp or not fp.md5: raise AssertionError("missing Fingerprint or MD5 when serializing FingerprintList: %s: %s" % (path, fp)) return values_to_str([("checkouts", self.checkouts.to_str()), ("fingerpr...
def build_supervised_model(self, n_features, n_classes): """ Creates the computational graph. This graph is intented to be created for finetuning, i.e. after unsupervised pretraining. :param n_features: Number of features. :param n_classes: number of classes. :return: self """ self._cr...
def method_is_explictly_overwritten(self): view_func = current_app.view_functions[request.endpoint] return hasattr(view_func, '_explict_rule_set') and view_func._explict_rule_set is True
def test_country_preferences(self): '''It should save a school's country preferences.''' c1 = TestCountries.new_country().id c2 = TestCountries.new_country().id params = self.get_params(countrypreferences=[0, c1, c2, 0, c1]) response = self.get_response(params=params) self.assertEqual(response....
def matches_subject_class(self, subject): """ subject can be either Classes or instances of classes self.subjects can either be string or Classes """ for sub in self.subjects: if inspect.isclass(sub): if inspect.isclass(subject): return issubclass(subject, sub) ...
def run_master(self): """ Runs the master service if it is not running :return: """ self._logger.info('Running master on {}'.format(self._master_url)) if self.is_master_up(): return cmd = [self._main_executable, 'master', '--port', self._port(self._master_url)] self._run_service...
def test_start_subjob_raises_if_slave_is_shutdown(self): slave = self._create_slave() slave._is_in_shutdown_mode = True self.assertRaises(SlaveMarkedForShutdownError, slave.start_subjob, Mock())
def test_send_template_without_from_field(self): msg = mail.EmailMessage('Subject', 'Text Body', 'from@example.com', ['to@example.com']) msg.template_name = "PERSONALIZED_SPECIALS" msg.use_template_from = True msg.send() self.assert_mandrill_called("/messages/send-template.json") data = ...
def test_func(self, user): raise NotImplementedError( '{0} is missing implementation of the ' 'test_func method. You should write one.'.format( self.__class__.__name__))
def test_save_blank_object(self): """Test that JSON model can save a blank object as none""" model = JsonModel() self.assertEqual(model.empty_default, {}) model.save() self.assertEqual(model.empty_default, {}) model1 = JsonModel(empty_default={"hey": "now"}) self.assertEqual(model1.empty_...
def __init__(self, attributes): AttributeGetter.__init__(self, attributes) if self.settlement_amount is not None: self.settlement_amount = Decimal(self.settlement_amount) if self.settlement_currency_exchange_rate is not None: self.settlement_currency_exchange_rate = Decimal(self.settlement_...
@override_settings(DJRILL_WEBHOOK_SECRET='abc123') def test_default_secret_name(self): response = self.client.head('/webhook/?secret=abc123') self.assertEqual(response.status_code, 200)
def starts_with(self, value): return Search.Node(self.name, {"starts_with": value})
def test_gauge(self): """Tests the result of the gauge template tag.""" with patch("redis_metrics.templatetags.redis_metric_tags.get_r") as mock_r: inst = mock_r.return_value inst.get_gauge.return_value = 100 size = 50 maximum = 200 result = taglib.gauge("test-slug", max...
@xform def inline(ast, M): return Front.procedure_prune(Front.inline(ast, M), M.entry_points)
def delete(self, *args, **kwargs): """ Delete object and redirect user to configured success URL. :return: Redirect to URL returned by :py:meth:`~.DeletionMixin.get_success_url`. """ self.object.delete() return redirect(self.get_success_url())
def test_user_gets_role_and_id(self): role = Role(name='administrator') self.assertTrue(role.id is None) user = User(email='b2@gmail.com', password='1234', role=role) self.assertTrue(user.id is None) db.session.add(user) db.session.commit() self.assertFalse(role.id is None) self.assertFa...
def test_text_node_is(self): credit_card = Customer.create({ "credit_card": { "number": "4111111111111111", "expiration_date": "05/2010", } }).customer.credit_cards[0] trial_subscription = Subscription.create({ "payment_method_token": credit_card.token, ...
def __repr__(self, d=2): """ return a string representation; 'd' determines amount of significant digits to display """ return "[%.*f, %.*f]" % (d, self.x, d, self.y)
def list_available_solution_stacks(self): """ Returns a list of available solution stacks """ stacks = self.ebs.list_available_solution_stacks() return stacks['ListAvailableSolutionStacksResponse']['ListAvailableSolutionStacksResult']['SolutionStacks']
def grep_word_from_files(): word = sys.argv[1] for filename in sys.argv[2:]: with open(filename) as file: for lino, line in enumerate(file, start=1): if word in line: print("{0}:{1}:{2:.40}".format(filename, lino, line.rstrip()))
def __init__(self, gpg): self.gpg = gpg self.type = None self.fingerprint = None