code
stringlengths
51
2.34k
sequence
stringlengths
186
3.94k
docstring
stringlengths
11
171
def challenge(self): response = super(ConfigBasicAuth, self).challenge() raise with_headers(Unauthorized(), response.headers)
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute call identifier argument_list identifier identifier identifier argument_list raise_statement call identifier argument_list call identifier argument_list attribute identifier identifier
Override challenge to raise an exception that will trigger regular error handling.
def to_dict(self): import copy options = copy.deepcopy(self._options) if self._insert_tasks: options['insert_tasks'] = reference_to_path(self._insert_tasks) if self._persistence_engine: options['persistence_engine'] = reference_to_path( self._persistence_engine) options.update({ '_tasks_inserted': self._tasks_inserted, }) callbacks = self._options.get('callbacks') if callbacks: options['callbacks'] = encode_callbacks(callbacks) return options
module function_definition identifier parameters identifier block import_statement dotted_name identifier expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier if_statement attribute identifier identifier block expression_statement assignment subscript identifier string string_start string_content string_end call identifier argument_list attribute identifier identifier if_statement attribute identifier identifier block expression_statement assignment subscript identifier string string_start string_content string_end call identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list dictionary pair string string_start string_content string_end attribute identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end if_statement identifier block expression_statement assignment subscript identifier string string_start string_content string_end call identifier argument_list identifier return_statement identifier
Return this Context as a dict suitable for json encoding.
def qs_for_ip(cls, ip_str): ip = int(netaddr.IPAddress(ip_str)) if ip > 4294967295: return cls.objects.none() ip_range_query = { 'start__lte': ip, 'stop__gte': ip } return cls.objects.filter(**ip_range_query)
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list identifier if_statement comparison_operator identifier integer block return_statement call attribute attribute identifier identifier identifier argument_list expression_statement assignment identifier dictionary pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier return_statement call attribute attribute identifier identifier identifier argument_list dictionary_splat identifier
Returns a queryset with matching IPNetwork objects for the given IP.
def search(query, model): query = query.strip() LOGGER.debug(query) sqs = SearchQuerySet() results = sqs.raw_search('{}*'.format(query)).models(model) if not results: results = sqs.raw_search('*{}'.format(query)).models(model) if not results: results = sqs.raw_search('*{}*'.format(query)).models(model) return [o.pk for o in results]
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier call attribute call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier identifier argument_list identifier if_statement not_operator identifier block expression_statement assignment identifier call attribute call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier identifier argument_list identifier if_statement not_operator identifier block expression_statement assignment identifier call attribute call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier identifier argument_list identifier return_statement list_comprehension attribute identifier identifier for_in_clause identifier identifier
Performs a search query and returns the object ids
def output_files(self): output_list = [] pm_dict = self.get_dict() output_list.append(pm_dict['output_surface']) if pm_dict['target_volume'] != 0.0: output_list.append(pm_dict['output_surface'] + str(".cell")) return output_list
module function_definition identifier parameters identifier block expression_statement assignment identifier list expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list subscript identifier string string_start string_content string_end if_statement comparison_operator subscript identifier string string_start string_content string_end float block expression_statement call attribute identifier identifier argument_list binary_operator subscript identifier string string_start string_content string_end call identifier argument_list string string_start string_content string_end return_statement identifier
Return list of output files to be retrieved
def save( self ): packets = self.__enumerate_packets() delete_expected_value(self.call_hash) for packet in packets: packet['call_hash'] = self.call_hash insert_expected_value(packet) return self
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call identifier argument_list attribute identifier identifier for_statement identifier identifier block expression_statement assignment subscript identifier string string_start string_content string_end attribute identifier identifier expression_statement call identifier argument_list identifier return_statement identifier
Save method for the ExpectedValue of a call.
def RandomUniformInt(shape, minval, maxval, seed): if seed: np.random.seed(seed) return np.random.randint(minval, maxval, size=shape),
module function_definition identifier parameters identifier identifier identifier identifier block if_statement identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier return_statement expression_list call attribute attribute identifier identifier identifier argument_list identifier identifier keyword_argument identifier identifier
Random uniform int op.
def extract_common_fields(self, data): email = None for curr_email in data.get("emails", []): email = email or curr_email.get("email") if curr_email.get("verified", False) and \ curr_email.get("primary", False): email = curr_email.get("email") return dict( email=email, id=data.get('id'), name=data.get('name'), first_name=data.get('first_name'), last_name=data.get('last_name'), image_url=data.get('image_url') )
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier none for_statement identifier call attribute identifier identifier argument_list string string_start string_content string_end list block expression_statement assignment identifier boolean_operator identifier call attribute identifier identifier argument_list string string_start string_content string_end if_statement boolean_operator call attribute identifier identifier argument_list string string_start string_content string_end false line_continuation call attribute identifier identifier argument_list string string_start string_content string_end false block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end return_statement call identifier argument_list keyword_argument identifier identifier keyword_argument identifier call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier call attribute identifier identifier argument_list string string_start string_content string_end
Extract fields from a basic user query.
def _decode_data(self, data): self.major = data[0] if data[1] is 0xff: self.minor = data[1] elif data[1] <= 0x99: self.minor = int(data[1:2].tostring().decode('bcd+')) else: raise DecodingError()
module function_definition identifier parameters identifier identifier block expression_statement assignment attribute identifier identifier subscript identifier integer if_statement comparison_operator subscript identifier integer integer block expression_statement assignment attribute identifier identifier subscript identifier integer elif_clause comparison_operator subscript identifier integer integer block expression_statement assignment attribute identifier identifier call identifier argument_list call attribute call attribute subscript identifier slice integer integer identifier argument_list identifier argument_list string string_start string_content string_end else_clause block raise_statement call identifier argument_list
`data` is array.array
def _gatherUpdatedJobs(self, updatedJobTuple): jobID, result, wallTime = updatedJobTuple try: updatedJob = self.jobBatchSystemIDToIssuedJob[jobID] except KeyError: logger.warn("A result seems to already have been processed " "for job %s", jobID) else: if result == 0: cur_logger = (logger.debug if str(updatedJob.jobName).startswith(CWL_INTERNAL_JOBS) else logger.info) cur_logger('Job ended successfully: %s', updatedJob) if self.toilMetrics: self.toilMetrics.logCompletedJob(updatedJob) else: logger.warn('Job failed with exit value %i: %s', result, updatedJob) self.processFinishedJob(jobID, result, wallTime=wallTime)
module function_definition identifier parameters identifier identifier block expression_statement assignment pattern_list identifier identifier identifier identifier try_statement block expression_statement assignment identifier subscript attribute identifier identifier identifier except_clause identifier block expression_statement call attribute identifier identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end identifier else_clause block if_statement comparison_operator identifier integer block expression_statement assignment identifier parenthesized_expression conditional_expression attribute identifier identifier call attribute call identifier argument_list attribute identifier identifier identifier argument_list identifier attribute identifier identifier expression_statement call identifier argument_list string string_start string_content string_end identifier if_statement attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier else_clause block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier identifier expression_statement call attribute identifier identifier argument_list identifier identifier keyword_argument identifier identifier
Gather any new, updated jobGraph from the batch system
def configure_logging(verbose, logger): if not verbose: log_level = logging.WARNING elif verbose == 1: log_level = logging.INFO else: log_level = logging.DEBUG logger.setLevel(log_level) ch = colorlog.StreamHandler() ch.setLevel(log_level) formatter = colorlog.ColoredFormatter( '%(log_color)s%(asctime)s %(name)s %(levelname)s: %(message)s') ch.setFormatter(formatter) logger.addHandler(ch)
module function_definition identifier parameters identifier identifier block if_statement not_operator identifier block expression_statement assignment identifier attribute identifier identifier elif_clause comparison_operator identifier integer block expression_statement assignment identifier attribute identifier identifier else_clause block expression_statement assignment identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list 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 identifier expression_statement call attribute identifier identifier argument_list identifier
Configures the logging used.
def surfplot(self, z, titletext): if self.latlon: plt.imshow(z, extent=(0, self.dx*z.shape[0], self.dy*z.shape[1], 0)) plt.xlabel('longitude [deg E]', fontsize=12, fontweight='bold') plt.ylabel('latitude [deg N]', fontsize=12, fontweight='bold') else: plt.imshow(z, extent=(0, self.dx/1000.*z.shape[0], self.dy/1000.*z.shape[1], 0)) plt.xlabel('x [km]', fontsize=12, fontweight='bold') plt.ylabel('y [km]', fontsize=12, fontweight='bold') plt.colorbar() plt.title(titletext,fontsize=16)
module function_definition identifier parameters identifier identifier identifier block if_statement attribute identifier identifier block expression_statement call attribute identifier identifier argument_list identifier keyword_argument identifier tuple integer binary_operator attribute identifier identifier subscript attribute identifier identifier integer binary_operator attribute identifier identifier subscript attribute identifier identifier integer integer expression_statement call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier integer keyword_argument 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 integer keyword_argument identifier string string_start string_content string_end else_clause block expression_statement call attribute identifier identifier argument_list identifier keyword_argument identifier tuple integer binary_operator binary_operator attribute identifier identifier float subscript attribute identifier identifier integer binary_operator binary_operator attribute identifier identifier float subscript attribute identifier identifier integer integer expression_statement call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier integer keyword_argument 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 integer keyword_argument identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list identifier keyword_argument identifier integer
Plot if you want to - for troubleshooting - 1 figure
def upload_debug(self): if os.path.exists(self.log_fname): api = InternalApi() api.set_current_run_id(self.id) pusher = FilePusher(api) pusher.update_file("wandb-debug.log", self.log_fname) pusher.file_changed("wandb-debug.log", self.log_fname) pusher.finish()
module function_definition identifier parameters identifier block if_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier block expression_statement assignment identifier call identifier argument_list expression_statement call attribute identifier identifier argument_list attribute identifier identifier expression_statement assignment identifier call identifier argument_list identifier 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 string string_start string_content string_end attribute identifier identifier expression_statement call attribute identifier identifier argument_list
Uploads the debug log to cloud storage
def delete_char(event): " Delete character before the cursor. " deleted = event.current_buffer.delete(count=event.arg) if not deleted: event.cli.output.bell()
module function_definition identifier parameters identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list keyword_argument identifier attribute identifier identifier if_statement not_operator identifier block expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list
Delete character before the cursor.
def load_tables_from_files(db_connection): _log.info('Loading tables from disk to DB.') sde_dir_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'sde') for sde_file_name in os.listdir(sde_dir_path): _log.info('Loading the following table: {}'.format(sde_file_name)) sde_file_path = os.path.join(sde_dir_path, sde_file_name) with open(sde_file_path, 'r') as sde_file: sql = sde_file.read() execute_sql(sql, db_connection) _log.info('Finished loading all requested tables.')
module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier string string_start string_content string_end for_statement identifier call attribute identifier identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier identifier with_statement with_clause with_item as_pattern call identifier argument_list identifier string string_start string_content string_end as_pattern_target identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call identifier argument_list identifier identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end
Looks in the current working directory for all required tables.
def _log_prior_gradients(self): if self.priors.size == 0: return 0. x = self.param_array ret = np.zeros(x.size) [np.put(ret, ind, p.lnpdf_grad(x[ind])) for p, ind in self.priors.items()] priored_indexes = np.hstack([i for p, i in self.priors.items()]) for c,j in self.constraints.items(): if not isinstance(c, Transformation):continue for jj in j: if jj in priored_indexes: ret[jj] += c.log_jacobian_grad(x[jj]) return ret
module function_definition identifier parameters identifier block if_statement comparison_operator attribute attribute identifier identifier identifier integer block return_statement float expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier expression_statement list_comprehension call attribute identifier identifier argument_list identifier identifier call attribute identifier identifier argument_list subscript identifier identifier for_in_clause pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list list_comprehension identifier for_in_clause pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list for_statement pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list block if_statement not_operator call identifier argument_list identifier identifier block continue_statement for_statement identifier identifier block if_statement comparison_operator identifier identifier block expression_statement augmented_assignment subscript identifier identifier call attribute identifier identifier argument_list subscript identifier identifier return_statement identifier
evaluate the gradients of the priors
def _controller(self): def server_controller(cmd_id, cmd_body, _): if not self.init_logginig: head = '%(asctime)-15s Server[' + str( self.kvstore.rank) + '] %(message)s' logging.basicConfig(level=logging.DEBUG, format=head) self.init_logginig = True if cmd_id == 0: try: optimizer = pickle.loads(cmd_body) except: raise self.kvstore.set_optimizer(optimizer) else: print("server %d, unknown command (%d, %s)" % ( self.kvstore.rank, cmd_id, cmd_body)) return server_controller
module function_definition identifier parameters identifier block function_definition identifier parameters identifier identifier identifier block if_statement not_operator attribute identifier identifier block expression_statement assignment identifier binary_operator binary_operator string string_start string_content string_end call identifier argument_list attribute attribute identifier identifier identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier identifier expression_statement assignment attribute identifier identifier true if_statement comparison_operator identifier integer block try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list identifier except_clause block raise_statement expression_statement call attribute attribute identifier identifier identifier argument_list identifier else_clause block expression_statement call identifier argument_list binary_operator string string_start string_content string_end tuple attribute attribute identifier identifier identifier identifier identifier return_statement identifier
Return the server controller.
async def read(cls, node, block_device): if isinstance(node, str): system_id = node elif isinstance(node, Node): system_id = node.system_id else: raise TypeError( "node must be a Node or str, not %s" % type(node).__name__) if isinstance(block_device, int): block_device = block_device elif isinstance(block_device, BlockDevice): block_device = block_device.id else: raise TypeError( "node must be a Node or str, not %s" % type(block_device).__name__) data = await cls._handler.read( system_id=system_id, device_id=block_device) return cls( cls._object(item) for item in data)
module function_definition identifier parameters identifier identifier identifier block if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier identifier elif_clause call identifier argument_list identifier identifier block expression_statement assignment identifier attribute identifier identifier else_clause block raise_statement call identifier argument_list binary_operator string string_start string_content string_end attribute call identifier argument_list identifier identifier if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier identifier elif_clause call identifier argument_list identifier identifier block expression_statement assignment identifier attribute identifier identifier else_clause block raise_statement call identifier argument_list binary_operator string string_start string_content string_end attribute call identifier argument_list identifier identifier expression_statement assignment identifier await call attribute attribute identifier identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier return_statement call identifier generator_expression call attribute identifier identifier argument_list identifier for_in_clause identifier identifier
Get list of `Partitions`'s for `node` and `block_device`.
def upload_files(self, file_paths, file_size_sum=0, dcp_type="data", target_filename=None, use_transfer_acceleration=True, report_progress=False, sync=True): self._setup_s3_agent_for_file_upload(file_count=len(file_paths), file_size_sum=file_size_sum, use_transfer_acceleration=use_transfer_acceleration) pool = ThreadPool() if report_progress: print("\nStarting upload of %s files to upload area %s" % (len(file_paths), self.uuid)) for file_path in file_paths: pool.add_task(self._upload_file, file_path, target_filename=target_filename, use_transfer_acceleration=use_transfer_acceleration, report_progress=report_progress, sync=sync) pool.wait_for_completion() if report_progress: number_of_errors = len(self.s3agent.failed_uploads) if number_of_errors == 0: print( "Completed upload of %d files to upload area %s\n" % (self.s3agent.file_upload_completed_count, self.uuid)) else: error = "\nThe following files failed:" for k, v in self.s3agent.failed_uploads.items(): error += "\n%s: [Exception] %s" % (k, v) error += "\nPlease retry or contact an hca administrator at data-help@humancellatlas.org for help.\n" raise UploadException(error)
module function_definition identifier parameters identifier identifier default_parameter identifier integer default_parameter identifier string string_start string_content string_end default_parameter identifier none default_parameter identifier true default_parameter identifier false default_parameter identifier true block expression_statement call attribute identifier identifier argument_list keyword_argument identifier call identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier identifier expression_statement assignment identifier call identifier argument_list if_statement identifier block expression_statement call identifier argument_list binary_operator string string_start string_content escape_sequence string_end tuple call identifier argument_list identifier attribute identifier identifier for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list attribute identifier identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier expression_statement call attribute identifier identifier argument_list if_statement identifier block expression_statement assignment identifier call identifier argument_list attribute attribute identifier identifier identifier if_statement comparison_operator identifier integer block expression_statement call identifier argument_list binary_operator string string_start string_content escape_sequence string_end tuple attribute attribute identifier identifier identifier attribute identifier identifier else_clause block expression_statement assignment identifier string string_start string_content escape_sequence string_end for_statement pattern_list identifier identifier call attribute attribute attribute identifier identifier identifier identifier argument_list block expression_statement augmented_assignment identifier binary_operator string string_start string_content escape_sequence string_end tuple identifier identifier expression_statement augmented_assignment identifier string string_start string_content escape_sequence escape_sequence string_end raise_statement call identifier argument_list identifier
A function that takes in a list of file paths and other optional args for parallel file upload
def none_of(s): @Parser def none_of_parser(text, index=0): if index < len(text) and text[index] not in s: return Value.success(index + 1, text[index]) else: return Value.failure(index, 'none of {}'.format(s)) return none_of_parser
module function_definition identifier parameters identifier block decorated_definition decorator identifier function_definition identifier parameters identifier default_parameter identifier integer block if_statement boolean_operator comparison_operator identifier call identifier argument_list identifier comparison_operator subscript identifier identifier identifier block return_statement call attribute identifier identifier argument_list binary_operator identifier integer subscript identifier identifier else_clause block return_statement call attribute identifier identifier argument_list identifier call attribute string string_start string_content string_end identifier argument_list identifier return_statement identifier
Parser a char NOT from specified string.
def lmx_relative(): hparams = lmx_base() hparams.self_attention_type = "dot_product_relative_v2" hparams.activation_dtype = "float32" hparams.weight_dtype = "float32" return hparams
module function_definition identifier parameters block expression_statement assignment identifier call identifier argument_list expression_statement assignment attribute identifier identifier string string_start string_content string_end expression_statement assignment attribute identifier identifier string string_start string_content string_end expression_statement assignment attribute identifier identifier string string_start string_content string_end return_statement identifier
Language model using relative attention.
def _recurse_replace(obj, key, new_key, sub, remove): if isinstance(obj, list): return [_recurse_replace(x, key, new_key, sub, remove) for x in obj] if isinstance(obj, dict): for k, v in list(obj.items()): if k == key and v in sub: obj[new_key] = sub[v] if remove: del obj[key] else: obj[k] = _recurse_replace(v, key, new_key, sub, remove) return obj
module function_definition identifier parameters identifier identifier identifier identifier identifier block if_statement call identifier argument_list identifier identifier block return_statement list_comprehension call identifier argument_list identifier identifier identifier identifier identifier for_in_clause identifier identifier if_statement call identifier argument_list identifier identifier block for_statement pattern_list identifier identifier call identifier argument_list call attribute identifier identifier argument_list block if_statement boolean_operator comparison_operator identifier identifier comparison_operator identifier identifier block expression_statement assignment subscript identifier identifier subscript identifier identifier if_statement identifier block delete_statement subscript identifier identifier else_clause block expression_statement assignment subscript identifier identifier call identifier argument_list identifier identifier identifier identifier identifier return_statement identifier
Recursive helper for `replace_by_key`
def to_time(self): return time(self.hours, self.minutes, self.seconds, self.milliseconds * 1000)
module function_definition identifier parameters identifier block return_statement call identifier argument_list attribute identifier identifier attribute identifier identifier attribute identifier identifier binary_operator attribute identifier identifier integer
Convert SubRipTime instance into a pure datetime.time object
def status(self): if hasattr(self, '_status'): return self._status if self.column.status or \ self.column.name in self.column.table._meta.status_columns: data_status_lower = six.text_type( self.column.get_raw_data(self.datum)).lower() for status_name, status_value in self.column.status_choices: if six.text_type(status_name).lower() == data_status_lower: self._status = status_value return self._status self._status = None return self._status
module function_definition identifier parameters identifier block if_statement call identifier argument_list identifier string string_start string_content string_end block return_statement attribute identifier identifier if_statement boolean_operator attribute attribute identifier identifier identifier line_continuation comparison_operator attribute attribute identifier identifier identifier attribute attribute attribute attribute identifier identifier identifier identifier identifier block expression_statement assignment identifier call attribute call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list attribute identifier identifier identifier argument_list for_statement pattern_list identifier identifier attribute attribute identifier identifier identifier block if_statement comparison_operator call attribute call attribute identifier identifier argument_list identifier identifier argument_list identifier block expression_statement assignment attribute identifier identifier identifier return_statement attribute identifier identifier expression_statement assignment attribute identifier identifier none return_statement attribute identifier identifier
Gets the status for the column based on the cell's data.
def board_msg(self): board_str = "s\t\t" for i in xrange(self.board_width): board_str += str(i)+"\t" board_str = board_str.expandtabs(4)+"\n\n" for i in xrange(self.board_height): temp_line = str(i)+"\t\t" for j in xrange(self.board_width): if self.info_map[i, j] == 9: temp_line += "@\t" elif self.info_map[i, j] == 10: temp_line += "?\t" elif self.info_map[i, j] == 11: temp_line += "*\t" elif self.info_map[i, j] == 12: temp_line += "!\t" else: temp_line += str(self.info_map[i, j])+"\t" board_str += temp_line.expandtabs(4)+"\n" return board_str
module function_definition identifier parameters identifier block expression_statement assignment identifier string string_start string_content escape_sequence escape_sequence string_end for_statement identifier call identifier argument_list attribute identifier identifier block expression_statement augmented_assignment identifier binary_operator call identifier argument_list identifier string string_start string_content escape_sequence string_end expression_statement assignment identifier binary_operator call attribute identifier identifier argument_list integer string string_start string_content escape_sequence escape_sequence string_end for_statement identifier call identifier argument_list attribute identifier identifier block expression_statement assignment identifier binary_operator call identifier argument_list identifier string string_start string_content escape_sequence escape_sequence string_end for_statement identifier call identifier argument_list attribute identifier identifier block if_statement comparison_operator subscript attribute identifier identifier identifier identifier integer block expression_statement augmented_assignment identifier string string_start string_content escape_sequence string_end elif_clause comparison_operator subscript attribute identifier identifier identifier identifier integer block expression_statement augmented_assignment identifier string string_start string_content escape_sequence string_end elif_clause comparison_operator subscript attribute identifier identifier identifier identifier integer block expression_statement augmented_assignment identifier string string_start string_content escape_sequence string_end elif_clause comparison_operator subscript attribute identifier identifier identifier identifier integer block expression_statement augmented_assignment identifier string string_start string_content escape_sequence string_end else_clause block expression_statement augmented_assignment identifier binary_operator call identifier argument_list subscript attribute identifier identifier identifier identifier string string_start string_content escape_sequence string_end expression_statement augmented_assignment identifier binary_operator call attribute identifier identifier argument_list integer string string_start string_content escape_sequence string_end return_statement identifier
Structure a board as in print_board.
def db_aws_list_instances(self): instances = self.db_services.get_db_instances() if not instances: print("There are no DB instances associated with your AWS account " \ "in region " + self.db_services.get_region()) else: print("Here are the current DB instances associated with your AWS " \ "account in region " + self.db_services.get_region()) for dbinst in instances: print '\t'+'-'*20 print "\tInstance ID: " + dbinst.id print "\tStatus: " + dbinst.status
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list if_statement not_operator identifier block expression_statement call identifier argument_list binary_operator concatenated_string string string_start string_content string_end string string_start string_content string_end call attribute attribute identifier identifier identifier argument_list else_clause block expression_statement call identifier argument_list binary_operator concatenated_string string string_start string_content string_end string string_start string_content string_end call attribute attribute identifier identifier identifier argument_list for_statement identifier identifier block print_statement binary_operator string string_start string_content escape_sequence string_end binary_operator string string_start string_content string_end integer print_statement binary_operator string string_start string_content escape_sequence string_end attribute identifier identifier print_statement binary_operator string string_start string_content escape_sequence string_end attribute identifier identifier
List AWS DB instances
def AgregarAjusteFisico(self, cantidad, cantidad_cabezas=None, cantidad_kg_vivo=None, **kwargs): "Agrega campos al detalle de item por un ajuste fisico" d = {'cantidad': cantidad, 'cantidadCabezas': cantidad_cabezas, 'cantidadKgVivo': cantidad_kg_vivo, } item_liq = self.solicitud['itemDetalleAjusteLiquidacion'][-1] item_liq['ajusteFisico'] = d return True
module function_definition identifier parameters identifier identifier default_parameter identifier none default_parameter identifier none dictionary_splat_pattern identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier dictionary pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier expression_statement assignment identifier subscript subscript attribute identifier identifier string string_start string_content string_end unary_operator integer expression_statement assignment subscript identifier string string_start string_content string_end identifier return_statement true
Agrega campos al detalle de item por un ajuste fisico
def _find_base_version_ids(self, symbol, version_ids): cursor = self._versions.find({'symbol': symbol, '_id': {'$nin': version_ids}, 'base_version_id': {'$exists': True}, }, projection={'base_version_id': 1}) return [version["base_version_id"] for version in cursor]
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list dictionary pair string string_start string_content string_end identifier pair string string_start string_content string_end dictionary pair string string_start string_content string_end identifier pair string string_start string_content string_end dictionary pair string string_start string_content string_end true keyword_argument identifier dictionary pair string string_start string_content string_end integer return_statement list_comprehension subscript identifier string string_start string_content string_end for_in_clause identifier identifier
Return all base_version_ids for a symbol that are not bases of version_ids
def _put_to_history(self, command_script): history_file_name = self._get_history_file_name() if os.path.isfile(history_file_name): with open(history_file_name, 'a') as history: entry = self._get_history_line(command_script) if six.PY2: history.write(entry.encode('utf-8')) else: history.write(entry)
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement call attribute attribute identifier identifier identifier argument_list identifier block with_statement with_clause with_item as_pattern call identifier argument_list identifier string string_start string_content string_end as_pattern_target identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement attribute identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end else_clause block expression_statement call attribute identifier identifier argument_list identifier
Puts command script to shell history.
def render_archive(entries): context = GLOBAL_TEMPLATE_CONTEXT.copy() context['entries'] = entries _render(context, 'archive_index.html', os.path.join(CONFIG['output_to'], 'archive/index.html')),
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment subscript identifier string string_start string_content string_end identifier expression_statement call identifier argument_list identifier string string_start string_content string_end call attribute attribute identifier identifier identifier argument_list subscript identifier string string_start string_content string_end string string_start string_content string_end
Creates the archive page
def SoS_eval(expr: str, extra_dict: dict = {}) -> Any: return eval(expr, env.sos_dict.dict(), extra_dict)
module function_definition identifier parameters typed_parameter identifier type identifier typed_default_parameter identifier type identifier dictionary type identifier block return_statement call identifier argument_list identifier call attribute attribute identifier identifier identifier argument_list identifier
Evaluate an expression with sos dict.
def byte(self): flags = int(self._in_use) << 7 \ | int(self._controller) << 6 \ | int(self._bit5) << 5 \ | int(self._bit4) << 4 \ | int(self._used_before) << 1 return flags
module function_definition identifier parameters identifier block expression_statement assignment identifier binary_operator binary_operator binary_operator binary_operator binary_operator call identifier argument_list attribute identifier identifier integer line_continuation binary_operator call identifier argument_list attribute identifier identifier integer line_continuation binary_operator call identifier argument_list attribute identifier identifier integer line_continuation binary_operator call identifier argument_list attribute identifier identifier integer line_continuation binary_operator call identifier argument_list attribute identifier identifier integer return_statement identifier
Return a byte representation of ControlFlags.
def run_sls_remove(sls_cmd, env_vars): sls_process = subprocess.Popen(sls_cmd, stdout=subprocess.PIPE, env=env_vars) stdoutdata, _stderrdata = sls_process.communicate() sls_return = sls_process.wait() print(stdoutdata) if sls_return != 0 and (sls_return == 1 and not ( re.search(r"Stack '.*' does not exist", stdoutdata))): sys.exit(sls_return)
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier identifier expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call identifier argument_list identifier if_statement boolean_operator comparison_operator identifier integer parenthesized_expression boolean_operator comparison_operator identifier integer not_operator parenthesized_expression call attribute identifier identifier argument_list string string_start string_content string_end identifier block expression_statement call attribute identifier identifier argument_list identifier
Run sls remove command.
def _add_routes(self): if self.app.has_static_folder: self.add_url_rule("/favicon.ico", "favicon", self.favicon) self.add_url_rule("/", "__default_redirect_to_status", self.redirect_to_status)
module function_definition identifier parameters identifier block if_statement attribute attribute identifier identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end attribute identifier identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end attribute identifier identifier
Add some nice default routes.
def difference(self, key, *others): if not isinstance(key, str): raise ValueError("String expected.") self.db.sdiffstore(key, [self.key] + [o.key for o in others]) return Set(key)
module function_definition identifier parameters identifier identifier list_splat_pattern identifier block if_statement not_operator call identifier argument_list identifier identifier block raise_statement call identifier argument_list string string_start string_content string_end expression_statement call attribute attribute identifier identifier identifier argument_list identifier binary_operator list attribute identifier identifier list_comprehension attribute identifier identifier for_in_clause identifier identifier return_statement call identifier argument_list identifier
Return a new set with elements in the set that are not in the others.
def execute_once(self, string): for rule in self.rules: if rule[0] in string: pos = string.find(rule[0]) self.last_rule = rule return string[:pos] + rule[1] + string[pos+len(rule[0]):] self.last_rule = None return string
module function_definition identifier parameters identifier identifier block for_statement identifier attribute identifier identifier block if_statement comparison_operator subscript identifier integer identifier block expression_statement assignment identifier call attribute identifier identifier argument_list subscript identifier integer expression_statement assignment attribute identifier identifier identifier return_statement binary_operator binary_operator subscript identifier slice identifier subscript identifier integer subscript identifier slice binary_operator identifier call identifier argument_list subscript identifier integer expression_statement assignment attribute identifier identifier none return_statement identifier
Execute only one rule.
def kml_master(): kml_doc = KMLMaster(app.config["url_formatter"], app.config["mapsources"].values()) return kml_response(kml_doc)
module function_definition identifier parameters block expression_statement assignment identifier call identifier argument_list subscript attribute identifier identifier string string_start string_content string_end call attribute subscript attribute identifier identifier string string_start string_content string_end identifier argument_list return_statement call identifier argument_list identifier
KML master document for loading all maps in Google Earth
async def probeUrl(self, url, response_headers=None): self.logger.debug("Probing URL '%s'..." % (url)) headers = {} self.updateHttpHeaders(headers) resp_headers = {} resp_ok = await self.http.isReachable(url, headers=headers, response_headers=resp_headers, cache=__class__.probe_cache) if response_headers is not None: response_headers.update(resp_headers) return resp_ok
module function_definition identifier parameters identifier identifier default_parameter identifier none block expression_statement call attribute attribute identifier identifier identifier argument_list binary_operator string string_start string_content string_end parenthesized_expression identifier expression_statement assignment identifier dictionary expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier dictionary expression_statement assignment identifier await call attribute attribute identifier identifier identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier attribute identifier identifier if_statement comparison_operator identifier none block expression_statement call attribute identifier identifier argument_list identifier return_statement identifier
Probe URL reachability from cache or HEAD request.
def run_build_cli(): args = parse_args() if args.verbose: log_level = logging.DEBUG else: log_level = logging.INFO logging.basicConfig( level=log_level, format='%(asctime)s %(levelname)s %(name)s: %(message)s') logger = logging.getLogger(__name__) logger.info('build-stack-docs version {0}'.format(__version__)) return_code = build_stack_docs(args.root_project_dir) if return_code == 0: logger.info('build-stack-docs succeeded') sys.exit(0) else: logger.error('Sphinx errored: code {0:d}'.format(return_code)) sys.exit(1)
module function_definition identifier parameters block expression_statement assignment identifier call identifier argument_list if_statement attribute identifier identifier block expression_statement assignment identifier attribute identifier identifier else_clause block expression_statement assignment identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier expression_statement assignment identifier call identifier argument_list attribute identifier identifier if_statement comparison_operator identifier integer block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list integer else_clause block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier expression_statement call attribute identifier identifier argument_list integer
Command line entrypoint for the ``build-stack-docs`` program.
def rtruncated_normal(mu, tau, a=-np.inf, b=np.inf, size=None): sigma = 1. / np.sqrt(tau) na = utils.normcdf((a - mu) / sigma) nb = utils.normcdf((b - mu) / sigma) U = np.random.mtrand.uniform(size=size) q = U * nb + (1 - U) * na R = utils.invcdf(q) return R * sigma + mu
module function_definition identifier parameters identifier identifier default_parameter identifier unary_operator attribute identifier identifier default_parameter identifier attribute identifier identifier default_parameter identifier none block expression_statement assignment identifier binary_operator float call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list binary_operator parenthesized_expression binary_operator identifier identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list binary_operator parenthesized_expression binary_operator identifier identifier identifier expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list keyword_argument identifier identifier expression_statement assignment identifier binary_operator binary_operator identifier identifier binary_operator parenthesized_expression binary_operator integer identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier return_statement binary_operator binary_operator identifier identifier identifier
Random truncated normal variates.
def clean_up(self): if self.selected_col: col_label_value = self.grid.GetColLabelValue(self.selected_col) col_label_value = col_label_value.strip('\nEDIT ALL') self.grid.SetColLabelValue(self.selected_col, col_label_value) for row in range(self.grid.GetNumberRows()): self.grid.SetCellBackgroundColour(row, self.selected_col, 'white') self.grid.ForceRefresh()
module function_definition identifier parameters identifier block if_statement attribute identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content escape_sequence string_end expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier identifier for_statement identifier call identifier argument_list call attribute attribute identifier identifier identifier argument_list block expression_statement call attribute attribute identifier identifier identifier argument_list identifier attribute identifier identifier string string_start string_content string_end expression_statement call attribute attribute identifier identifier identifier argument_list
de-select grid cols, refresh grid
def setup_regex(self): self._RX_TYPE = r"\n\s*type(?P<modifiers>,\s+(public|private))?(\s*::)?\s+(?P<name>[A-Za-z0-9_]+)" + \ r"(?P<contents>.+?)end\s*type(\s+(?P=name))?" self.RE_TYPE = re.compile(self._RX_TYPE, re.DOTALL | re.I) self._RX_SIG = r"type(?P<modifiers>,\s+(public|private))?(\s+::)?\s+(?P<name>[A-Za-z0-9_]+)" self.RE_SIG = re.compile(self._RX_SIG, re.I) self._RX_PRIV = "private.+?(contains)?" self.RE_PRIV = re.compile(self._RX_PRIV, re.DOTALL | re.I) self._RX_EXEC = r"^\s*(?P<modifiers>[^:]+)\s+::\s+(?P<name>[A-Za-z0-9_]+)" + \ r"(\s+=>\s+(?P<points>[A-Za-z0-9_]+))?$" self.RE_EXEC = re.compile(self._RX_EXEC, re.M | re.I) self._RX_CONTAINS = "\n\s*contains(?P<remainder>.+)" self.RE_CONTAINS = re.compile(self._RX_CONTAINS, re.DOTALL | re.I)
module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier binary_operator string string_start string_content string_end string string_start string_content string_end expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list attribute identifier identifier binary_operator attribute identifier identifier attribute identifier identifier expression_statement assignment attribute identifier identifier string string_start string_content string_end expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier expression_statement assignment attribute identifier identifier string string_start string_content string_end expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list attribute identifier identifier binary_operator attribute identifier identifier attribute identifier identifier expression_statement assignment attribute identifier identifier binary_operator string string_start string_content string_end string string_start string_content string_end expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list attribute identifier identifier binary_operator attribute identifier identifier attribute identifier identifier expression_statement assignment attribute identifier identifier string string_start string_content escape_sequence string_end expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list attribute identifier identifier binary_operator attribute identifier identifier attribute identifier identifier
Sets up the patterns and compiled regex objects for parsing types.
def bell_set(self, collection, ordinal=False): if len(collection) == 1: yield [ collection ] return first = collection[0] for smaller in self.bell_set(collection[1:]): for n, subset in enumerate(smaller): if not ordinal or (ordinal and is_sorted(smaller[:n] + [[ first ] + subset] + smaller[n+1:], self._nan)): yield smaller[:n] + [[ first ] + subset] + smaller[n+1:] if not ordinal or (ordinal and is_sorted([ [ first ] ] + smaller, self._nan)): yield [ [ first ] ] + smaller
module function_definition identifier parameters identifier identifier default_parameter identifier false block if_statement comparison_operator call identifier argument_list identifier integer block expression_statement yield list identifier return_statement expression_statement assignment identifier subscript identifier integer for_statement identifier call attribute identifier identifier argument_list subscript identifier slice integer block for_statement pattern_list identifier identifier call identifier argument_list identifier block if_statement boolean_operator not_operator identifier parenthesized_expression boolean_operator identifier call identifier argument_list binary_operator binary_operator subscript identifier slice identifier list binary_operator list identifier identifier subscript identifier slice binary_operator identifier integer attribute identifier identifier block expression_statement yield binary_operator binary_operator subscript identifier slice identifier list binary_operator list identifier identifier subscript identifier slice binary_operator identifier integer if_statement boolean_operator not_operator identifier parenthesized_expression boolean_operator identifier call identifier argument_list binary_operator list list identifier identifier attribute identifier identifier block expression_statement yield binary_operator list list identifier identifier
Calculates the Bell set
def encode_task(task): task = task.copy() if 'tags' in task: task['tags'] = ','.join(task['tags']) for k in task: for unsafe, safe in six.iteritems(encode_replacements): if isinstance(task[k], six.string_types): task[k] = task[k].replace(unsafe, safe) if isinstance(task[k], datetime.datetime): task[k] = task[k].strftime("%Y%m%dT%M%H%SZ") return "[%s]\n" % " ".join([ "%s:\"%s\"" % (k, v) for k, v in sorted(task.items(), key=itemgetter(0)) ])
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment subscript identifier string string_start string_content string_end call attribute string string_start string_content string_end identifier argument_list subscript identifier string string_start string_content string_end for_statement identifier identifier block for_statement pattern_list identifier identifier call attribute identifier identifier argument_list identifier block if_statement call identifier argument_list subscript identifier identifier attribute identifier identifier block expression_statement assignment subscript identifier identifier call attribute subscript identifier identifier identifier argument_list identifier identifier if_statement call identifier argument_list subscript identifier identifier attribute identifier identifier block expression_statement assignment subscript identifier identifier call attribute subscript identifier identifier identifier argument_list string string_start string_content string_end return_statement binary_operator string string_start string_content escape_sequence string_end call attribute string string_start string_content string_end identifier argument_list list_comprehension binary_operator string string_start string_content escape_sequence escape_sequence string_end tuple identifier identifier for_in_clause pattern_list identifier identifier call identifier argument_list call attribute identifier identifier argument_list keyword_argument identifier call identifier argument_list integer
Convert a dict-like task to its string representation
def populate_fw_dev(self, fw_id, mgmt_ip, new): for cnt in self.res: used = self.res.get(cnt).get('used') if mgmt_ip == self.res[cnt].get('mgmt_ip'): if new: self.res[cnt]['used'] = used + 1 self.res[cnt]['fw_id_lst'].append(fw_id) return self.res[cnt].get('obj_dict'), ( self.res[cnt].get('mgmt_ip')) return None, None
module function_definition identifier parameters identifier identifier identifier identifier block for_statement identifier attribute identifier identifier block expression_statement assignment identifier call attribute call attribute attribute identifier identifier identifier argument_list identifier identifier argument_list string string_start string_content string_end if_statement comparison_operator identifier call attribute subscript attribute identifier identifier identifier identifier argument_list string string_start string_content string_end block if_statement identifier block expression_statement assignment subscript subscript attribute identifier identifier identifier string string_start string_content string_end binary_operator identifier integer expression_statement call attribute subscript subscript attribute identifier identifier identifier string string_start string_content string_end identifier argument_list identifier return_statement expression_list call attribute subscript attribute identifier identifier identifier identifier argument_list string string_start string_content string_end parenthesized_expression call attribute subscript attribute identifier identifier identifier identifier argument_list string string_start string_content string_end return_statement expression_list none none
Populate the class after a restart.
def _calc_taub(w, aod700, p): p0 = 101325. tb1 = 1.82 + 0.056*np.log(w) + 0.0071*np.log(w)**2 tb0 = 0.33 + 0.045*np.log(w) + 0.0096*np.log(w)**2 tbp = 0.0089*w + 0.13 taub = tb1*aod700 + tb0 + tbp*np.log(p/p0) return taub
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier float expression_statement assignment identifier binary_operator binary_operator float binary_operator float call attribute identifier identifier argument_list identifier binary_operator float binary_operator call attribute identifier identifier argument_list identifier integer expression_statement assignment identifier binary_operator binary_operator float binary_operator float call attribute identifier identifier argument_list identifier binary_operator float binary_operator call attribute identifier identifier argument_list identifier integer expression_statement assignment identifier binary_operator binary_operator float identifier float expression_statement assignment identifier binary_operator binary_operator binary_operator identifier identifier identifier binary_operator identifier call attribute identifier identifier argument_list binary_operator identifier identifier return_statement identifier
Calculate the taub coefficient
def seen_nonce(id, nonce, timestamp): key = '{id}:{n}:{ts}'.format(id=id, n=nonce, ts=timestamp) if cache.get(key): log.warning('replay attack? already processed nonce {k}' .format(k=key)) return True else: log.debug('caching nonce {k}'.format(k=key)) cache.set(key, True, timeout=getattr(settings, 'HAWK_MESSAGE_EXPIRATION', default_message_expiration) + 5) return False
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier if_statement call attribute identifier identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list keyword_argument identifier identifier return_statement true else_clause block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list keyword_argument identifier identifier expression_statement call attribute identifier identifier argument_list identifier true keyword_argument identifier binary_operator call identifier argument_list identifier string string_start string_content string_end identifier integer return_statement false
Returns True if the Hawk nonce has been seen already.
def EnsureTempDirIsSane(directory): if not os.path.isabs(directory): raise ErrorBadPath("Directory %s is not absolute" % directory) if os.path.isdir(directory): if not client_utils.VerifyFileOwner(directory): shutil.rmtree(directory) if not os.path.isdir(directory): os.makedirs(directory) if sys.platform == "win32": from grr_response_client import client_utils_windows client_utils_windows.WinChmod(directory, ["FILE_GENERIC_READ", "FILE_GENERIC_WRITE"]) else: os.chmod(directory, stat.S_IXUSR | stat.S_IRUSR | stat.S_IWUSR)
module function_definition identifier parameters identifier block if_statement not_operator call attribute attribute identifier identifier identifier argument_list identifier block raise_statement call identifier argument_list binary_operator string string_start string_content string_end identifier if_statement call attribute attribute identifier identifier identifier argument_list identifier block if_statement not_operator call attribute identifier identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list identifier if_statement not_operator call attribute attribute identifier identifier identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list identifier if_statement comparison_operator attribute identifier identifier string string_start string_content string_end block import_from_statement dotted_name identifier dotted_name identifier expression_statement call attribute identifier identifier argument_list identifier list string string_start string_content string_end string string_start string_content string_end else_clause block expression_statement call attribute identifier identifier argument_list identifier binary_operator binary_operator attribute identifier identifier attribute identifier identifier attribute identifier identifier
Checks that the directory exists and has the correct permissions set.
def update_content_encoding(self, data: Any) -> None: if not data: return enc = self.headers.get(hdrs.CONTENT_ENCODING, '').lower() if enc: if self.compress: raise ValueError( 'compress can not be set ' 'if Content-Encoding header is set') elif self.compress: if not isinstance(self.compress, str): self.compress = 'deflate' self.headers[hdrs.CONTENT_ENCODING] = self.compress self.chunked = True
module function_definition identifier parameters identifier typed_parameter identifier type identifier type none block if_statement not_operator identifier block return_statement expression_statement assignment identifier call attribute call attribute attribute identifier identifier identifier argument_list attribute identifier identifier string string_start string_end identifier argument_list if_statement identifier block if_statement attribute identifier identifier block raise_statement call identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end elif_clause attribute identifier identifier block if_statement not_operator call identifier argument_list attribute identifier identifier identifier block expression_statement assignment attribute identifier identifier string string_start string_content string_end expression_statement assignment subscript attribute identifier identifier attribute identifier identifier attribute identifier identifier expression_statement assignment attribute identifier identifier true
Set request content encoding.
def away(dev, away_end, temperature): if away_end: click.echo("Setting away until %s, temperature: %s" % (away_end, temperature)) else: click.echo("Disabling away mode") dev.set_away(away_end, temperature)
module function_definition identifier parameters identifier identifier identifier block if_statement identifier block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end tuple identifier identifier else_clause block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier identifier
Enables or disables the away mode.
def _check_child_limits(self, child_pid): if self.max_children is not None and \ self.children.count() >= self.max_children: raise PIDRelationConsistencyError( "Max number of children is set to {}.". format(self.max_children)) if self.max_parents is not None and \ PIDRelation.query.filter_by( child=child_pid, relation_type=self.relation_type.id)\ .count() >= self.max_parents: raise PIDRelationConsistencyError( "This pid already has the maximum number of parents.")
module function_definition identifier parameters identifier identifier block if_statement boolean_operator comparison_operator attribute identifier identifier none line_continuation comparison_operator call attribute attribute identifier identifier identifier argument_list attribute identifier identifier block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier if_statement boolean_operator comparison_operator attribute identifier identifier none line_continuation comparison_operator call attribute call attribute attribute identifier identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier attribute attribute identifier identifier identifier line_continuation identifier argument_list attribute identifier identifier block raise_statement call identifier argument_list string string_start string_content string_end
Check that inserting a child is within the limits.
def GetRegion(region_name): regions = boto_ec2.regions() region = None valid_region_names = [] for r in regions: valid_region_names.append(r.name) if r.name == region_name: region = r break if not region: logging.info( 'invalid region name: %s ' % (region_name)) logging.info( 'Try one of these:\n %s' % ('\n'.join(valid_region_names))) assert(False) return region
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier none expression_statement assignment identifier list for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list attribute identifier identifier if_statement comparison_operator attribute identifier identifier identifier block expression_statement assignment identifier identifier break_statement if_statement not_operator identifier block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end parenthesized_expression identifier expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content escape_sequence string_end parenthesized_expression call attribute string string_start string_content escape_sequence string_end identifier argument_list identifier assert_statement parenthesized_expression false return_statement identifier
Converts region name string into boto Region object.
def parse_sacct(sacct_stream): rows = (line.split() for line in sacct_stream) relevant_rows = (row for row in rows if row[0].isdigit()) jobs = [convert_job(row) for row in relevant_rows] return jobs
module function_definition identifier parameters identifier block expression_statement assignment identifier generator_expression call attribute identifier identifier argument_list for_in_clause identifier identifier expression_statement assignment identifier generator_expression identifier for_in_clause identifier identifier if_clause call attribute subscript identifier integer identifier argument_list expression_statement assignment identifier list_comprehension call identifier argument_list identifier for_in_clause identifier identifier return_statement identifier
Parse out information from sacct status output.
def clear_on_run(self, prefix="Running Tests:"): if platform.system() == 'Windows': os.system('cls') else: os.system('clear') if prefix: print(prefix)
module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end block if_statement comparison_operator call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end else_clause block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end if_statement identifier block expression_statement call identifier argument_list identifier
Clears console before running the tests.
def indent(lines, amount, ch=' '): padding = amount * ch return padding + ('\n' + padding).join(lines.split('\n'))
module function_definition identifier parameters identifier identifier default_parameter identifier string string_start string_content string_end block expression_statement assignment identifier binary_operator identifier identifier return_statement binary_operator identifier call attribute parenthesized_expression binary_operator string string_start string_content escape_sequence string_end identifier identifier argument_list call attribute identifier identifier argument_list string string_start string_content escape_sequence string_end
Indent the lines in a string by padding each one with proper number of pad characters
def html_with_encoding(self, url, timeout=None, encoding="utf-8"): response = self.get_response(url, timeout=timeout) if response: return self.decoder.decode(response.content, encoding)[0] else: return None
module function_definition identifier parameters identifier identifier default_parameter identifier none default_parameter identifier string string_start string_content string_end block expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier identifier if_statement identifier block return_statement subscript call attribute attribute identifier identifier identifier argument_list attribute identifier identifier identifier integer else_clause block return_statement none
Manually get html with user encoding setting.
def savecsv(filename, datadict, mode="w"): if mode == "a" : header = False else: header = True with open(filename, mode) as f: _pd.DataFrame(datadict).to_csv(f, index=False, header=header)
module function_definition identifier parameters identifier identifier default_parameter identifier string string_start string_content string_end block if_statement comparison_operator identifier string string_start string_content string_end block expression_statement assignment identifier false else_clause block expression_statement assignment identifier true with_statement with_clause with_item as_pattern call identifier argument_list identifier identifier as_pattern_target identifier block expression_statement call attribute call attribute identifier identifier argument_list identifier identifier argument_list identifier keyword_argument identifier false keyword_argument identifier identifier
Save a dictionary of data to CSV.
def gauge(self, stat, value, rate=1, delta=False): if value < 0 and not delta: if rate < 1: if random.random() > rate: return with self.pipeline() as pipe: pipe._send_stat(stat, '0|g', 1) pipe._send_stat(stat, '%s|g' % value, 1) else: prefix = '+' if delta and value >= 0 else '' self._send_stat(stat, '%s%s|g' % (prefix, value), rate)
module function_definition identifier parameters identifier identifier identifier default_parameter identifier integer default_parameter identifier false block if_statement boolean_operator comparison_operator identifier integer not_operator identifier block if_statement comparison_operator identifier integer block if_statement comparison_operator call attribute identifier identifier argument_list identifier block return_statement with_statement with_clause with_item as_pattern call attribute identifier identifier argument_list as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list identifier string string_start string_content string_end integer expression_statement call attribute identifier identifier argument_list identifier binary_operator string string_start string_content string_end identifier integer else_clause block expression_statement assignment identifier conditional_expression string string_start string_content string_end boolean_operator identifier comparison_operator identifier integer string string_start string_end expression_statement call attribute identifier identifier argument_list identifier binary_operator string string_start string_content string_end tuple identifier identifier identifier
Set a gauge value.
def _evaluate_expressions(self, expression_engine, step_id, values, context): if expression_engine is None: return values processed = {} for name, value in values.items(): if isinstance(value, str): value = value.strip() try: expression = expression_engine.get_inline_expression(value) if expression is not None: value = expression_engine.evaluate_inline(expression, context) else: value = expression_engine.evaluate_block(value, context) except EvaluationError as error: raise ExecutionError('Error while evaluating expression for step "{}":\n{}'.format( step_id, error )) elif isinstance(value, dict): value = self._evaluate_expressions(expression_engine, step_id, value, context) processed[name] = value return processed
module function_definition identifier parameters identifier identifier identifier identifier identifier block if_statement comparison_operator identifier none block return_statement identifier expression_statement assignment identifier dictionary for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement comparison_operator identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier else_clause block expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier except_clause as_pattern identifier as_pattern_target identifier block raise_statement call identifier argument_list call attribute string string_start string_content escape_sequence string_end identifier argument_list identifier identifier elif_clause call identifier argument_list identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier identifier identifier expression_statement assignment subscript identifier identifier identifier return_statement identifier
Recursively evaluate expressions in a dictionary of values.
def files_in_subdir(dir, subdir): paths = [] for (path, dirs, files) in os.walk(os.path.join(dir, subdir)): for file in files: paths.append(os.path.relpath(os.path.join(path, file), dir)) return paths
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier list for_statement tuple_pattern identifier identifier identifier call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier identifier block for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier identifier identifier return_statement identifier
Find all files in a directory.
def cms_check(migrate_cmd=False): from django.core.management import call_command try: import cms _create_db(migrate_cmd) call_command('cms', 'check') except ImportError: print('cms_check available only if django CMS is installed')
module function_definition identifier parameters default_parameter identifier false block import_from_statement dotted_name identifier identifier identifier dotted_name identifier try_statement block import_statement dotted_name identifier expression_statement call identifier argument_list identifier expression_statement call identifier argument_list string string_start string_content string_end string string_start string_content string_end except_clause identifier block expression_statement call identifier argument_list string string_start string_content string_end
Runs the django CMS ``cms check`` command
def inflate(self): if not self._is_inflated: self.check_version() for k, v in self._filter.items(): if '[' in v: self._filter[k] = ast.literal_eval(v) self.load(self.client.get(self.url, params=self._filter)) self._is_inflated = True return self
module function_definition identifier parameters identifier block if_statement not_operator attribute identifier identifier block expression_statement call attribute identifier identifier argument_list for_statement pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list block if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment subscript attribute identifier identifier identifier call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list attribute identifier identifier keyword_argument identifier attribute identifier identifier expression_statement assignment attribute identifier identifier true return_statement identifier
Load the collection from the server, if necessary.
def append_elements(self, elements): self._elements = self._elements + list(elements) self._on_element_change()
module function_definition identifier parameters identifier identifier block expression_statement assignment attribute identifier identifier binary_operator attribute identifier identifier call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list
Appends more elements to the contained internal elements.
def _create_fw_fab_dev(self, tenant_id, drvr_name, fw_dict): if fw_dict.get('fw_type') == fw_constants.FW_TENANT_EDGE: self._create_fw_fab_dev_te(tenant_id, drvr_name, fw_dict)
module function_definition identifier parameters identifier identifier identifier identifier block if_statement comparison_operator call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier block expression_statement call attribute identifier identifier argument_list identifier identifier identifier
This routine calls the Tenant Edge routine if FW Type is TE.
def add_timestamps(self): transform, _ = self.transform().inverted() stamps = _make_timestamps(self.start_time, self.minimum, self.maximum, self.parent.value('timestamp_steps')) for stamp, xpos in zip(*stamps): text = self.scene.addSimpleText(stamp) text.setFlag(QGraphicsItem.ItemIgnoresTransformations) text_width = text.boundingRect().width() * transform.m11() text.setPos(xpos - text_width / 2, TIME_HEIGHT)
module function_definition identifier parameters identifier block expression_statement assignment pattern_list identifier identifier call attribute call attribute identifier identifier argument_list identifier argument_list expression_statement assignment identifier call identifier argument_list attribute identifier identifier attribute identifier identifier attribute identifier identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end for_statement pattern_list identifier identifier call identifier argument_list list_splat identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier expression_statement assignment identifier binary_operator call attribute call attribute identifier identifier argument_list identifier argument_list call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list binary_operator identifier binary_operator identifier integer identifier
Add timestamps at the bottom of the overview.
def _request(self, method, url, **kwargs): self.last_request = None self.last_response = self.session.request(method, url, auth=self.auth, headers=self.headers, **kwargs) self.last_request = self.last_response.request self.last_url = self.last_response.url if self.last_response.status_code == requests.codes.forbidden: raise ForbiddenError(self.last_response.json()['results'][0]['detail']) return self.last_response
module function_definition identifier parameters identifier identifier identifier dictionary_splat_pattern identifier block expression_statement assignment attribute identifier identifier none expression_statement assignment attribute identifier identifier call attribute attribute identifier identifier identifier argument_list identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier dictionary_splat identifier expression_statement assignment attribute identifier identifier attribute attribute identifier identifier identifier expression_statement assignment attribute identifier identifier attribute attribute identifier identifier identifier if_statement comparison_operator attribute attribute identifier identifier identifier attribute attribute identifier identifier identifier block raise_statement call identifier argument_list subscript subscript subscript call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end integer string string_start string_content string_end return_statement attribute identifier identifier
Perform the request on the API.
def widget_from_tuple(o): if _matches(o, (Real, Real)): min, max, value = _get_min_max_value(o[0], o[1]) if all(isinstance(_, Integral) for _ in o): cls = IntSlider else: cls = FloatSlider return cls(value=value, min=min, max=max) elif _matches(o, (Real, Real, Real)): step = o[2] if step <= 0: raise ValueError("step must be >= 0, not %r" % step) min, max, value = _get_min_max_value(o[0], o[1], step=step) if all(isinstance(_, Integral) for _ in o): cls = IntSlider else: cls = FloatSlider return cls(value=value, min=min, max=max, step=step)
module function_definition identifier parameters identifier block if_statement call identifier argument_list identifier tuple identifier identifier block expression_statement assignment pattern_list identifier identifier identifier call identifier argument_list subscript identifier integer subscript identifier integer if_statement call identifier generator_expression call identifier argument_list identifier identifier for_in_clause identifier identifier block expression_statement assignment identifier identifier else_clause block expression_statement assignment identifier identifier return_statement call identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier elif_clause call identifier argument_list identifier tuple identifier identifier identifier block expression_statement assignment identifier subscript identifier integer if_statement comparison_operator identifier integer block raise_statement call identifier argument_list binary_operator string string_start string_content string_end identifier expression_statement assignment pattern_list identifier identifier identifier call identifier argument_list subscript identifier integer subscript identifier integer keyword_argument identifier identifier if_statement call identifier generator_expression call identifier argument_list identifier identifier for_in_clause identifier identifier block expression_statement assignment identifier identifier else_clause block expression_statement assignment identifier identifier return_statement call identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier
Make widgets from a tuple abbreviation.
def del_metadata_keys(self, bucket, label, keys): if self.mode !="r": try: payload = self._get_bucket_md(bucket) except OFSFileNotFound: raise OFSFileNotFound("Couldn't find a md file for %s bucket" % bucket) except OFSException as e: raise OFSException(e) if payload.has_key(label): for key in [x for x in keys if payload[label].has_key(x)]: del payload[label][key] self.put_stream(bucket, MD_FILE, json.dumps(payload), params={}, replace=True, add_md=False) else: raise OFSException("Cannot update MD in archive in 'r' mode")
module function_definition identifier parameters identifier identifier identifier identifier block if_statement comparison_operator attribute identifier identifier string string_start string_content string_end block try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list identifier except_clause identifier block raise_statement call identifier argument_list binary_operator string string_start string_content string_end identifier except_clause as_pattern identifier as_pattern_target identifier block raise_statement call identifier argument_list identifier if_statement call attribute identifier identifier argument_list identifier block for_statement identifier list_comprehension identifier for_in_clause identifier identifier if_clause call attribute subscript identifier identifier identifier argument_list identifier block delete_statement subscript subscript identifier identifier identifier expression_statement call attribute identifier identifier argument_list identifier identifier call attribute identifier identifier argument_list identifier keyword_argument identifier dictionary keyword_argument identifier true keyword_argument identifier false else_clause block raise_statement call identifier argument_list string string_start string_content string_end
Delete the metadata corresponding to the specified keys.
def _read_input_csv(in_file): with io.open(in_file, newline=None) as in_handle: reader = csv.reader(in_handle) next(reader) for line in reader: if line: (fc_id, lane, sample_id, genome, barcode) = line[:5] yield fc_id, lane, sample_id, genome, barcode
module function_definition identifier parameters identifier block with_statement with_clause with_item as_pattern call attribute identifier identifier argument_list identifier keyword_argument identifier none as_pattern_target identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement call identifier argument_list identifier for_statement identifier identifier block if_statement identifier block expression_statement assignment tuple_pattern identifier identifier identifier identifier identifier subscript identifier slice integer expression_statement yield expression_list identifier identifier identifier identifier identifier
Parse useful details from SampleSheet CSV file.
def write_data(self, write_finished_cb): self._write_finished_cb = write_finished_cb data = bytearray() for led in self.leds: R5 = ((int)((((int(led.r) & 0xFF) * 249 + 1014) >> 11) & 0x1F) * led.intensity / 100) G6 = ((int)((((int(led.g) & 0xFF) * 253 + 505) >> 10) & 0x3F) * led.intensity / 100) B5 = ((int)((((int(led.b) & 0xFF) * 249 + 1014) >> 11) & 0x1F) * led.intensity / 100) tmp = (int(R5) << 11) | (int(G6) << 5) | (int(B5) << 0) data += bytearray((tmp >> 8, tmp & 0xFF)) self.mem_handler.write(self, 0x00, data, flush_queue=True)
module function_definition identifier parameters identifier identifier block expression_statement assignment attribute identifier identifier identifier expression_statement assignment identifier call identifier argument_list for_statement identifier attribute identifier identifier block expression_statement assignment identifier parenthesized_expression binary_operator binary_operator call parenthesized_expression identifier argument_list binary_operator parenthesized_expression binary_operator parenthesized_expression binary_operator binary_operator parenthesized_expression binary_operator call identifier argument_list attribute identifier identifier integer integer integer integer integer attribute identifier identifier integer expression_statement assignment identifier parenthesized_expression binary_operator binary_operator call parenthesized_expression identifier argument_list binary_operator parenthesized_expression binary_operator parenthesized_expression binary_operator binary_operator parenthesized_expression binary_operator call identifier argument_list attribute identifier identifier integer integer integer integer integer attribute identifier identifier integer expression_statement assignment identifier parenthesized_expression binary_operator binary_operator call parenthesized_expression identifier argument_list binary_operator parenthesized_expression binary_operator parenthesized_expression binary_operator binary_operator parenthesized_expression binary_operator call identifier argument_list attribute identifier identifier integer integer integer integer integer attribute identifier identifier integer expression_statement assignment identifier binary_operator binary_operator parenthesized_expression binary_operator call identifier argument_list identifier integer parenthesized_expression binary_operator call identifier argument_list identifier integer parenthesized_expression binary_operator call identifier argument_list identifier integer expression_statement augmented_assignment identifier call identifier argument_list tuple binary_operator identifier integer binary_operator identifier integer expression_statement call attribute attribute identifier identifier identifier argument_list identifier integer identifier keyword_argument identifier true
Write the saved LED-ring data to the Crazyflie
def srbt1(bt_address, pkts, *args, **kargs): a, b = srbt(bt_address, pkts, *args, **kargs) if len(a) > 0: return a[0][1]
module function_definition identifier parameters identifier identifier list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment pattern_list identifier identifier call identifier argument_list identifier identifier list_splat identifier dictionary_splat identifier if_statement comparison_operator call identifier argument_list identifier integer block return_statement subscript subscript identifier integer integer
send and receive 1 packet using a bluetooth socket
def check_outlet(self, helper): try: outlet_name, outlet_state = self.sess.get_oids(self.oids['oid_outlet_name'], self.oids['oid_outlet_state']) except health_monitoring_plugins.SnmpException as e: helper.exit(summary=str(e), exit_code=unknown, perfdata='') outlet_real_state = states[int(outlet_state)] if outlet_real_state != "on": helper.status(critical) helper.add_summary("Outlet %s - '%s' is: %s" % (self.number, outlet_name, outlet_real_state.upper()))
module function_definition identifier parameters identifier identifier block try_statement block expression_statement assignment pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list subscript attribute identifier identifier string string_start string_content string_end subscript attribute identifier identifier string string_start string_content string_end except_clause as_pattern attribute identifier identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list keyword_argument identifier call identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier string string_start string_end expression_statement assignment identifier subscript identifier call identifier argument_list identifier if_statement comparison_operator identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end tuple attribute identifier identifier identifier call attribute identifier identifier argument_list
check the status of the specified outlet
def _get_entity(partition_key, row_key, select, accept): _validate_not_none('partition_key', partition_key) _validate_not_none('row_key', row_key) _validate_not_none('accept', accept) request = HTTPRequest() request.method = 'GET' request.headers = [('Accept', _to_str(accept))] request.query = [('$select', _to_str(select))] return request
module function_definition identifier parameters identifier identifier identifier identifier block expression_statement call identifier argument_list string string_start string_content string_end identifier expression_statement call identifier argument_list string string_start string_content string_end identifier expression_statement call identifier argument_list string string_start string_content string_end identifier expression_statement assignment identifier call identifier argument_list expression_statement assignment attribute identifier identifier string string_start string_content string_end expression_statement assignment attribute identifier identifier list tuple string string_start string_content string_end call identifier argument_list identifier expression_statement assignment attribute identifier identifier list tuple string string_start string_content string_end call identifier argument_list identifier return_statement identifier
Constructs a get entity request.
def GetRepacker(self, context, signer=None): if "Target:Darwin" in context: deployer_class = build.DarwinClientRepacker elif "Target:Windows" in context: deployer_class = build.WindowsClientRepacker elif "Target:LinuxDeb" in context: deployer_class = build.LinuxClientRepacker elif "Target:LinuxRpm" in context: deployer_class = build.CentosClientRepacker else: raise RuntimeError("Bad build context: %s" % context) return deployer_class(context=context, signer=signer)
module function_definition identifier parameters identifier identifier default_parameter identifier none block if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment identifier attribute identifier identifier elif_clause comparison_operator string string_start string_content string_end identifier block expression_statement assignment identifier attribute identifier identifier elif_clause comparison_operator string string_start string_content string_end identifier block expression_statement assignment identifier attribute identifier identifier elif_clause comparison_operator string string_start string_content string_end identifier block expression_statement assignment identifier attribute identifier identifier else_clause block raise_statement call identifier argument_list binary_operator string string_start string_content string_end identifier return_statement call identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier
Get the appropriate client deployer based on the selected flags.
def read_file(filename): with open(join(abspath(dirname(__file__)), filename)) as file: return file.read()
module function_definition identifier parameters identifier block with_statement with_clause with_item as_pattern call identifier argument_list call identifier argument_list call identifier argument_list call identifier argument_list identifier identifier as_pattern_target identifier block return_statement call attribute identifier identifier argument_list
Read the contents of a file located relative to setup.py
def _init(init, X, N, rank, dtype): Uinit = [None for _ in range(N)] if isinstance(init, list): Uinit = init elif init == 'random': for n in range(1, N): Uinit[n] = array(rand(X.shape[n], rank), dtype=dtype) elif init == 'nvecs': for n in range(1, N): Uinit[n] = array(nvecs(X, n, rank), dtype=dtype) else: raise 'Unknown option (init=%s)' % str(init) return Uinit
module function_definition identifier parameters identifier identifier identifier identifier identifier block expression_statement assignment identifier list_comprehension none for_in_clause identifier call identifier argument_list identifier if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier identifier elif_clause comparison_operator identifier string string_start string_content string_end block for_statement identifier call identifier argument_list integer identifier block expression_statement assignment subscript identifier identifier call identifier argument_list call identifier argument_list subscript attribute identifier identifier identifier identifier keyword_argument identifier identifier elif_clause comparison_operator identifier string string_start string_content string_end block for_statement identifier call identifier argument_list integer identifier block expression_statement assignment subscript identifier identifier call identifier argument_list call identifier argument_list identifier identifier identifier keyword_argument identifier identifier else_clause block raise_statement binary_operator string string_start string_content string_end call identifier argument_list identifier return_statement identifier
Initialization for CP models
def refresh_devices(self): try: response = self.api.get("/api/v2/devices", {'properties':'all'}) for device_data in response['DeviceList']: self.devices.append(Device(device_data, self)) except APIError as e: print("API error: ") for key,value in e.data.iteritems: print(str(key) + ": " + str(value))
module function_definition identifier parameters identifier block try_statement block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end dictionary pair string string_start string_content string_end string string_start string_content string_end for_statement identifier subscript identifier string string_start string_content string_end block expression_statement call attribute attribute identifier identifier identifier argument_list call identifier argument_list identifier identifier except_clause as_pattern identifier as_pattern_target identifier block expression_statement call identifier argument_list string string_start string_content string_end for_statement pattern_list identifier identifier attribute attribute identifier identifier identifier block expression_statement call identifier argument_list binary_operator binary_operator call identifier argument_list identifier string string_start string_content string_end call identifier argument_list identifier
Queries hub for list of devices, and creates new device objects
def decorate_check_error(error_enum): def decorator(func): @functools.wraps(func) def _check_error(*args, **kwargs): return check_error(func(*args, **kwargs), error_enum) return _check_error return decorator
module function_definition identifier parameters identifier block function_definition identifier parameters identifier block decorated_definition decorator call attribute identifier identifier argument_list identifier function_definition identifier parameters list_splat_pattern identifier dictionary_splat_pattern identifier block return_statement call identifier argument_list call identifier argument_list list_splat identifier dictionary_splat identifier identifier return_statement identifier return_statement identifier
Decorator to call `check_error` on the return value.
def _wrap_deprecated_function(func, message): def _(col): warnings.warn(message, DeprecationWarning) return func(col) return functools.wraps(func)(_)
module function_definition identifier parameters identifier identifier block function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list identifier identifier return_statement call identifier argument_list identifier return_statement call call attribute identifier identifier argument_list identifier argument_list identifier
Wrap the deprecated function to print out deprecation warnings
def _is_dir(self, f): return self._tar.getmember(f).type == tarfile.DIRTYPE
module function_definition identifier parameters identifier identifier block return_statement comparison_operator attribute call attribute attribute identifier identifier identifier argument_list identifier identifier attribute identifier identifier
Check if the given in-dap file is a directory
def updateRemoveEnabled( self ): lineWidgets = self.lineWidgets() count = len(lineWidgets) state = self.minimumCount() < count for widget in lineWidgets: widget.setRemoveEnabled(state)
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier comparison_operator call attribute identifier identifier argument_list identifier for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list identifier
Updates the remove enabled baesd on the current number of line widgets.
def start(self): if not self.writeThread.isAlive() and not self.readThread.isAlive(): self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.client.connect(self.ADDR) self.running = True self.writeThread.start() self.readThread.start()
module function_definition identifier parameters identifier block if_statement boolean_operator not_operator call attribute attribute identifier identifier identifier argument_list not_operator call attribute attribute identifier identifier identifier argument_list block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier expression_statement assignment attribute identifier identifier true expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list
Open sockets to the server and start threads
def parents(self): q = self.__parent__.parents() q.put(self) return q
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement call attribute identifier identifier argument_list identifier return_statement identifier
Returns an simple FIFO queue with the ancestors and itself.
def version_already_uploaded(project_name, version_str, index_url, requests_verify=True): all_versions = _get_uploaded_versions(project_name, index_url, requests_verify) return version_str in all_versions
module function_definition identifier parameters identifier identifier identifier default_parameter identifier true block expression_statement assignment identifier call identifier argument_list identifier identifier identifier return_statement comparison_operator identifier identifier
Check to see if the version specified has already been uploaded to the configured index
def keysym_definitions(): for keysym_line in keysym_lines(): keysym_number, codepoint, status, _, name_part = [ p.strip() for p in keysym_line.split(None, 4)] name = name_part.split()[0] yield (int(keysym_number, 16), codepoint[1:], status, name)
module function_definition identifier parameters block for_statement identifier call identifier argument_list block expression_statement assignment pattern_list identifier identifier identifier identifier identifier list_comprehension call attribute identifier identifier argument_list for_in_clause identifier call attribute identifier identifier argument_list none integer expression_statement assignment identifier subscript call attribute identifier identifier argument_list integer expression_statement yield tuple call identifier argument_list identifier integer subscript identifier slice integer identifier identifier
Yields all keysym definitions parsed as tuples.
def get(self, url, params=dict()): try: res = requests.get(url, headers=self.headers, params=params) return json.loads(res.text) except Exception as e: print(e) return "error"
module function_definition identifier parameters identifier identifier default_parameter identifier call identifier argument_list block try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier identifier return_statement call attribute identifier identifier argument_list attribute identifier identifier except_clause as_pattern identifier as_pattern_target identifier block expression_statement call identifier argument_list identifier return_statement string string_start string_content string_end
Http get method wrapper, to support search.
def drive_rotational_speed_rpm(self): drv_rot_speed_rpm = set() for member in self.get_members(): if member.rotational_speed_rpm is not None: drv_rot_speed_rpm.add(member.rotational_speed_rpm) return drv_rot_speed_rpm
module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list for_statement identifier call attribute identifier identifier argument_list block if_statement comparison_operator attribute identifier identifier none block expression_statement call attribute identifier identifier argument_list attribute identifier identifier return_statement identifier
Gets the set of rotational speed of the HDD drives
def _delete_sbo_tar_gz(self): if not self.auto and os.path.isfile(self.meta.build_path + self.script): os.remove(self.meta.build_path + self.script)
module function_definition identifier parameters identifier block if_statement boolean_operator not_operator attribute identifier identifier call attribute attribute identifier identifier identifier argument_list binary_operator attribute attribute identifier identifier identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list binary_operator attribute attribute identifier identifier identifier attribute identifier identifier
Delete slackbuild tar.gz file after untar
def _get_metadata_path(self, key): return "{group}/meta/{key}/meta".format(group=self.group._v_pathname, key=key)
module function_definition identifier parameters identifier identifier block return_statement call attribute string string_start string_content string_end identifier argument_list keyword_argument identifier attribute attribute identifier identifier identifier keyword_argument identifier identifier
return the metadata pathname for this key
def build_dir(): tag_arr = ['add', 'edit', 'view', 'list', 'infolist'] path_arr = [os.path.join(CRUD_PATH, x) for x in tag_arr] for wpath in path_arr: if os.path.exists(wpath): continue os.makedirs(wpath)
module function_definition identifier parameters block 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 string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier list_comprehension call attribute attribute identifier identifier identifier argument_list identifier identifier for_in_clause identifier identifier for_statement identifier identifier block if_statement call attribute attribute identifier identifier identifier argument_list identifier block continue_statement expression_statement call attribute identifier identifier argument_list identifier
Build the directory used for templates.
def process_file(path): info = dict() with fits.open(path) as hdu: head = hdu[0].header data = hdu[0].data labels = {theme: value for value, theme in list(hdu[1].data)} info['filename'] = os.path.basename(path) info['trainer'] = head['expert'] info['date-label'] = dateparser.parse(head['date-lab']) info['date-observation'] = dateparser.parse(head['date-end']) for theme in themes: info[theme + "_count"] = np.sum(data == labels[theme]) return info
module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list with_statement with_clause with_item as_pattern call attribute identifier identifier argument_list identifier as_pattern_target identifier block expression_statement assignment identifier attribute subscript identifier integer identifier expression_statement assignment identifier attribute subscript identifier integer identifier expression_statement assignment identifier dictionary_comprehension pair identifier identifier for_in_clause pattern_list identifier identifier call identifier argument_list attribute subscript identifier integer identifier expression_statement assignment subscript identifier string string_start string_content string_end call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment subscript identifier string string_start string_content string_end subscript identifier string string_start string_content string_end expression_statement assignment subscript identifier string string_start string_content string_end call attribute identifier identifier argument_list subscript identifier string string_start string_content string_end expression_statement assignment subscript identifier string string_start string_content string_end call attribute identifier identifier argument_list subscript identifier string string_start string_content string_end for_statement identifier identifier block expression_statement assignment subscript identifier binary_operator identifier string string_start string_content string_end call attribute identifier identifier argument_list comparison_operator identifier subscript identifier identifier return_statement identifier
Open a single labeled image at path and get needed information, return as a dictionary
def output_extras(self, output_file): output_directory = dirname(output_file) def local_path(name): return join(output_directory, self.path_helper.local_name(name)) files_directory = "%s_files%s" % (basename(output_file)[0:-len(".dat")], self.path_helper.separator) names = filter(lambda o: o.startswith(files_directory), self.output_directory_contents) return dict(map(lambda name: (local_path(name), name), names))
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier function_definition identifier parameters identifier block return_statement call identifier argument_list identifier call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment identifier binary_operator string string_start string_content string_end tuple subscript call identifier argument_list identifier slice integer unary_operator call identifier argument_list string string_start string_content string_end attribute attribute identifier identifier identifier expression_statement assignment identifier call identifier argument_list lambda lambda_parameters identifier call attribute identifier identifier argument_list identifier attribute identifier identifier return_statement call identifier argument_list call identifier argument_list lambda lambda_parameters identifier tuple call identifier argument_list identifier identifier identifier
Returns dict mapping local path to remote name.
def validate(self): self.pixel_truth_sum = np.sum(self.pixel_truth_counts, axis=0) self.pixel_classification_sum = np.sum(self.pixel_classification_counts, axis=0)
module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list attribute identifier identifier keyword_argument identifier integer expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list attribute identifier identifier keyword_argument identifier integer
Aggregate the results from all EOPatches.
def handle(self): mr_id = self.request.get("mapreduce_id") logging.info("Processing kickoff for job %s", mr_id) state = model.MapreduceState.get_by_job_id(mr_id) if not self._check_mr_state(state, mr_id): return readers, serialized_readers_entity = self._get_input_readers(state) if readers is None: logging.warning("Found no mapper input data to process.") state.active = False state.result_status = model.MapreduceState.RESULT_SUCCESS ControllerCallbackHandler._finalize_job( state.mapreduce_spec, state) return False self._setup_output_writer(state) result = self._save_states(state, serialized_readers_entity) if result is None: readers, _ = self._get_input_readers(state) elif not result: return queue_name = self.request.headers.get("X-AppEngine-QueueName") KickOffJobHandler._schedule_shards(state.mapreduce_spec, readers, queue_name, state.mapreduce_spec.params["base_path"], state) ControllerCallbackHandler.reschedule( state, state.mapreduce_spec, serial_id=0, queue_name=queue_name)
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 expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier if_statement not_operator call attribute identifier identifier argument_list identifier identifier block return_statement expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list identifier if_statement comparison_operator identifier none block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment attribute identifier identifier false expression_statement assignment attribute identifier identifier attribute attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier identifier return_statement false expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier if_statement comparison_operator identifier none block expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list identifier elif_clause not_operator identifier block return_statement expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list attribute identifier identifier identifier identifier subscript attribute attribute identifier identifier identifier string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list identifier attribute identifier identifier keyword_argument identifier integer keyword_argument identifier identifier
Handles kick off request.
def _work_function(job_q: Queue, result_q: Queue, error_q: Queue) -> None: while True: job = job_q.get() if isinstance(job, _ThreadPoolSentinel): result_q.put(_ThreadPoolSentinel()) error_q.put(_ThreadPoolSentinel()) job_q.task_done() break work_function = job[0] args = job[1] try: result = work_function(*args) except Exception as e: error_q.put((job, e)) else: result_q.put((job, result)) finally: job_q.task_done()
module function_definition identifier parameters typed_parameter identifier type identifier typed_parameter identifier type identifier typed_parameter identifier type identifier type none block while_statement true block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement call identifier argument_list identifier identifier block expression_statement call attribute identifier identifier argument_list call identifier argument_list expression_statement call attribute identifier identifier argument_list call identifier argument_list expression_statement call attribute identifier identifier argument_list break_statement expression_statement assignment identifier subscript identifier integer expression_statement assignment identifier subscript identifier integer try_statement block expression_statement assignment identifier call identifier argument_list list_splat identifier except_clause as_pattern identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list tuple identifier identifier else_clause block expression_statement call attribute identifier identifier argument_list tuple identifier identifier finally_clause block expression_statement call attribute identifier identifier argument_list
Work function expected to run within threads.
def _create_access_token(self, subject_identifier, auth_req, granted_scope, current_scope=None): access_token = AccessToken(rand_str(), self.access_token_lifetime) scope = current_scope or granted_scope logger.debug('creating access token for scope=%s', scope) authz_info = { 'iat': int(time.time()), 'exp': int(time.time()) + self.access_token_lifetime, 'sub': subject_identifier, 'client_id': auth_req['client_id'], 'aud': [auth_req['client_id']], 'scope': scope, 'granted_scope': granted_scope, 'token_type': access_token.BEARER_TOKEN_TYPE, self.KEY_AUTHORIZATION_REQUEST: auth_req } self.access_tokens[access_token.value] = authz_info logger.debug('new access_token=%s to client_id=%s for sub=%s valid_until=%s', access_token.value, auth_req['client_id'], subject_identifier, authz_info['exp']) return access_token
module function_definition identifier parameters identifier identifier identifier identifier default_parameter identifier none block expression_statement assignment identifier call identifier argument_list call identifier argument_list attribute identifier identifier expression_statement assignment identifier boolean_operator identifier identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier expression_statement assignment identifier dictionary pair string string_start string_content string_end call identifier argument_list call attribute identifier identifier argument_list pair string string_start string_content string_end binary_operator call identifier argument_list call attribute identifier identifier argument_list attribute identifier identifier pair string string_start string_content string_end identifier 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 list subscript identifier string string_start string_content string_end pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier pair string string_start string_content string_end attribute identifier identifier pair attribute identifier identifier identifier expression_statement assignment subscript attribute identifier identifier attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier subscript identifier string string_start string_content string_end identifier subscript identifier string string_start string_content string_end return_statement identifier
Creates an access token bound to the subject identifier, client id and requested scope.
def value(self): if self._wrapped is not self.Null: return self._wrapped else: return self.obj
module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier attribute identifier identifier block return_statement attribute identifier identifier else_clause block return_statement attribute identifier identifier
returns the object instead of instance
def texture_from_image(renderer, image_name): soft_surface = ext.load_image(image_name) texture = SDL_CreateTextureFromSurface(renderer.renderer, soft_surface) SDL_FreeSurface(soft_surface) return texture
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call identifier argument_list attribute identifier identifier identifier expression_statement call identifier argument_list identifier return_statement identifier
Create an SDL2 Texture from an image file
def frac_vol_floc(ConcAluminum, ConcClay, coag, DIM_FRACTAL, material, DiamTarget): return (frac_vol_floc_initial(ConcAluminum, ConcClay, coag, material) * (DiamTarget / material.Diameter)**(3-DIM_FRACTAL) )
module function_definition identifier parameters identifier identifier identifier identifier identifier identifier block return_statement parenthesized_expression binary_operator call identifier argument_list identifier identifier identifier identifier binary_operator parenthesized_expression binary_operator identifier attribute identifier identifier parenthesized_expression binary_operator integer identifier
Return the floc volume fraction.
def dump(self, fileobj): if self.file_format == 'csv': csv.writer(fileobj).writerows(self.raw_dict().items()) elif self.file_format == 'json': json.dump(self.raw_dict(), fileobj, separators=(',', ':')) elif self.file_format == 'pickle': pickle.dump(dict(self.raw_dict()), fileobj, 2) else: raise NotImplementedError('Unknown format: ' + repr(self.file_format))
module function_definition identifier parameters identifier identifier block if_statement comparison_operator attribute identifier identifier string string_start string_content string_end block expression_statement call attribute call attribute identifier identifier argument_list identifier identifier argument_list call attribute call attribute identifier identifier argument_list identifier argument_list elif_clause comparison_operator attribute identifier identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier keyword_argument identifier tuple string string_start string_content string_end string string_start string_content string_end elif_clause comparison_operator attribute identifier identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list call identifier argument_list call attribute identifier identifier argument_list identifier integer else_clause block raise_statement call identifier argument_list binary_operator string string_start string_content string_end call identifier argument_list attribute identifier identifier
Handles the writing of the dict to the file object