code
stringlengths
51
2.34k
sequence
stringlengths
186
3.94k
docstring
stringlengths
11
171
def _update_spec_config(self, document_name, spec): self._spec_table.update_item( Key={'_id': '{}'.format(document_name)}, UpdateExpression="SET config = :v", ExpressionAttributeValues={':v': spec}, ReturnValues='ALL_NEW')
module function_definition identifier parameters identifier identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list keyword_argument identifier dictionary pair string string_start string_content string_end call attribute string string_start string_content string_end identifier argument_list identifier keyword_argument identifier string string_start string_content string_end keyword_argument identifier dictionary pair string string_start string_content string_end identifier keyword_argument identifier string string_start string_content string_end
Dynamo implementation of project specific metadata spec
def interpolate_sysenv(line, defaults={}): map = ChainMap(os.environ, defaults) return line.format(**map)
module function_definition identifier parameters identifier default_parameter identifier dictionary block expression_statement assignment identifier call identifier argument_list attribute identifier identifier identifier return_statement call attribute identifier identifier argument_list dictionary_splat identifier
Format line system environment variables + defaults
def deserialize(self, obj): if obj['immutable']: return obj['value'] else: guid = obj['value'] if not guid in object_registry: instance = JSObject(self, guid) object_registry[guid] = instance return object_registry[guid]
module function_definition identifier parameters identifier identifier block if_statement subscript identifier string string_start string_content string_end block return_statement subscript identifier string string_start string_content string_end else_clause block expression_statement assignment identifier subscript identifier string string_start string_content string_end if_statement not_operator comparison_operator identifier identifier block expression_statement assignment identifier call identifier argument_list identifier identifier expression_statement assignment subscript identifier identifier identifier return_statement subscript identifier identifier
Deserialize an object from the front-end.
def load_patt(filename): with open(filename) as f: lines = f.readlines() lst = lines[0].split(',') patt = np.zeros([int(lst[0]), int(lst[1])], dtype=np.complex128) lines.pop(0) for line in lines: lst = line.split(',') n = int(lst[0]) m = int(lst[1]) re = float(lst[2]) im = float(lst[3]) patt[n, m] = re + 1j * im return sp.ScalarPatternUniform(patt, doublesphere=False)
module function_definition identifier parameters identifier block with_statement with_clause with_item as_pattern call identifier argument_list identifier as_pattern_target identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute subscript identifier integer identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list list call identifier argument_list subscript identifier integer call identifier argument_list subscript identifier integer keyword_argument identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list integer for_statement identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call identifier argument_list subscript identifier integer expression_statement assignment identifier call identifier argument_list subscript identifier integer expression_statement assignment identifier call identifier argument_list subscript identifier integer expression_statement assignment identifier call identifier argument_list subscript identifier integer expression_statement assignment subscript identifier identifier identifier binary_operator identifier binary_operator integer identifier return_statement call attribute identifier identifier argument_list identifier keyword_argument identifier false
Loads a file that was saved with the save_patt routine.
def setup_sensors(self): self._add_result = Sensor.float("add.result", "Last ?add result.", "", [-10000, 10000]) self._add_result.set_value(0, Sensor.UNREACHABLE) self._time_result = Sensor.timestamp("time.result", "Last ?time result.", "") self._time_result.set_value(0, Sensor.INACTIVE) self._eval_result = Sensor.string("eval.result", "Last ?eval result.", "") self._eval_result.set_value('', Sensor.UNKNOWN) self._fruit_result = Sensor.discrete("fruit.result", "Last ?pick-fruit result.", "", self.FRUIT) self._fruit_result.set_value('apple', Sensor.ERROR) self.add_sensor(self._add_result) self.add_sensor(self._time_result) self.add_sensor(self._eval_result) self.add_sensor(self._fruit_result)
module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end string string_start string_end list unary_operator integer integer expression_statement call attribute attribute identifier identifier identifier argument_list integer attribute identifier identifier expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end string string_start string_end expression_statement call attribute attribute identifier identifier identifier argument_list integer attribute identifier identifier expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end string string_start string_end expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_end attribute identifier identifier expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end string string_start string_end attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end attribute identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier
Setup some server sensors.
def key_field_name(self): name = 'resource_id' if self.resource: key_field = getmeta(self.resource).key_field if key_field: name = key_field.attname return name
module function_definition identifier parameters identifier block expression_statement assignment identifier string string_start string_content string_end if_statement attribute identifier identifier block expression_statement assignment identifier attribute call identifier argument_list attribute identifier identifier identifier if_statement identifier block expression_statement assignment identifier attribute identifier identifier return_statement identifier
Field identified as the key.
def pinyin(char, variant='mandarin', sep=' ', out='tones'): if len(char) > 1: return sep.join([pinyin(c, variant=variant, sep=sep, out=out) for c in char]) if not is_chinese(char): return char if char in _cd.GBK: char = gbk2big5(char) out_char = _cd.UNIHAN.get(char, {variant: '?({0}'.format(char)}).get(variant, '!({0})'.format(char)) if out != 'tones': out_char = ''.join([tone_converter.get(x, x) for x in out_char]) return out_char
module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end default_parameter identifier string string_start string_content string_end default_parameter identifier string string_start string_content string_end block if_statement comparison_operator call identifier argument_list identifier integer block return_statement call attribute identifier identifier argument_list list_comprehension call identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier for_in_clause identifier identifier if_statement not_operator call identifier argument_list identifier block return_statement identifier if_statement comparison_operator identifier attribute identifier identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call attribute call attribute attribute identifier identifier identifier argument_list identifier dictionary pair identifier call attribute string string_start string_content string_end identifier argument_list identifier identifier argument_list identifier call attribute string string_start string_content string_end identifier argument_list identifier if_statement comparison_operator identifier string string_start string_content string_end block expression_statement assignment identifier call attribute string string_start string_end identifier argument_list list_comprehension call attribute identifier identifier argument_list identifier identifier for_in_clause identifier identifier return_statement identifier
Retrieve Pinyin of a character.
def _load_rules(self): for ruleset in self.active_rulesets: section_name = 'sweep_rules_' + ruleset.lower() try: ruledefs = getattr(self.config, section_name) except AttributeError: raise error.UserError("There is no [{}] section in your configuration" .format(section_name.upper())) for ruledef, filtercond in ruledefs.items(): if ruledef.endswith('.filter'): rulename = ruledef.rsplit('.', 1)[0] rule = SweepRule(ruleset, rulename, int(ruledefs.get(rulename + '.prio', '999')), ruledefs.get(rulename + '.order', self.default_order), parse_cond(filtercond)) self.rules.append(rule) self.rules.sort(key=lambda x: (x.prio, x.name)) return self.rules
module function_definition identifier parameters identifier block for_statement identifier attribute identifier identifier block expression_statement assignment identifier binary_operator string string_start string_content string_end call attribute identifier identifier argument_list try_statement block expression_statement assignment identifier call identifier argument_list attribute identifier identifier identifier except_clause identifier block raise_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list call attribute identifier identifier argument_list for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block if_statement call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement assignment identifier subscript call attribute identifier identifier argument_list string string_start string_content string_end integer integer expression_statement assignment identifier call identifier argument_list identifier identifier call identifier argument_list call attribute identifier identifier argument_list binary_operator identifier string string_start string_content string_end string string_start string_content string_end call attribute identifier identifier argument_list binary_operator identifier string string_start string_content string_end attribute identifier identifier call identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list keyword_argument identifier lambda lambda_parameters identifier tuple attribute identifier identifier attribute identifier identifier return_statement attribute identifier identifier
Load rule definitions from config.
def create(gandi, name, value=None, filename=None): if not value and not filename: raise UsageError('You must set value OR filename.') if value and filename: raise UsageError('You must not set value AND filename.') if filename: value = filename.read() ret = gandi.sshkey.create(name, value) output_keys = ['id', 'name', 'fingerprint'] return output_sshkey(gandi, ret, output_keys)
module function_definition identifier parameters identifier identifier default_parameter identifier none default_parameter identifier none block if_statement boolean_operator not_operator identifier not_operator identifier block raise_statement call identifier argument_list string string_start string_content string_end if_statement boolean_operator identifier identifier block raise_statement call identifier argument_list string string_start string_content string_end if_statement identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier identifier expression_statement assignment identifier list string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end return_statement call identifier argument_list identifier identifier identifier
Create a new SSH key.
def _prepare(self, serialized_obj): nonce = nacl.utils.random(nacl.secret.SecretBox.NONCE_SIZE) encrypted = self.__safe.encrypt(serialized_obj, nonce) signed = self.__signing_key.sign(encrypted) return signed
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list attribute attribute attribute identifier identifier identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier return_statement identifier
Prepare the object to be sent over the untrusted channel.
async def teardown_conn(self, context): client_id = context.user_data self._logger.info("Tearing down client connection: %s", client_id) if client_id not in self.clients: self._logger.warning("client_id %s did not exist in teardown_conn", client_id) else: del self.clients[client_id]
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end identifier if_statement comparison_operator identifier attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end identifier else_clause block delete_statement subscript attribute identifier identifier identifier
Teardown a connection from a client.
def _terminate_process_iou(self): if self._iou_process: log.info('Stopping IOU process for IOU VM "{}" PID={}'.format(self.name, self._iou_process.pid)) try: self._iou_process.terminate() except ProcessLookupError: pass self._started = False self.status = "stopped"
module function_definition identifier parameters identifier block if_statement attribute identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier attribute attribute identifier identifier identifier try_statement block expression_statement call attribute attribute identifier identifier identifier argument_list except_clause identifier block pass_statement expression_statement assignment attribute identifier identifier false expression_statement assignment attribute identifier identifier string string_start string_content string_end
Terminate the IOU process if running
def run(self): connection = self.output().connect() query = ("select pg_terminate_backend(process) " "from STV_SESSIONS " "where db_name=%s " "and user_name != 'rdsdb' " "and process != pg_backend_pid()") cursor = connection.cursor() logger.info('Killing all open Redshift sessions for database: %s', self.database) try: cursor.execute(query, (self.database,)) cursor.close() connection.commit() except psycopg2.DatabaseError as e: if e.message and 'EOF' in e.message: connection.close() logger.info('Pausing %s seconds for Redshift to reset connection', self.connection_reset_wait_seconds) time.sleep(self.connection_reset_wait_seconds) logger.info('Reconnecting to Redshift') connection = self.output().connect() else: raise try: self.output().touch(connection) connection.commit() finally: connection.close() logger.info('Done killing all open Redshift sessions for database: %s', self.database)
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute call attribute identifier identifier argument_list identifier argument_list expression_statement assignment identifier parenthesized_expression concatenated_string string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier try_statement block expression_statement call attribute identifier identifier argument_list identifier tuple attribute identifier identifier expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list except_clause as_pattern attribute identifier identifier as_pattern_target identifier block if_statement boolean_operator attribute identifier identifier comparison_operator string string_start string_content string_end attribute identifier identifier block expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute call attribute identifier identifier argument_list identifier argument_list else_clause block raise_statement try_statement block expression_statement call attribute call attribute identifier identifier argument_list identifier argument_list identifier expression_statement call attribute identifier identifier argument_list finally_clause block expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier
Kill any open Redshift sessions for the given database.
def small_phi_ces_distance(C1, C2): return sum(c.phi for c in C1) - sum(c.phi for c in C2)
module function_definition identifier parameters identifier identifier block return_statement binary_operator call identifier generator_expression attribute identifier identifier for_in_clause identifier identifier call identifier generator_expression attribute identifier identifier for_in_clause identifier identifier
Return the difference in |small_phi| between |CauseEffectStructure|.
def same_pyname(expected, pyname): if expected is None or pyname is None: return False if expected == pyname: return True if type(expected) not in (pynames.ImportedModule, pynames.ImportedName) \ and type(pyname) not in \ (pynames.ImportedModule, pynames.ImportedName): return False return expected.get_definition_location() == \ pyname.get_definition_location() and \ expected.get_object() == pyname.get_object()
module function_definition identifier parameters identifier identifier block if_statement boolean_operator comparison_operator identifier none comparison_operator identifier none block return_statement false if_statement comparison_operator identifier identifier block return_statement true if_statement boolean_operator comparison_operator call identifier argument_list identifier tuple attribute identifier identifier attribute identifier identifier line_continuation comparison_operator call identifier argument_list identifier line_continuation tuple attribute identifier identifier attribute identifier identifier block return_statement false return_statement boolean_operator comparison_operator call attribute identifier identifier argument_list line_continuation call attribute identifier identifier argument_list line_continuation comparison_operator call attribute identifier identifier argument_list call attribute identifier identifier argument_list
Check whether `expected` and `pyname` are the same
def close(self) -> None: self.cancel_pending_tasks() _LOGGER.debug("Disconnected") if self._transport: self._transport.close() self._is_connected = False
module function_definition identifier parameters identifier type none block expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list string string_start string_content string_end if_statement attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement assignment attribute identifier identifier false
Closes connection to the LifeSOS ethernet interface.
def list(self): response = self._client.raw('disk.list', {}) result = response.get() if result.state != 'SUCCESS': raise RuntimeError('failed to list disks: %s' % result.stderr) if result.level != 20: raise RuntimeError('invalid response type from disk.list command') data = result.data.strip() if data: return json.loads(data) else: return {}
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end dictionary expression_statement assignment identifier call attribute identifier identifier argument_list if_statement comparison_operator attribute identifier identifier string string_start string_content string_end block raise_statement call identifier argument_list binary_operator string string_start string_content string_end attribute identifier identifier if_statement comparison_operator attribute identifier identifier integer block raise_statement call identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list if_statement identifier block return_statement call attribute identifier identifier argument_list identifier else_clause block return_statement dictionary
List available block devices
def declare_local_operator(self, type, raw_model=None): onnx_name = self.get_unique_operator_name(str(type)) operator = Operator(onnx_name, self.name, type, raw_model, self.target_opset) self.operators[onnx_name] = operator return operator
module function_definition identifier parameters identifier identifier default_parameter identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier attribute identifier identifier identifier identifier attribute identifier identifier expression_statement assignment subscript attribute identifier identifier identifier identifier return_statement identifier
This function is used to declare new local operator.
def modify_path(): if os.name != "nt": return path = os.environ.get("PATH") if path is None: return try: extra_dll_dir = pkg_resources.resource_filename("bezier", "extra-dll") if os.path.isdir(extra_dll_dir): os.environ["PATH"] = path + os.pathsep + extra_dll_dir except ImportError: pass
module function_definition identifier parameters block if_statement comparison_operator attribute identifier identifier string string_start string_content string_end block return_statement expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end if_statement comparison_operator identifier none block return_statement try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end if_statement call attribute attribute identifier identifier identifier argument_list identifier block expression_statement assignment subscript attribute identifier identifier string string_start string_content string_end binary_operator binary_operator identifier attribute identifier identifier identifier except_clause identifier block pass_statement
Modify the module search path.
def RestoreTaskStoreFactory(store_class, chunk_size, restore_file, save_file): intm_results = np.load(restore_file) intm = intm_results[intm_results.files[0]] idx = np.isnan(intm).flatten().nonzero()[0] partitions = math.ceil(len(idx) / float(chunk_size)) task_store = store_class(partitions, idx.tolist(), save_file) task_store.num_tasks = len(idx) for f in intm_results.files: task_store.__dict__[f] = intm_results[f] return task_store
module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier subscript identifier subscript attribute identifier identifier integer expression_statement assignment identifier subscript call attribute call attribute call attribute identifier identifier argument_list identifier identifier argument_list identifier argument_list integer expression_statement assignment identifier call attribute identifier identifier argument_list binary_operator call identifier argument_list identifier call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier call attribute identifier identifier argument_list identifier expression_statement assignment attribute identifier identifier call identifier argument_list identifier for_statement identifier attribute identifier identifier block expression_statement assignment subscript attribute identifier identifier identifier subscript identifier identifier return_statement identifier
Restores a task store from file.
def local_run(): server_software = os.environ.get('SERVER_SOFTWARE') if server_software is None: return True if 'remote_api' in server_software: return False if server_software.startswith(('Development', 'testutil')): return True return False
module function_definition identifier parameters block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end if_statement comparison_operator identifier none block return_statement true if_statement comparison_operator string string_start string_content string_end identifier block return_statement false if_statement call attribute identifier identifier argument_list tuple string string_start string_content string_end string string_start string_content string_end block return_statement true return_statement false
Whether we should hit GCS dev appserver stub.
def deps_tree(self): dependencies = self.dependencies + [self.name] if self.repo == "sbo": for dep in dependencies: deps = Requires(flag="").sbo(dep) if dep not in self.deps_dict.values(): self.deps_dict[dep] = Utils().dimensional_list(deps) else: for dep in dependencies: deps = Dependencies(self.repo, self.black).binary(dep, flag="") if dep not in self.deps_dict.values(): self.deps_dict[dep] = Utils().dimensional_list(deps)
module function_definition identifier parameters identifier block expression_statement assignment identifier binary_operator attribute identifier identifier list attribute identifier identifier if_statement comparison_operator attribute identifier identifier string string_start string_content string_end block for_statement identifier identifier block expression_statement assignment identifier call attribute call identifier argument_list keyword_argument identifier string string_start string_end identifier argument_list identifier if_statement comparison_operator identifier call attribute attribute identifier identifier identifier argument_list block expression_statement assignment subscript attribute identifier identifier identifier call attribute call identifier argument_list identifier argument_list identifier else_clause block for_statement identifier identifier block expression_statement assignment identifier call attribute call identifier argument_list attribute identifier identifier attribute identifier identifier identifier argument_list identifier keyword_argument identifier string string_start string_end if_statement comparison_operator identifier call attribute attribute identifier identifier identifier argument_list block expression_statement assignment subscript attribute identifier identifier identifier call attribute call identifier argument_list identifier argument_list identifier
Package dependencies image map file
def redef(obj, key, value, **kwargs): return Redef(obj, key, value=value, **kwargs)
module function_definition identifier parameters identifier identifier identifier dictionary_splat_pattern identifier block return_statement call identifier argument_list identifier identifier keyword_argument identifier identifier dictionary_splat identifier
A static constructor helper function
def push_supply(self, tokens): logger.debug("Pushing supply data: %s" % tokens) bus = self.case.buses[tokens["bus_no"] - 1] n_generators = len([g for g in self.case.generators if g.bus == bus]) if n_generators == 0: logger.error("No generator at bus [%s] for matching supply" % bus) return elif n_generators > 1: g = [g for g in self.case.generators if g.bus == bus][0] logger.warning( "More than one generator at bus [%s] for demand. Using the " "first one [%s]." % (bus, g) ) else: g = [g for g in self.case.generators if g.bus == bus][0] g.pcost_model = "poly" g.poly_coeffs = ( tokens["p_fixed"], tokens["p_proportional"], tokens["p_quadratic"] )
module function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end identifier expression_statement assignment identifier subscript attribute attribute identifier identifier identifier binary_operator subscript identifier string string_start string_content string_end integer expression_statement assignment identifier call identifier argument_list list_comprehension identifier for_in_clause identifier attribute attribute identifier identifier identifier if_clause comparison_operator attribute identifier identifier identifier if_statement comparison_operator identifier integer block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end identifier return_statement elif_clause comparison_operator identifier integer block expression_statement assignment identifier subscript list_comprehension identifier for_in_clause identifier attribute attribute identifier identifier identifier if_clause comparison_operator attribute identifier identifier identifier integer expression_statement call attribute identifier identifier argument_list binary_operator concatenated_string string string_start string_content string_end string string_start string_content string_end tuple identifier identifier else_clause block expression_statement assignment identifier subscript list_comprehension identifier for_in_clause identifier attribute attribute identifier identifier identifier if_clause comparison_operator attribute identifier identifier identifier integer expression_statement assignment attribute identifier identifier string string_start string_content string_end expression_statement assignment attribute identifier identifier tuple subscript identifier string string_start string_content string_end subscript identifier string string_start string_content string_end subscript identifier string string_start string_content string_end
Adds OPF and CPF data to a Generator.
def mol(self): if self._mol is None: apiurl = 'http://www.chemspider.com/MassSpecAPI.asmx/GetRecordMol?csid=%s&calc3d=false&token=%s' % (self.csid,TOKEN) response = urlopen(apiurl) tree = ET.parse(response) self._mol = tree.getroot().text return self._mol
module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier none block expression_statement assignment identifier binary_operator string string_start string_content string_end tuple attribute identifier identifier identifier expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment attribute identifier identifier attribute call attribute identifier identifier argument_list identifier return_statement attribute identifier identifier
Return record in MOL format
def tempnam(): stderr = sys.stderr try: sys.stderr = cStringIO.StringIO() return os.tempnam(None, 'tess_') finally: sys.stderr = stderr
module function_definition identifier parameters block expression_statement assignment identifier attribute identifier identifier try_statement block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list return_statement call attribute identifier identifier argument_list none string string_start string_content string_end finally_clause block expression_statement assignment attribute identifier identifier identifier
returns a temporary file-name
def _construct_location_stack_entry(location, num_traverses): if not isinstance(num_traverses, int) or num_traverses < 0: raise AssertionError(u'Attempted to create a LocationStackEntry namedtuple with an invalid ' u'value for "num_traverses" {}. This is not allowed.' .format(num_traverses)) if not isinstance(location, Location): raise AssertionError(u'Attempted to create a LocationStackEntry namedtuple with an invalid ' u'value for "location" {}. This is not allowed.' .format(location)) return LocationStackEntry(location=location, num_traverses=num_traverses)
module function_definition identifier parameters identifier identifier block if_statement boolean_operator not_operator call identifier argument_list identifier identifier comparison_operator identifier integer block raise_statement call identifier argument_list call attribute concatenated_string string string_start string_content string_end string string_start string_content string_end identifier argument_list identifier if_statement not_operator call identifier argument_list identifier identifier block raise_statement call identifier argument_list call attribute concatenated_string string string_start string_content string_end string string_start string_content string_end identifier argument_list identifier return_statement call identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier
Return a LocationStackEntry namedtuple with the specified parameters.
def _draw_lines(self, bg, colour, extent, line, xo, yo): coords = [self._scale_coords(x, y, extent, xo, yo) for x, y in line] self._draw_lines_internal(coords, colour, bg)
module function_definition identifier parameters identifier identifier identifier identifier identifier identifier identifier block expression_statement assignment identifier list_comprehension call attribute identifier identifier argument_list identifier identifier identifier identifier identifier for_in_clause pattern_list identifier identifier identifier expression_statement call attribute identifier identifier argument_list identifier identifier identifier
Draw a set of lines from a vector tile.
def close_application(self): self._debug('Closing application with session id %s' % self._current_application().session_id) self._cache.close()
module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end attribute call attribute identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list
Closes the current application and also close webdriver session.
def FaultFromFaultMessage(ps): pyobj = ps.Parse(FaultType.typecode) if pyobj.detail == None: detailany = None else: detailany = pyobj.detail.any return Fault(pyobj.faultcode, pyobj.faultstring, pyobj.faultactor, detailany)
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier if_statement comparison_operator attribute identifier identifier none block expression_statement assignment identifier none else_clause block expression_statement assignment identifier attribute attribute identifier identifier identifier return_statement call identifier argument_list attribute identifier identifier attribute identifier identifier attribute identifier identifier identifier
Parse the message as a fault.
def __print(self, msg): self.announce(msg, level=distutils.log.INFO)
module function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list identifier keyword_argument identifier attribute attribute identifier identifier identifier
Shortcut for printing with the distutils logger.
def toggle_view(self, *args, **kwargs): group_to_display = self.views.popleft() self.cur_view.value = group_to_display for repo in self.tools_tc: for tool in self.tools_tc[repo]: t_groups = self.manifest.option(tool, 'groups')[1] if group_to_display not in t_groups and \ group_to_display != 'all groups': self.tools_tc[repo][tool].value = False self.tools_tc[repo][tool].hidden = True else: self.tools_tc[repo][tool].value = True self.tools_tc[repo][tool].hidden = False self.display() self.views.append(group_to_display)
module function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement assignment attribute attribute identifier identifier identifier identifier for_statement identifier attribute identifier identifier block for_statement identifier subscript attribute identifier identifier identifier block expression_statement assignment identifier subscript call attribute attribute identifier identifier identifier argument_list identifier string string_start string_content string_end integer if_statement boolean_operator comparison_operator identifier identifier line_continuation comparison_operator identifier string string_start string_content string_end block expression_statement assignment attribute subscript subscript attribute identifier identifier identifier identifier identifier false expression_statement assignment attribute subscript subscript attribute identifier identifier identifier identifier identifier true else_clause block expression_statement assignment attribute subscript subscript attribute identifier identifier identifier identifier identifier true expression_statement assignment attribute subscript subscript attribute identifier identifier identifier identifier identifier false expression_statement call attribute identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list identifier
Toggles the view between different groups
async def fastStreamedQuery(self, url, *, headers=None, verify=True): response = await self.session.get(url, headers=self._buildHeaders(headers), timeout=HTTP_SHORT_TIMEOUT, ssl=verify) response.raise_for_status() return response
module function_definition identifier parameters identifier identifier keyword_separator default_parameter identifier none default_parameter identifier true block expression_statement assignment identifier await call attribute attribute identifier identifier identifier argument_list identifier keyword_argument identifier call attribute identifier identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier identifier expression_statement call attribute identifier identifier argument_list return_statement identifier
Send a GET request with short timeout, do not retry, and return streamed response.
def setdefault (self, key, *args): assert isinstance(key, basestring) return dict.setdefault(self, key.lower(), *args)
module function_definition identifier parameters identifier identifier list_splat_pattern identifier block assert_statement call identifier argument_list identifier identifier return_statement call attribute identifier identifier argument_list identifier call attribute identifier identifier argument_list list_splat identifier
Set lowercase key value and return.
def match_patterns(pathname, patterns): for pattern in patterns: if fnmatch(pathname, pattern): return True return False
module function_definition identifier parameters identifier identifier block for_statement identifier identifier block if_statement call identifier argument_list identifier identifier block return_statement true return_statement false
Returns ``True`` if the pathname matches any of the given patterns.
def convert_trig_to_hdf(workflow, hdfbank, xml_trigger_files, out_dir, tags=None): if tags is None: tags = [] logging.info('convert single inspiral trigger files to hdf5') make_analysis_dir(out_dir) trig_files = FileList() for ifo, insp_group in zip(*xml_trigger_files.categorize_by_attr('ifo')): trig2hdf_exe = PyCBCTrig2HDFExecutable(workflow.cp, 'trig2hdf', ifos=ifo, out_dir=out_dir, tags=tags) _, insp_bundles = insp_group.categorize_by_attr('segment') for insps in insp_bundles: trig2hdf_node = trig2hdf_exe.create_node(insps, hdfbank[0]) workflow.add_node(trig2hdf_node) trig_files += trig2hdf_node.output_files return trig_files
module function_definition identifier parameters identifier identifier identifier identifier default_parameter identifier none block if_statement comparison_operator identifier none block expression_statement assignment identifier list expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list for_statement pattern_list identifier identifier call identifier argument_list list_splat call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement assignment identifier call identifier argument_list attribute identifier identifier string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end for_statement identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier subscript identifier integer expression_statement call attribute identifier identifier argument_list identifier expression_statement augmented_assignment identifier attribute identifier identifier return_statement identifier
Return the list of hdf5 trigger files outputs
def transform_outgoing(self, son, collection): if isinstance(son, dict): for (key, value) in son.items(): if self.replacement in key: k = self.revert_key(key) son[k] = self.transform_outgoing(son.pop(key), collection) elif isinstance(value, dict): son[key] = self.transform_outgoing(value, collection) elif isinstance(value, list): son[key] = [self.transform_outgoing(item, collection) for item in value] return son elif isinstance(son, list): return [self.transform_outgoing(item, collection) for item in son] else: return son
module function_definition identifier parameters identifier identifier identifier block if_statement call identifier argument_list identifier identifier block for_statement tuple_pattern identifier identifier call attribute identifier identifier argument_list block if_statement comparison_operator attribute identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment subscript identifier identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier identifier elif_clause call identifier argument_list identifier identifier block expression_statement assignment subscript identifier identifier call attribute identifier identifier argument_list identifier identifier elif_clause call identifier argument_list identifier identifier block expression_statement assignment subscript identifier identifier list_comprehension call attribute identifier identifier argument_list identifier identifier for_in_clause identifier identifier return_statement identifier elif_clause call identifier argument_list identifier identifier block return_statement list_comprehension call attribute identifier identifier argument_list identifier identifier for_in_clause identifier identifier else_clause block return_statement identifier
Recursively restore all transformed keys.
def in_attack_range_of(self, unit: Unit, bonus_distance: Union[int, float] = 0) -> "Units": return self.filter(lambda x: unit.target_in_range(x, bonus_distance=bonus_distance))
module function_definition identifier parameters identifier typed_parameter identifier type identifier typed_default_parameter identifier type generic_type identifier type_parameter type identifier type identifier integer type string string_start string_content string_end block return_statement call attribute identifier identifier argument_list lambda lambda_parameters identifier call attribute identifier identifier argument_list identifier keyword_argument identifier identifier
Filters units that are in attack range of the unit in parameter
def rgb_reduce(r, g, b, mode=8): colours = ANSI_COLOURS[:mode] matches = [(rgb_distance(c, map(int, [r, g, b])), i) for i, c in enumerate(colours)] matches.sort() return sequence('m')(str(30 + matches[0][1]))
module function_definition identifier parameters identifier identifier identifier default_parameter identifier integer block expression_statement assignment identifier subscript identifier slice identifier expression_statement assignment identifier list_comprehension tuple call identifier argument_list identifier call identifier argument_list identifier list identifier identifier identifier identifier for_in_clause pattern_list identifier identifier call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list return_statement call call identifier argument_list string string_start string_content string_end argument_list call identifier argument_list binary_operator integer subscript subscript identifier integer integer
Convert an RGB colour to 8 or 16 colour ANSI graphics.
def to_python(self, value): "Normalize data to a list of strings." if not value: return [] return [v.strip() for v in value.splitlines() if v != ""]
module function_definition identifier parameters identifier identifier block expression_statement string string_start string_content string_end if_statement not_operator identifier block return_statement list return_statement list_comprehension call attribute identifier identifier argument_list for_in_clause identifier call attribute identifier identifier argument_list if_clause comparison_operator identifier string string_start string_end
Normalize data to a list of strings.
def _get_all_children(self,): res = '' if self.child_nodes: for c in self.child_nodes: res += ' child = ' + str(c) + '\n' if c.child_nodes: for grandchild in c.child_nodes: res += ' child = ' + str(grandchild) + '\n' else: res += ' child = None\n' return res
module function_definition identifier parameters identifier block expression_statement assignment identifier string string_start string_end if_statement attribute identifier identifier block for_statement identifier attribute identifier identifier block expression_statement augmented_assignment identifier binary_operator binary_operator string string_start string_content string_end call identifier argument_list identifier string string_start string_content escape_sequence string_end if_statement attribute identifier identifier block for_statement identifier attribute identifier identifier block expression_statement augmented_assignment identifier binary_operator binary_operator string string_start string_content string_end call identifier argument_list identifier string string_start string_content escape_sequence string_end else_clause block expression_statement augmented_assignment identifier string string_start string_content escape_sequence string_end return_statement identifier
return the list of children of a node
def queryables(self): return dict( [(a.cname, a) for a in self.index_axes] + [(self.storage_obj_type._AXIS_NAMES[axis], None) for axis, values in self.non_index_axes] + [(v.cname, v) for v in self.values_axes if v.name in set(self.data_columns)] )
module function_definition identifier parameters identifier block return_statement call identifier argument_list binary_operator binary_operator list_comprehension tuple attribute identifier identifier identifier for_in_clause identifier attribute identifier identifier list_comprehension tuple subscript attribute attribute identifier identifier identifier identifier none for_in_clause pattern_list identifier identifier attribute identifier identifier list_comprehension tuple attribute identifier identifier identifier for_in_clause identifier attribute identifier identifier if_clause comparison_operator attribute identifier identifier call identifier argument_list attribute identifier identifier
return a dict of the kinds allowable columns for this object
def find_interconnect_ports(self): phy_port_list = self.ext_br_obj.get_port_name_list() int_port_list = self.integ_br_obj.get_port_name_list() for port in phy_port_list: is_patch = ovs_lib.is_patch(self.root_helper, port) if is_patch: peer_port = ovs_lib.get_peer(self.root_helper, port) if peer_port in int_port_list: return port, peer_port return None, None
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list for_statement identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier identifier if_statement identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier identifier if_statement comparison_operator identifier identifier block return_statement expression_list identifier identifier return_statement expression_list none none
Find the internal veth or patch ports.
def delete_thumbnails(relative_source_path, root=None, basedir=None, subdir=None, prefix=None): thumbs = thumbnails_for_file(relative_source_path, root, basedir, subdir, prefix) return _delete_using_thumbs_list(thumbs)
module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier none default_parameter identifier none default_parameter identifier none block expression_statement assignment identifier call identifier argument_list identifier identifier identifier identifier identifier return_statement call identifier argument_list identifier
Delete all thumbnails for a source image.
def message(self, bot, comm): super(KarmaAdv, self).message(bot, comm) if not comm['directed'] and not comm['pm']: msg = comm['message'].strip().lower() words = self.regstr.findall(msg) karmas = self.modify_karma(words) if comm['user'] in karmas.keys(): if karmas[comm['user']] <= 0: bot.reply(comm, "Don't be so hard on yourself.") else: bot.reply(comm, "Tisk, tisk, no up'ing your own karma.") self.update_db(comm["user"], karmas)
module function_definition identifier parameters identifier identifier identifier block expression_statement call attribute call identifier argument_list identifier identifier identifier argument_list identifier identifier if_statement boolean_operator not_operator subscript identifier string string_start string_content string_end not_operator subscript identifier string string_start string_content string_end block expression_statement assignment identifier call attribute call attribute subscript identifier string string_start string_content string_end identifier argument_list identifier argument_list expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement comparison_operator subscript identifier string string_start string_content string_end call attribute identifier identifier argument_list block if_statement comparison_operator subscript identifier subscript identifier string string_start string_content string_end integer block expression_statement call attribute identifier identifier argument_list identifier string string_start string_content string_end else_clause block expression_statement call attribute identifier identifier argument_list identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list subscript identifier string string_start string_content string_end identifier
Check for strings ending with 2 or more '-' or '+'
def skip_connection_distance(a, b): if a[2] != b[2]: return 1.0 len_a = abs(a[1] - a[0]) len_b = abs(b[1] - b[0]) return (abs(a[0] - b[0]) + abs(len_a - len_b)) / (max(a[0], b[0]) + max(len_a, len_b))
module function_definition identifier parameters identifier identifier block if_statement comparison_operator subscript identifier integer subscript identifier integer block return_statement float expression_statement assignment identifier call identifier argument_list binary_operator subscript identifier integer subscript identifier integer expression_statement assignment identifier call identifier argument_list binary_operator subscript identifier integer subscript identifier integer return_statement binary_operator parenthesized_expression binary_operator call identifier argument_list binary_operator subscript identifier integer subscript identifier integer call identifier argument_list binary_operator identifier identifier parenthesized_expression binary_operator call identifier argument_list subscript identifier integer subscript identifier integer call identifier argument_list identifier identifier
The distance between two skip-connections.
def can_convert(x): if len(x.shape) < 2 or len(x.shape) > 3: return False dtype = x.dtype height = x.shape[0] width = x.shape[1] channels = 1 if len(x.shape) == 3: channels = x.shape[2] if channels > 4: return False return True
module function_definition identifier parameters identifier block if_statement boolean_operator comparison_operator call identifier argument_list attribute identifier identifier integer comparison_operator call identifier argument_list attribute identifier identifier integer block return_statement false expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier subscript attribute identifier identifier integer expression_statement assignment identifier subscript attribute identifier identifier integer expression_statement assignment identifier integer if_statement comparison_operator call identifier argument_list attribute identifier identifier integer block expression_statement assignment identifier subscript attribute identifier identifier integer if_statement comparison_operator identifier integer block return_statement false return_statement true
Returns True if x can be converted to an image, False otherwise.
def round_corner(radius, fill): corner = Image.new('L', (radius, radius), 0) draw = ImageDraw.Draw(corner) draw.pieslice((0, 0, radius * 2, radius * 2), 180, 270, fill=fill) return corner
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end tuple identifier identifier integer expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list tuple integer integer binary_operator identifier integer binary_operator identifier integer integer integer keyword_argument identifier identifier return_statement identifier
Draw a round corner
def object_path(self, objhash): return os.path.join(self._path, self.OBJ_DIR, objhash)
module function_definition identifier parameters identifier identifier block return_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier attribute identifier identifier identifier
Returns the path to an object file based on its hash.
def _prepare_target(ts, tables, buffer_size): for tablename in tables: table = ts[tablename] table[:] = [] if buffer_size is not None and table.is_attached(): table.write(append=False)
module function_definition identifier parameters identifier identifier identifier block for_statement identifier identifier block expression_statement assignment identifier subscript identifier identifier expression_statement assignment subscript identifier slice list if_statement boolean_operator comparison_operator identifier none call attribute identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list keyword_argument identifier false
Clear tables affected by the processing.
def request(self, action): ev = threading.Event() first = False with self.__lock: if len(self.__events) == 0: first = True self.__events.append(ev) if first: action() return ev
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier false with_statement with_clause with_item attribute identifier identifier block if_statement comparison_operator call identifier argument_list attribute identifier identifier integer block expression_statement assignment identifier true expression_statement call attribute attribute identifier identifier identifier argument_list identifier if_statement identifier block expression_statement call identifier argument_list return_statement identifier
Request an action to be performed, in case one.
def _save_file_and_pos(self): if not self._pos_changed: return with open(self.pos_storage_filename, 'w+') as f: _pos = '%s:%s' % (self._log_file, self._log_pos) _logger.debug('Saving position %s to file %s' % (_pos, self.pos_storage_filename)) f.write(_pos) self._pos_changed = False
module function_definition identifier parameters identifier block if_statement not_operator attribute identifier identifier block return_statement with_statement with_clause with_item as_pattern call identifier argument_list attribute identifier identifier string string_start string_content string_end as_pattern_target identifier block expression_statement assignment identifier binary_operator string string_start string_content string_end tuple attribute identifier identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end tuple identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment attribute identifier identifier false
Save current position into file
def periodicity(freq_or_frame): if hasattr(freq_or_frame, 'rule_code'): rc = freq_or_frame.rule_code rc = rc.split('-')[0] factor = PER_YEAR_MAP.get(rc, None) if factor is not None: return factor / abs(freq_or_frame.n) else: raise Exception('Failed to determine periodicity. No factor mapping for %s' % freq_or_frame) elif isinstance(freq_or_frame, basestring): factor = PER_YEAR_MAP.get(freq_or_frame, None) if factor is not None: return factor else: raise Exception('Failed to determine periodicity. No factor mapping for %s' % freq_or_frame) elif isinstance(freq_or_frame, (pd.Series, pd.DataFrame, pd.TimeSeries)): freq = freq_or_frame.index.freq if not freq: freq = pd.infer_freq(freq_or_frame.index) if freq: return periodicity(freq) else: import warnings freq = guess_freq(freq_or_frame.index) warnings.warn('frequency not set. guessed it to be %s' % freq) return periodicity(freq) else: return periodicity(freq) else: raise ValueError("periodicity expects DataFrame, Series, or rule_code property")
module function_definition identifier parameters identifier block if_statement call identifier argument_list identifier string string_start string_content string_end block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier subscript call attribute identifier identifier argument_list string string_start string_content string_end integer expression_statement assignment identifier call attribute identifier identifier argument_list identifier none if_statement comparison_operator identifier none block return_statement binary_operator identifier call identifier argument_list attribute identifier identifier else_clause block raise_statement call identifier argument_list binary_operator string string_start string_content string_end identifier elif_clause call identifier argument_list identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier none if_statement comparison_operator identifier none block return_statement identifier else_clause block raise_statement call identifier argument_list binary_operator string string_start string_content string_end identifier elif_clause call identifier argument_list identifier tuple attribute identifier identifier attribute identifier identifier attribute identifier identifier block expression_statement assignment identifier attribute attribute identifier identifier identifier if_statement not_operator identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier if_statement identifier block return_statement call identifier argument_list identifier else_clause block import_statement dotted_name identifier expression_statement assignment identifier call identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end identifier return_statement call identifier argument_list identifier else_clause block return_statement call identifier argument_list identifier else_clause block raise_statement call identifier argument_list string string_start string_content string_end
resolve the number of periods per year
def stat(self, filename, timeout=None): transport = StatFilesyncTransport(self.stream) transport.write_data('STAT', filename, timeout) stat_msg = transport.read_message(timeout) stat_msg.assert_command_is('STAT') return DeviceFileStat(filename, stat_msg.mode, stat_msg.size, stat_msg.time)
module function_definition identifier parameters identifier identifier default_parameter identifier none block expression_statement assignment identifier call identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end return_statement call identifier argument_list identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier
Return device file stat.
def device_connect(device_id): success = False if device_id in devices: devices[device_id].connect() success = True return jsonify(success=success)
module function_definition identifier parameters identifier block expression_statement assignment identifier false if_statement comparison_operator identifier identifier block expression_statement call attribute subscript identifier identifier identifier argument_list expression_statement assignment identifier true return_statement call identifier argument_list keyword_argument identifier identifier
Force a connection attempt via HTTP GET.
def _get_schema(name): item = datalab.utils.commands.get_notebook_item(name) if not item: item = _get_table(name) if isinstance(item, datalab.bigquery.Schema): return item if hasattr(item, 'schema') and isinstance(item.schema, datalab.bigquery._schema.Schema): return item.schema return None
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list identifier if_statement not_operator identifier block expression_statement assignment identifier call identifier argument_list identifier if_statement call identifier argument_list identifier attribute attribute identifier identifier identifier block return_statement identifier if_statement boolean_operator call identifier argument_list identifier string string_start string_content string_end call identifier argument_list attribute identifier identifier attribute attribute attribute identifier identifier identifier identifier block return_statement attribute identifier identifier return_statement none
Given a variable or table name, get the Schema if it exists.
def handle_code(code): "Handle a key or sequence of keys in braces" code_keys = [] if code in CODES: code_keys.append(VirtualKeyAction(CODES[code])) elif len(code) == 1: code_keys.append(KeyAction(code)) elif ' ' in code: to_repeat, count = code.rsplit(None, 1) if to_repeat == "PAUSE": try: pause_time = float(count) except ValueError: raise KeySequenceError('invalid pause time %s'% count) code_keys.append(PauseAction(pause_time)) else: try: count = int(count) except ValueError: raise KeySequenceError( 'invalid repetition count %s'% count) if to_repeat in CODES: code_keys.extend( [VirtualKeyAction(CODES[to_repeat])] * count) else: to_repeat = parse_keys(to_repeat) if isinstance(to_repeat, list): keys = to_repeat * count else: keys = [to_repeat] * count code_keys.extend(keys) else: raise RuntimeError("Unknown code: %s"% code) return code_keys
module function_definition identifier parameters identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier list if_statement comparison_operator identifier identifier block expression_statement call attribute identifier identifier argument_list call identifier argument_list subscript identifier identifier elif_clause comparison_operator call identifier argument_list identifier integer block expression_statement call attribute identifier identifier argument_list call identifier argument_list identifier elif_clause comparison_operator string string_start string_content string_end identifier block expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list none integer if_statement comparison_operator identifier string string_start string_content string_end block try_statement block expression_statement assignment identifier call identifier argument_list identifier except_clause identifier block raise_statement call identifier argument_list binary_operator string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list call identifier argument_list identifier else_clause block try_statement block expression_statement assignment identifier call identifier argument_list identifier except_clause identifier block raise_statement call identifier argument_list binary_operator string string_start string_content string_end identifier if_statement comparison_operator identifier identifier block expression_statement call attribute identifier identifier argument_list binary_operator list call identifier argument_list subscript identifier identifier identifier else_clause block expression_statement assignment identifier call identifier argument_list identifier if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier binary_operator identifier identifier else_clause block expression_statement assignment identifier binary_operator list identifier identifier expression_statement call attribute identifier identifier argument_list identifier else_clause block raise_statement call identifier argument_list binary_operator string string_start string_content string_end identifier return_statement identifier
Handle a key or sequence of keys in braces
def _filterDictToStr(self, filterDict): values = [] for key, vals in filterDict.items(): if key not in ('contentRating', 'label'): raise BadRequest('Unknown filter key: %s', key) values.append('%s=%s' % (key, '%2C'.join(vals))) return '|'.join(values)
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier list for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block if_statement comparison_operator identifier tuple string string_start string_content string_end string string_start string_content string_end block raise_statement call identifier argument_list string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end tuple identifier call attribute string string_start string_content string_end identifier argument_list identifier return_statement call attribute string string_start string_content string_end identifier argument_list identifier
Converts friend filters to a string representation for transport.
def callback(newstate): print('callback: ', newstate) if newstate == modem.STATE_RING: if state == modem.STATE_IDLE: att = {"cid_time": modem.get_cidtime, "cid_number": modem.get_cidnumber, "cid_name": modem.get_cidname} print('Ringing', att) elif newstate == modem.STATE_CALLERID: att = {"cid_time": modem.get_cidtime, "cid_number": modem.get_cidnumber, "cid_name": modem.get_cidname} print('CallerID', att) elif newstate == modem.STATE_IDLE: print('idle') return
module function_definition identifier parameters identifier block expression_statement call identifier argument_list string string_start string_content string_end identifier if_statement comparison_operator identifier attribute identifier identifier block if_statement comparison_operator identifier attribute identifier identifier block expression_statement assignment identifier dictionary pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier expression_statement call identifier argument_list string string_start string_content string_end identifier elif_clause comparison_operator identifier attribute identifier identifier block expression_statement assignment identifier dictionary pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier expression_statement call identifier argument_list string string_start string_content string_end identifier elif_clause comparison_operator identifier attribute identifier identifier block expression_statement call identifier argument_list string string_start string_content string_end return_statement
Callback from modem, process based on new state
def _parse_button(self, keypad, component_xml): button_xml = component_xml.find('Button') name = button_xml.get('Engraving') button_type = button_xml.get('ButtonType') direction = button_xml.get('Direction') if button_type == 'SingleSceneRaiseLower': name = 'Dimmer ' + direction if not name: name = "Unknown Button" button = Button(self._lutron, keypad, name=name, num=int(component_xml.get('ComponentNumber')), button_type=button_type, direction=direction) return button
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end if_statement comparison_operator identifier string string_start string_content string_end block expression_statement assignment identifier binary_operator string string_start string_content string_end identifier if_statement not_operator identifier block expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier call identifier argument_list attribute identifier identifier identifier keyword_argument identifier identifier keyword_argument identifier call identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier identifier return_statement identifier
Parses a button device that part of a keypad.
def _handler_http(self, result): monitor = result['monitor'] self.thread_debug("process_http", data=monitor, module='handler') self.stats.http_handled += 1 logargs = { 'type':"metric", 'endpoint': result['url'], 'pipeline': monitor['pipeline'], 'service': monitor['service'], 'instance': monitor['instance'], 'status': result['status'], 'elapsed-ms': round(result['elapsedms'], 5), 'code': result['code'] } self.NOTIFY(result['message'], **logargs) if result['status'] != self.instances[monitor['instance']]['status']: self.instances[monitor['instance']]['status'] = result['status'] self.rcs.patch('instance', monitor['instance'], {'status': result['status']})
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier subscript identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier string string_start string_content string_end expression_statement augmented_assignment attribute attribute identifier identifier identifier integer expression_statement assignment identifier dictionary pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end subscript identifier string string_start string_content string_end pair string string_start string_content string_end subscript identifier string string_start string_content string_end pair string string_start string_content string_end subscript identifier string string_start string_content string_end pair string string_start string_content string_end subscript identifier string string_start string_content string_end pair string string_start string_content string_end subscript identifier string string_start string_content string_end pair string string_start string_content string_end call identifier argument_list subscript identifier string string_start string_content string_end integer pair string string_start string_content string_end subscript identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list subscript identifier string string_start string_content string_end dictionary_splat identifier if_statement comparison_operator subscript identifier string string_start string_content string_end subscript subscript attribute identifier identifier subscript identifier string string_start string_content string_end string string_start string_content string_end block expression_statement assignment subscript subscript attribute identifier identifier subscript identifier string string_start string_content string_end string string_start string_content string_end subscript identifier string string_start string_content string_end expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end subscript identifier string string_start string_content string_end dictionary pair string string_start string_content string_end subscript identifier string string_start string_content string_end
Handle the result of an http monitor
def __json(self): if self.exclude_list is None: self.exclude_list = [] fields = {} for key, item in vars(self).items(): if hasattr(self, '_sa_instance_state'): if len(orm.attributes.instance_state(self).unloaded) > 0: mapper = inspect(self) for column in mapper.attrs: column.key column.value if str(key).startswith('_') or key in self.exclude_list: continue fields[key] = item obj = Json.safe_object(fields) return str(obj)
module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier none block expression_statement assignment attribute identifier identifier list expression_statement assignment identifier dictionary for_statement pattern_list identifier identifier call attribute call identifier argument_list identifier identifier argument_list block if_statement call identifier argument_list identifier string string_start string_content string_end block if_statement comparison_operator call identifier argument_list attribute call attribute attribute identifier identifier identifier argument_list identifier identifier integer block expression_statement assignment identifier call identifier argument_list identifier for_statement identifier attribute identifier identifier block expression_statement attribute identifier identifier expression_statement attribute identifier identifier if_statement boolean_operator call attribute call identifier argument_list identifier identifier argument_list string string_start string_content string_end comparison_operator identifier attribute identifier identifier block continue_statement expression_statement assignment subscript identifier identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier return_statement call identifier argument_list identifier
Using the exclude lists, convert fields to a string.
def _get_counts(self, f): self._consolidate_inplace() counts = dict() for b in self.blocks: v = f(b) counts[v] = counts.get(v, 0) + b.shape[0] return counts
module function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list expression_statement assignment identifier call identifier argument_list for_statement identifier attribute identifier identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment subscript identifier identifier binary_operator call attribute identifier identifier argument_list identifier integer subscript attribute identifier identifier integer return_statement identifier
return a dict of the counts of the function in BlockManager
def _fill(self): right_now = time.time() time_diff = right_now - self._last_fill if time_diff < 0: return self._count = min( self._count + self._fill_rate * time_diff, self._capacity, ) self._last_fill = right_now
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier binary_operator identifier attribute identifier identifier if_statement comparison_operator identifier integer block return_statement expression_statement assignment attribute identifier identifier call identifier argument_list binary_operator attribute identifier identifier binary_operator attribute identifier identifier identifier attribute identifier identifier expression_statement assignment attribute identifier identifier identifier
Fills bucket with accrued tokens since last fill.
def save_proficiency(self, proficiency_form, *args, **kwargs): if proficiency_form.is_for_update(): return self.update_proficiency(proficiency_form, *args, **kwargs) else: return self.create_proficiency(proficiency_form, *args, **kwargs)
module function_definition identifier parameters identifier identifier list_splat_pattern identifier dictionary_splat_pattern identifier block if_statement call attribute identifier identifier argument_list block return_statement call attribute identifier identifier argument_list identifier list_splat identifier dictionary_splat identifier else_clause block return_statement call attribute identifier identifier argument_list identifier list_splat identifier dictionary_splat identifier
Pass through to provider ProficiencyAdminSession.update_proficiency
def parse(data, datafile): data._last_travel = [0, [0]] while True: section_number = int(datafile.readline()) if not section_number: break store = globals().get('section%d' % section_number) while True: fields = [ (int(field) if field.lstrip('-').isdigit() else field) for field in datafile.readline().strip().split('\t') ] if fields[0] == -1: break store(data, *fields) del data._last_travel del data._object data.object_list = sorted(set(data.objects.values()), key=attrgetter('n')) for obj in data.object_list: name = obj.names[0] if hasattr(data, name): name = name + '2' setattr(data, name, obj) return data
module function_definition identifier parameters identifier identifier block expression_statement assignment attribute identifier identifier list integer list integer while_statement true block expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list if_statement not_operator identifier block break_statement expression_statement assignment identifier call attribute call identifier argument_list identifier argument_list binary_operator string string_start string_content string_end identifier while_statement true block expression_statement assignment identifier list_comprehension parenthesized_expression conditional_expression call identifier argument_list identifier call attribute call attribute identifier identifier argument_list string string_start string_content string_end identifier argument_list identifier for_in_clause identifier call attribute call attribute call attribute identifier identifier argument_list identifier argument_list identifier argument_list string string_start string_content escape_sequence string_end if_statement comparison_operator subscript identifier integer unary_operator integer block break_statement expression_statement call identifier argument_list identifier list_splat identifier delete_statement attribute identifier identifier delete_statement attribute identifier identifier expression_statement assignment attribute identifier identifier call identifier argument_list call identifier argument_list call attribute attribute identifier identifier identifier argument_list keyword_argument identifier call identifier argument_list string string_start string_content string_end for_statement identifier attribute identifier identifier block expression_statement assignment identifier subscript attribute identifier identifier integer if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier binary_operator identifier string string_start string_content string_end expression_statement call identifier argument_list identifier identifier identifier return_statement identifier
Read the Adventure data file and return a ``Data`` object.
def _tag_ec2(self, conn, role): tags = {'Role': role} conn.create_tags([self.instance_id], tags)
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier dictionary pair string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list list attribute identifier identifier identifier
tag the current EC2 instance with a cluster role
def _player_step_tuple(self, envs_step_tuples): ob, reward, done, info = envs_step_tuples["env"] ob = self._augment_observation(ob, reward, self.cumulative_reward) return ob, reward, done, info
module function_definition identifier parameters identifier identifier block expression_statement assignment pattern_list identifier identifier identifier identifier subscript identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier attribute identifier identifier return_statement expression_list identifier identifier identifier identifier
Augment observation, return usual step tuple.
def main(dimension, iterations): objective_function = minimize(functions.sphere) stopping_condition = max_iterations(iterations) (solution, metrics) = optimize(objective_function=objective_function, domain=Domain(-5.12, 5.12, dimension), stopping_condition=stopping_condition, parameters={'seed': 3758117674, 'rho': 1.0, 'e_s': 15, 'e_f': 5}, velocity_update=gc_velocity_update, parameter_update=update_rho, measurements=[fitness_measurement]) return solution
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list attribute identifier identifier expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment tuple_pattern identifier identifier call identifier argument_list keyword_argument identifier identifier keyword_argument identifier call identifier argument_list unary_operator float float identifier keyword_argument identifier identifier keyword_argument identifier dictionary pair string string_start string_content string_end integer pair string string_start string_content string_end float pair string string_start string_content string_end integer pair string string_start string_content string_end integer keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier list identifier return_statement identifier
Main function to execute gbest GC PSO algorithm.
def _dict_to_obj(self, d): if JsonEncoder.TYPE_ID not in d: return d type_name = d.pop(JsonEncoder.TYPE_ID) if type_name in _TYPE_NAME_TO_DECODER: decoder = _TYPE_NAME_TO_DECODER[type_name] return decoder(d) else: raise TypeError("Invalid type %s.", type_name)
module function_definition identifier parameters identifier identifier block if_statement comparison_operator attribute identifier identifier identifier block return_statement identifier expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier if_statement comparison_operator identifier identifier block expression_statement assignment identifier subscript identifier identifier return_statement call identifier argument_list identifier else_clause block raise_statement call identifier argument_list string string_start string_content string_end identifier
Converts a dictionary of json object to a Python object.
def attrfindrows(self, groupname, attrname, value): values = self.attrgetcol(groupname, attrname) return [i for i in range(len(values)) if values[i] == value]
module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier return_statement list_comprehension identifier for_in_clause identifier call identifier argument_list call identifier argument_list identifier if_clause comparison_operator subscript identifier identifier identifier
Get the row numbers of all rows where the attribute matches the given value.
async def _mogrify(conn, query, args): ps = await conn.prepare(query) paramtypes = [] for t in ps.get_parameters(): if t.name.endswith('[]'): pname = '_' + t.name[:-2] else: pname = t.name paramtypes.append('{}.{}'.format( _quote_ident(t.schema), _quote_ident(pname))) del ps cols = ['quote_literal(${}::{}::text)'.format(i, t) for i, t in enumerate(paramtypes, start=1)] textified = await conn.fetchrow( 'SELECT {cols}'.format(cols=', '.join(cols)), *args) return re.sub( r'\$(\d+)\b', lambda m: textified[int(m.group(1)) - 1], query)
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier await call attribute identifier identifier argument_list identifier expression_statement assignment identifier list for_statement identifier call attribute identifier identifier argument_list block if_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end block expression_statement assignment identifier binary_operator string string_start string_content string_end subscript attribute identifier identifier slice unary_operator integer else_clause block expression_statement assignment identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list call identifier argument_list attribute identifier identifier call identifier argument_list identifier delete_statement identifier expression_statement assignment identifier list_comprehension call attribute string string_start string_content string_end identifier argument_list identifier identifier for_in_clause pattern_list identifier identifier call identifier argument_list identifier keyword_argument identifier integer expression_statement assignment identifier await call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list keyword_argument identifier call attribute string string_start string_content string_end identifier argument_list identifier list_splat identifier return_statement call attribute identifier identifier argument_list string string_start string_content string_end lambda lambda_parameters identifier subscript identifier binary_operator call identifier argument_list call attribute identifier identifier argument_list integer integer identifier
Safely inline arguments to query text.
def list_dynamodb(region, filter_by_kwargs): conn = boto.dynamodb.connect_to_region(region) tables = conn.list_tables() return lookup(tables, filter_by=filter_by_kwargs)
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list return_statement call identifier argument_list identifier keyword_argument identifier identifier
List all DynamoDB tables.
def md5(self): return hashlib.md5('_'.join([self.CHROM, str(self.POS), self.REF, self.ALT])).hexdigest()
module function_definition identifier parameters identifier block return_statement call attribute call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list list attribute identifier identifier call identifier argument_list attribute identifier identifier attribute identifier identifier attribute identifier identifier identifier argument_list
Return a md5 key string based on position, ref and alt
def deep_run(self): self.get_period_LS(self.date, self.mag, self.n_threads, self.min_period) phase_folded_date = self.date % (self.period * 2.) sorted_index = np.argsort(phase_folded_date) folded_date = phase_folded_date[sorted_index] folded_mag = self.mag[sorted_index] self.phase_eta = self.get_eta(folded_mag, self.weighted_std) self.slope_per10, self.slope_per90 = \ self.slope_percentile(folded_date, folded_mag) self.phase_cusum = self.get_cusum(folded_mag)
module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier expression_statement assignment identifier binary_operator attribute identifier identifier parenthesized_expression binary_operator attribute identifier identifier float expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier subscript identifier identifier expression_statement assignment identifier subscript attribute identifier identifier identifier expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list identifier attribute identifier identifier expression_statement assignment pattern_list attribute identifier identifier attribute identifier identifier line_continuation call attribute identifier identifier argument_list identifier identifier expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list identifier
Derive period-based features.
def group_remove(name, **kwargs): ctx = Context(**kwargs) ctx.execute_action('group:remove', **{ 'storage': ctx.repo.create_secure_service('storage'), 'name': name, })
module function_definition identifier parameters identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call identifier argument_list dictionary_splat identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end dictionary_splat dictionary pair string string_start string_content string_end call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end pair string string_start string_content string_end identifier
Remove routing group from the storage.
def send_point_data(events, additional): bodies = {} for (site, content_id), count in events.items(): if not len(site) or not len(content_id): continue bodies.setdefault(site, []) event, path = additional.get((site, content_id), (None, None)) bodies[site].append([content_id, event, path, count]) for site, points in bodies.items(): try: data = [{ "name": site, "columns": ["content_id", "event", "path", "value"], "points": points, }] INFLUXDB_CLIENT.write_points(data) except Exception as e: LOGGER.exception(e)
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier dictionary for_statement pattern_list tuple_pattern identifier identifier identifier call attribute identifier identifier argument_list block if_statement boolean_operator not_operator call identifier argument_list identifier not_operator call identifier argument_list identifier block continue_statement expression_statement call attribute identifier identifier argument_list identifier list expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list tuple identifier identifier tuple none none expression_statement call attribute subscript identifier identifier identifier argument_list list identifier identifier identifier identifier for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block try_statement block expression_statement assignment identifier list dictionary pair string string_start string_content string_end identifier pair string string_start string_content string_end list string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list identifier except_clause as_pattern identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list identifier
creates data point payloads and sends them to influxdb
def _wraps(self, tokens): def _differ(tokens): inner, outer = tokens not_same_start = inner.get('start') != outer.get('start') not_same_end = inner.get('end') != outer.get('end') return not_same_start or not_same_end def _in_range(tokens): inner, outer = tokens starts_in = outer.get('start') <= inner.get('start') \ <= outer.get('end') ends_in = outer.get('start') <= inner.get('end') \ <= outer.get('end') return starts_in and ends_in if not _differ(tokens): return False return _in_range(tokens)
module function_definition identifier parameters identifier identifier block function_definition identifier parameters identifier block expression_statement assignment pattern_list identifier identifier identifier expression_statement assignment identifier comparison_operator call attribute identifier identifier argument_list string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier comparison_operator call attribute identifier identifier argument_list string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content string_end return_statement boolean_operator identifier identifier function_definition identifier parameters identifier block expression_statement assignment pattern_list identifier identifier identifier expression_statement assignment identifier comparison_operator call attribute identifier identifier argument_list string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content string_end line_continuation call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier comparison_operator call attribute identifier identifier argument_list string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content string_end line_continuation call attribute identifier identifier argument_list string string_start string_content string_end return_statement boolean_operator identifier identifier if_statement not_operator call identifier argument_list identifier block return_statement false return_statement call identifier argument_list identifier
determine if a token is wrapped by another token
def read_records(file): records = [] for record_data in read_recordio(file): record = Record() record.ParseFromString(record_data) records.append(record) return records
module function_definition identifier parameters identifier block expression_statement assignment identifier list for_statement identifier call identifier argument_list identifier block expression_statement assignment identifier call identifier argument_list expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier return_statement identifier
Eagerly read a collection of amazon Record protobuf objects from file.
def _num_vowel_to_acc(vowel, tone): try: return VOWEL_MAP[vowel + str(tone)] except IndexError: raise ValueError("Vowel must be one of '{}' and tone must be a tone.".format(VOWELS))
module function_definition identifier parameters identifier identifier block try_statement block return_statement subscript identifier binary_operator identifier call identifier argument_list identifier except_clause identifier block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier
Convert a numbered vowel to an accented vowel.
def getElementsByClassName(start_node: ParentNode, class_name: str ) -> NodeList: classes = set(class_name.split(' ')) return getElementsBy( start_node, lambda node: classes.issubset(set(node.classList)) )
module function_definition identifier parameters typed_parameter identifier type identifier typed_parameter identifier type identifier type identifier block expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end return_statement call identifier argument_list identifier lambda lambda_parameters identifier call attribute identifier identifier argument_list call identifier argument_list attribute identifier identifier
Get child nodes which has ``class_name`` class attribute.
def read_pos_neg_data(path, folder, limit): training_pos_path = os.path.join(path, folder, 'pos') training_neg_path = os.path.join(path, folder, 'neg') X_pos = read_folder(training_pos_path) X_neg = read_folder(training_neg_path) if limit is None: X = X_pos + X_neg else: X = X_pos[:limit] + X_neg[:limit] y = [1] * int(len(X) / 2) + [0] * int(len(X) / 2) return X, y
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier identifier string string_start string_content string_end expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier identifier string string_start string_content string_end expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier if_statement comparison_operator identifier none block expression_statement assignment identifier binary_operator identifier identifier else_clause block expression_statement assignment identifier binary_operator subscript identifier slice identifier subscript identifier slice identifier expression_statement assignment identifier binary_operator binary_operator list integer call identifier argument_list binary_operator call identifier argument_list identifier integer binary_operator list integer call identifier argument_list binary_operator call identifier argument_list identifier integer return_statement expression_list identifier identifier
returns array with positive and negative examples
def save_hierarchy(self, hierarchy_form, *args, **kwargs): if hierarchy_form.is_for_update(): return self.update_hierarchy(hierarchy_form, *args, **kwargs) else: return self.create_hierarchy(hierarchy_form, *args, **kwargs)
module function_definition identifier parameters identifier identifier list_splat_pattern identifier dictionary_splat_pattern identifier block if_statement call attribute identifier identifier argument_list block return_statement call attribute identifier identifier argument_list identifier list_splat identifier dictionary_splat identifier else_clause block return_statement call attribute identifier identifier argument_list identifier list_splat identifier dictionary_splat identifier
Pass through to provider HierarchyAdminSession.update_hierarchy
def _doc_rev(self, res): jstr = res.headers['X-Couchbase-Meta'] jobj = json.loads(jstr) return jobj['rev']
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier subscript attribute identifier identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier return_statement subscript identifier string string_start string_content string_end
Returns the rev id from the header
def omnihash(obj): if isinstance(obj, set): return hash(frozenset(omnihash(e) for e in obj)) elif isinstance(obj, (tuple, list)): return hash(tuple(omnihash(e) for e in obj)) elif isinstance(obj, dict): return hash(frozenset((k, omnihash(v)) for k, v in obj.items())) else: return hash(obj)
module function_definition identifier parameters identifier block if_statement call identifier argument_list identifier identifier block return_statement call identifier argument_list call identifier generator_expression call identifier argument_list identifier for_in_clause identifier identifier elif_clause call identifier argument_list identifier tuple identifier identifier block return_statement call identifier argument_list call identifier generator_expression call identifier argument_list identifier for_in_clause identifier identifier elif_clause call identifier argument_list identifier identifier block return_statement call identifier argument_list call identifier generator_expression tuple identifier call identifier argument_list identifier for_in_clause pattern_list identifier identifier call attribute identifier identifier argument_list else_clause block return_statement call identifier argument_list identifier
recursively hash unhashable objects
def scoreatpercentile(data,per,axis=0): 'like the function in scipy.stats but with an axis argument and works on arrays' a = np.sort(data,axis=axis) idx = per/100. * (data.shape[axis]-1) if (idx % 1 == 0): return a[[slice(None) if ii != axis else idx for ii in range(a.ndim)]] else: lowerweight = 1-(idx % 1) upperweight = (idx % 1) idx = int(np.floor(idx)) return lowerweight * a[[slice(None) if ii != axis else idx for ii in range(a.ndim)]] \ + upperweight * a[[slice(None) if ii != axis else idx+1 for ii in range(a.ndim)]]
module function_definition identifier parameters identifier identifier default_parameter identifier integer block expression_statement string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier identifier expression_statement assignment identifier binary_operator binary_operator identifier float parenthesized_expression binary_operator subscript attribute identifier identifier identifier integer if_statement parenthesized_expression comparison_operator binary_operator identifier integer integer block return_statement subscript identifier list_comprehension conditional_expression call identifier argument_list none comparison_operator identifier identifier identifier for_in_clause identifier call identifier argument_list attribute identifier identifier else_clause block expression_statement assignment identifier binary_operator integer parenthesized_expression binary_operator identifier integer expression_statement assignment identifier parenthesized_expression binary_operator identifier integer expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list identifier return_statement binary_operator binary_operator identifier subscript identifier list_comprehension conditional_expression call identifier argument_list none comparison_operator identifier identifier identifier for_in_clause identifier call identifier argument_list attribute identifier identifier line_continuation binary_operator identifier subscript identifier list_comprehension conditional_expression call identifier argument_list none comparison_operator identifier identifier binary_operator identifier integer for_in_clause identifier call identifier argument_list attribute identifier identifier
like the function in scipy.stats but with an axis argument and works on arrays
def _get_counter_reference(self): if (self.model is not None and self.base_factory is not None and self.base_factory._meta.model is not None and issubclass(self.model, self.base_factory._meta.model)): return self.base_factory._meta.counter_reference else: return self
module function_definition identifier parameters identifier block if_statement parenthesized_expression boolean_operator boolean_operator boolean_operator comparison_operator attribute identifier identifier none comparison_operator attribute identifier identifier none comparison_operator attribute attribute attribute identifier identifier identifier identifier none call identifier argument_list attribute identifier identifier attribute attribute attribute identifier identifier identifier identifier block return_statement attribute attribute attribute identifier identifier identifier identifier else_clause block return_statement identifier
Identify which factory should be used for a shared counter.
def list_action(**kwargs): def decorator(func): func.action = True func.detail = False func.kwargs = kwargs return func return decorator
module function_definition identifier parameters dictionary_splat_pattern identifier block function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier true expression_statement assignment attribute identifier identifier false expression_statement assignment attribute identifier identifier identifier return_statement identifier return_statement identifier
Used to mark a method on a ResourceBinding that should be routed for list actions.
def _match_data_to_parameter(cls, data): in_value = data["in"] for cls in [QueryParameter, HeaderParameter, FormDataParameter, PathParameter, BodyParameter]: if in_value == cls.IN: return cls return None
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier subscript identifier string string_start string_content string_end for_statement identifier list identifier identifier identifier identifier identifier block if_statement comparison_operator identifier attribute identifier identifier block return_statement identifier return_statement none
find the appropriate parameter for a parameter field
def query(self): if not self.b64_query: return None s = QSerializer(base64=True) return s.loads(self.b64_query)
module function_definition identifier parameters identifier block if_statement not_operator attribute identifier identifier block return_statement none expression_statement assignment identifier call identifier argument_list keyword_argument identifier true return_statement call attribute identifier identifier argument_list attribute identifier identifier
De-serialize, decode and return an ORM query stored in b64_query.
def normalize_value(value): value = str(value) value = value.casefold() value = re.sub(r'\/\s*\d+', '', value) value = re.sub(r'^0+([0-9]+)', r'\1', value) value = re.sub(r'^(\d+)\.+', r'\1', value) value = re.sub(r'[^\w\s]', '', value) value = re.sub(r'^the\s+', '', value) value = re.sub(r'^\s+', '', value) value = re.sub(r'\s+$', '', value) value = re.sub(r'\s+', ' ', value) return value
module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_end identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_end identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_end identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_end identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_end identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end identifier return_statement identifier
Normalize metadata value to improve match accuracy.
def _segment_normalized_cnvkit(cnr_file, work_dir, paired): cnvkit_base = os.path.join(utils.safe_makedir(os.path.join(work_dir, "cnvkit")), dd.get_sample_name(paired.tumor_data)) cnr_file = chromhacks.bed_to_standardonly(cnr_file, paired.tumor_data, headers="chromosome", include_sex_chroms=True, out_dir=os.path.dirname(cnvkit_base)) cnr_file = _remove_overlaps(cnr_file, os.path.dirname(cnvkit_base), paired.tumor_data) seg_file = cnvkit.segment_from_cnr(cnr_file, paired.tumor_data, cnvkit_base) return cnr_file, seg_file
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier string string_start string_content string_end call attribute identifier identifier argument_list attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier attribute identifier identifier keyword_argument identifier string string_start string_content string_end keyword_argument identifier true keyword_argument identifier call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier call attribute attribute identifier identifier identifier argument_list identifier attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier attribute identifier identifier identifier return_statement expression_list identifier identifier
Segmentation of normalized inputs using CNVkit.
def _before_insert(mapper, connection, target): if target.position is None: func = sa.sql.func stmt = sa.select([func.coalesce(func.max(mapper.mapped_table.c.position), -1)]) target.position = connection.execute(stmt).scalar() + 1
module function_definition identifier parameters identifier identifier identifier block if_statement comparison_operator attribute identifier identifier none block expression_statement assignment identifier attribute attribute identifier identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list list call attribute identifier identifier argument_list call attribute identifier identifier argument_list attribute attribute attribute identifier identifier identifier identifier unary_operator integer expression_statement assignment attribute identifier identifier binary_operator call attribute call attribute identifier identifier argument_list identifier identifier argument_list integer
Set item to last position if position not defined.
def _generic_signal_handler(self, signal_type): print("</pre>") message = "Got " + signal_type + ". Failing gracefully..." self.timestamp(message) self.fail_pipeline(KeyboardInterrupt(signal_type), dynamic_recover=True) sys.exit(1)
module function_definition identifier parameters identifier identifier block expression_statement call identifier argument_list string string_start string_content string_end expression_statement assignment identifier binary_operator binary_operator string string_start string_content string_end identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list call identifier argument_list identifier keyword_argument identifier true expression_statement call attribute identifier identifier argument_list integer
Function for handling both SIGTERM and SIGINT
def find_column(t): pos = t.lexer.lexpos data = t.lexer.lexdata last_cr = data.rfind('\n', 0, pos) if last_cr < 0: last_cr = -1 column = pos - last_cr return column
module function_definition identifier parameters identifier block expression_statement assignment identifier attribute attribute identifier identifier identifier expression_statement assignment identifier attribute attribute identifier identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content escape_sequence string_end integer identifier if_statement comparison_operator identifier integer block expression_statement assignment identifier unary_operator integer expression_statement assignment identifier binary_operator identifier identifier return_statement identifier
Get cursor position, based on previous newline
def trim_trailing_silence(self): length = self.get_active_length() self.pianoroll = self.pianoroll[:length]
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment attribute identifier identifier subscript attribute identifier identifier slice identifier
Trim the trailing silence of the pianoroll.
def in_tree(self, cmd_args): if not cmd_args: return True tree = self try: for datum in cmd_args: tree = tree.get_child(datum) except ValueError: return False return True
module function_definition identifier parameters identifier identifier block if_statement not_operator identifier block return_statement true expression_statement assignment identifier identifier try_statement block for_statement identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier except_clause identifier block return_statement false return_statement true
if a command is in the tree
def feed(self, cube, pair): self.cube = cube if pair not in ["FR", "RB", "BL", "LF"]: pair = ["FR", "RB", "BL", "LF"][["RF", "BR", "LB", "FL"].index(pair)] self.pair = pair
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment attribute identifier identifier identifier if_statement comparison_operator identifier list string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end block expression_statement assignment identifier subscript list string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end call attribute list string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end identifier argument_list identifier expression_statement assignment attribute identifier identifier identifier
Feed Cube to the solver.
def _at(self, t): rITRF, vITRF, error = self.ITRF_position_velocity_error(t) rGCRS, vGCRS = ITRF_to_GCRS2(t, rITRF, vITRF) return rGCRS, vGCRS, rGCRS, error
module function_definition identifier parameters identifier identifier block expression_statement assignment pattern_list identifier identifier identifier call attribute identifier identifier argument_list identifier expression_statement assignment pattern_list identifier identifier call identifier argument_list identifier identifier identifier return_statement expression_list identifier identifier identifier identifier
Compute this satellite's GCRS position and velocity at time `t`.
def _configure_logging(verbose=False, debug=False): overall_level = logging.DEBUG if debug else logging.INFO logging.basicConfig( format=('{levelname[0]}{asctime}.{msecs:03.0f} {thread} ' '{filename}:{lineno}] {message}'), datefmt='%m%d %H:%M:%S', style='{', level=overall_level) global log log = logging.getLogger('portserver') log.setLevel(logging.DEBUG if verbose else overall_level)
module function_definition identifier parameters default_parameter identifier false default_parameter identifier false block expression_statement assignment identifier conditional_expression attribute identifier identifier identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list keyword_argument identifier parenthesized_expression concatenated_string string string_start string_content string_end string string_start string_content string_end keyword_argument identifier string string_start string_content string_end keyword_argument identifier string string_start string_content string_end keyword_argument identifier identifier global_statement identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list conditional_expression attribute identifier identifier identifier identifier
Configure the log global, message format, and verbosity settings.