_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q235800
ODOO.exec_workflow
train
def exec_workflow(self, model, record_id, signal): """Execute the workflow `signal` on the instance having the ID `record_id` of `model`. *Python 2:* :raise: :class:`odoorpc.error.RPCError` :raise: :class:`odoorpc.error.InternalError` (if not logged) :raise: `urllib2.UR...
python
{ "resource": "" }
q235801
DB.create
train
def create(self, password, db, demo=False, lang='en_US', admin_password='admin'): """Request the server to create a new database named `db` which will have `admin_password` as administrator password and localized with the `lang` parameter. You have to set the flag `demo` to `True` in ord...
python
{ "resource": "" }
q235802
DB.duplicate
train
def duplicate(self, password, db, new_db): """Duplicate `db' as `new_db`. >>> odoo.db.duplicate('super_admin_passwd', 'prod', 'test') # doctest: +SKIP The super administrator password is required to perform this method. *Python 2:* :raise: :class:`odoorpc.error.RPCError` (acc...
python
{ "resource": "" }
q235803
ConnectorJSONRPC.timeout
train
def timeout(self, timeout): """Set the timeout.""" self._proxy_json._timeout = timeout self._proxy_http._timeout = timeout
python
{ "resource": "" }
q235804
is_int
train
def is_int(value): """Return `True` if ``value`` is an integer.""" if isinstance(value, bool): return False try: int(value) return True except (ValueError, TypeError): return False
python
{ "resource": "" }
q235805
BaseField.check_value
train
def check_value(self, value): """Check the validity of a value for the field.""" #if self.readonly: # raise error.Error( # "'{field_name}' field is readonly".format( # field_name=self.name)) if value and self.size: if not is_string(value):...
python
{ "resource": "" }
q235806
Reference._check_relation
train
def _check_relation(self, relation): """Raise a `ValueError` if `relation` is not allowed among the possible values. """ selection = [val[0] for val in self.selection] if relation not in selection: raise ValueError( ("The value '{value}' supplied doesn...
python
{ "resource": "" }
q235807
Model._with_context
train
def _with_context(self, *args, **kwargs): """As the `with_context` class method but for recordset.""" context = dict(args[0] if args else self.env.context, **kwargs) return self.with_env(self.env(context=context))
python
{ "resource": "" }
q235808
Model._with_env
train
def _with_env(self, env): """As the `with_env` class method but for recordset.""" res = self._browse(env, self._ids) return res
python
{ "resource": "" }
q235809
Model._init_values
train
def _init_values(self, context=None): """Retrieve field values from the server. May be used to restore the original values in the purpose to cancel all changes made. """ if context is None: context = self.env.context # Get basic fields (no relational ones) ...
python
{ "resource": "" }
q235810
from_wei
train
def from_wei(number: int, unit: str) -> Union[int, decimal.Decimal]: """ Takes a number of wei and converts it to any other ether unit. """ if unit.lower() not in units: raise ValueError( "Unknown unit. Must be one of {0}".format("/".join(units.keys())) ) if number == 0...
python
{ "resource": "" }
q235811
to_wei
train
def to_wei(number: int, unit: str) -> int: """ Takes a number of a unit and converts it to wei. """ if unit.lower() not in units: raise ValueError( "Unknown unit. Must be one of {0}".format("/".join(units.keys())) ) if is_integer(number) or is_string(number): d_...
python
{ "resource": "" }
q235812
validate_conversion_arguments
train
def validate_conversion_arguments(to_wrap): """ Validates arguments for conversion functions. - Only a single argument is present - Kwarg must be 'primitive' 'hexstr' or 'text' - If it is 'hexstr' or 'text' that it is a text type """ @functools.wraps(to_wrap) def wrapper(*args, **kwargs...
python
{ "resource": "" }
q235813
replace_exceptions
train
def replace_exceptions( old_to_new_exceptions: Dict[Type[BaseException], Type[BaseException]] ) -> Callable[..., Any]: """ Replaces old exceptions with new exceptions to be raised in their place. """ old_exceptions = tuple(old_to_new_exceptions.keys()) def decorator(to_wrap: Callable[..., Any])...
python
{ "resource": "" }
q235814
collapse_if_tuple
train
def collapse_if_tuple(abi): """Converts a tuple from a dict to a parenthesized list of its types. >>> from eth_utils.abi import collapse_if_tuple >>> collapse_if_tuple( ... { ... 'components': [ ... {'name': 'anAddress', 'type': 'address'}, ... {'name': '...
python
{ "resource": "" }
q235815
is_hex_address
train
def is_hex_address(value: Any) -> bool: """ Checks if the given string of text type is an address in hexadecimal encoded form. """ if not is_text(value): return False elif not is_hex(value): return False else: unprefixed = remove_0x_prefix(value) return len(unpref...
python
{ "resource": "" }
q235816
is_binary_address
train
def is_binary_address(value: Any) -> bool: """ Checks if the given string is an address in raw bytes form. """ if not is_bytes(value): return False elif len(value) != 20: return False else: return True
python
{ "resource": "" }
q235817
is_address
train
def is_address(value: Any) -> bool: """ Checks if the given string in a supported value is an address in any of the known formats. """ if is_checksum_formatted_address(value): return is_checksum_address(value) elif is_hex_address(value): return True elif is_binary_address(val...
python
{ "resource": "" }
q235818
to_normalized_address
train
def to_normalized_address(value: AnyStr) -> HexAddress: """ Converts an address to its normalized hexadecimal representation. """ try: hex_address = hexstr_if_str(to_hex, value).lower() except AttributeError: raise TypeError( "Value must be any string, instead got type {}...
python
{ "resource": "" }
q235819
is_normalized_address
train
def is_normalized_address(value: Any) -> bool: """ Returns whether the provided value is an address in its normalized form. """ if not is_address(value): return False else: return value == to_normalized_address(value)
python
{ "resource": "" }
q235820
is_canonical_address
train
def is_canonical_address(address: Any) -> bool: """ Returns `True` if the `value` is an address in its canonical form. """ if not is_bytes(address) or len(address) != 20: return False return address == to_canonical_address(address)
python
{ "resource": "" }
q235821
is_same_address
train
def is_same_address(left: AnyAddress, right: AnyAddress) -> bool: """ Checks if both addresses are same or not. """ if not is_address(left) or not is_address(right): raise ValueError("Both values must be valid addresses") else: return to_normalized_address(left) == to_normalized_addr...
python
{ "resource": "" }
q235822
to_checksum_address
train
def to_checksum_address(value: AnyStr) -> ChecksumAddress: """ Makes a checksum address given a supported format. """ norm_address = to_normalized_address(value) address_hash = encode_hex(keccak(text=remove_0x_prefix(norm_address))) checksum_address = add_0x_prefix( "".join( ...
python
{ "resource": "" }
q235823
get_msi_token
train
def get_msi_token(resource, port=50342, msi_conf=None): """Get MSI token if MSI_ENDPOINT is set. IF MSI_ENDPOINT is not set, will try legacy access through 'http://localhost:{}/oauth2/token'.format(port). If msi_conf is used, must be a dict of one key in ["client_id", "object_id", "msi_res_id"] :para...
python
{ "resource": "" }
q235824
get_msi_token_webapp
train
def get_msi_token_webapp(resource): """Get a MSI token from inside a webapp or functions. Env variable will look like: - MSI_ENDPOINT = http://127.0.0.1:41741/MSI/token/ - MSI_SECRET = 69418689F1E342DD946CB82994CDA3CB """ try: msi_endpoint = os.environ['MSI_ENDPOINT'] msi_secre...
python
{ "resource": "" }
q235825
AADMixin._configure
train
def _configure(self, **kwargs): """Configure authentication endpoint. Optional kwargs may include: - cloud_environment (msrestazure.azure_cloud.Cloud): A targeted cloud environment - china (bool): Configure auth for China-based service, default is 'False'. ...
python
{ "resource": "" }
q235826
AADMixin._convert_token
train
def _convert_token(self, token): """Convert token fields from camel case. :param dict token: An authentication token. :rtype: dict """ # Beware that ADAL returns a pointer to its own dict, do # NOT change it in place token = token.copy() # If it's from A...
python
{ "resource": "" }
q235827
AADMixin.signed_session
train
def signed_session(self, session=None): """Create token-friendly Requests session, using auto-refresh. Used internally when a request is made. If a session object is provided, configure it directly. Otherwise, create a new session and return it. :param session: The session to c...
python
{ "resource": "" }
q235828
AADMixin.refresh_session
train
def refresh_session(self, session=None): """Return updated session if token has expired, attempts to refresh using newly acquired token. If a session object is provided, configure it directly. Otherwise, create a new session and return it. :param session: The session to configu...
python
{ "resource": "" }
q235829
_validate
train
def _validate(url): """Validate a url. :param str url: Polling URL extracted from response header. :raises: ValueError if URL has no scheme or host. """ if url is None: return parsed = urlparse(url) if not parsed.scheme or not parsed.netloc: raise ValueError("Invalid URL hea...
python
{ "resource": "" }
q235830
LongRunningOperation._raise_if_bad_http_status_and_method
train
def _raise_if_bad_http_status_and_method(self, response): """Check response status code is valid for a Put or Patch request. Must be 200, 201, 202, or 204. :raises: BadStatus if invalid status. """ code = response.status_code if code in {200, 202} or \ (code =...
python
{ "resource": "" }
q235831
LongRunningOperation._deserialize
train
def _deserialize(self, response): """Attempt to deserialize resource from response. :param requests.Response response: latest REST call response. """ # Hacking response with initial status_code previous_status = response.status_code response.status_code = self.initial_st...
python
{ "resource": "" }
q235832
LongRunningOperation.get_status_from_location
train
def get_status_from_location(self, response): """Process the latest status update retrieved from a 'location' header. :param requests.Response response: latest REST call response. :raises: BadResponse if response has no body and not status 202. """ self._raise_if_bad_htt...
python
{ "resource": "" }
q235833
AzureOperationPoller._polling_cookie
train
def _polling_cookie(self): """Collect retry cookie - we only want to do this for the test server at this point, unless we implement a proper cookie policy. :returns: Dictionary containing a cookie header if required, otherwise an empty dictionary. """ parsed_url = urlpa...
python
{ "resource": "" }
q235834
AzureOperationPoller.remove_done_callback
train
def remove_done_callback(self, func): """Remove a callback from the long running operation. :param callable func: The function to be removed from the callbacks. :raises: ValueError if the long running operation has already completed. """ if self._done is None or self._d...
python
{ "resource": "" }
q235835
register_rp_hook
train
def register_rp_hook(r, *args, **kwargs): """This is a requests hook to register RP automatically. You should not use this command manually, this is added automatically by the SDK. See requests documentation for details of the signature of this function. http://docs.python-requests.org/en/master/u...
python
{ "resource": "" }
q235836
_register_rp
train
def _register_rp(session, url_prefix, rp_name): """Synchronously register the RP is paremeter. Return False if we have a reason to believe this didn't work """ post_url = "{}providers/{}/register?api-version=2016-02-01".format(url_prefix, rp_name) get_url = "{}providers/{}?api-version=2016-02-0...
python
{ "resource": "" }
q235837
parse_resource_id
train
def parse_resource_id(rid): """Parses a resource_id into its various parts. Returns a dictionary with a single key-value pair, 'name': rid, if invalid resource id. :param rid: The resource id being parsed :type rid: str :returns: A dictionary with with following key/value pairs (if found): ...
python
{ "resource": "" }
q235838
_populate_alternate_kwargs
train
def _populate_alternate_kwargs(kwargs): """ Translates the parsed arguments into a format used by generic ARM commands such as the resource and lock commands. """ resource_namespace = kwargs['namespace'] resource_type = kwargs.get('child_type_{}'.format(kwargs['last_child_num'])) or kwargs['type'] ...
python
{ "resource": "" }
q235839
_get_parents_from_parts
train
def _get_parents_from_parts(kwargs): """ Get the parents given all the children parameters. """ parent_builder = [] if kwargs['last_child_num'] is not None: parent_builder.append('{type}/{name}/'.format(**kwargs)) for index in range(1, kwargs['last_child_num']): child_namespa...
python
{ "resource": "" }
q235840
resource_id
train
def resource_id(**kwargs): """Create a valid resource id string from the given parts. This method builds the resource id from the left until the next required id parameter to be appended is not found. It then returns the built up id. :param dict kwargs: The keyword arguments that will make up the id. ...
python
{ "resource": "" }
q235841
is_valid_resource_id
train
def is_valid_resource_id(rid, exception_type=None): """Validates the given resource id. :param rid: The resource id being validated. :type rid: str :param exception_type: Raises this Exception if invalid. :type exception_type: :class:`Exception` :returns: A boolean describing whether the id is ...
python
{ "resource": "" }
q235842
is_valid_resource_name
train
def is_valid_resource_name(rname, exception_type=None): """Validates the given resource name to ARM guidelines, individual services may be more restrictive. :param rname: The resource name being validated. :type rname: str :param exception_type: Raises this Exception if invalid. :type exception_typ...
python
{ "resource": "" }
q235843
AsyncARMPolling._delay
train
async def _delay(self): """Check for a 'retry-after' header to set timeout, otherwise use configured timeout. """ if self._response is None: await asyncio.sleep(0) if self._response.headers.get('retry-after'): await asyncio.sleep(int(self._response.headers...
python
{ "resource": "" }
q235844
AsyncARMPolling.update_status
train
async def update_status(self): """Update the current status of the LRO. """ if self._operation.async_url: self._response = await self.request_status(self._operation.async_url) self._operation.set_async_url_if_present(self._response) self._operation.get_status_...
python
{ "resource": "" }
q235845
AsyncARMPolling.request_status
train
async def request_status(self, status_link): """Do a simple GET to this status link. This method re-inject 'x-ms-client-request-id'. :rtype: requests.Response """ # ARM requires to re-inject 'x-ms-client-request-id' while polling header_parameters = { 'x-ms-...
python
{ "resource": "" }
q235846
CloudErrorData.message
train
def message(self, value): """Attempt to deconstruct error message to retrieve further error data. """ try: import ast value = ast.literal_eval(value) except (SyntaxError, TypeError, ValueError): pass try: value = value.get('...
python
{ "resource": "" }
q235847
get_cloud_from_metadata_endpoint
train
def get_cloud_from_metadata_endpoint(arm_endpoint, name=None, session=None): """Get a Cloud object from an ARM endpoint. .. versionadded:: 0.4.11 :Example: .. code:: python get_cloud_from_metadata_endpoint(https://management.azure.com/, "Public Azure") :param str arm_endpoint: The ARM m...
python
{ "resource": "" }
q235848
LongRunningOperation._as_json
train
def _as_json(self, response): """Assuming this is not empty, return the content as JSON. Result/exceptions is not determined if you call this method without testing _is_empty. :raises: DeserializationError if response body contains invalid json data. """ # Assume ClientResponse...
python
{ "resource": "" }
q235849
LongRunningOperation.should_do_final_get
train
def should_do_final_get(self): """Check whether the polling should end doing a final GET. :param requests.Response response: latest REST call response. :rtype: bool """ return ((self.async_url or not self.resource) and self.method in {'PUT', 'PATCH'}) \ or (self....
python
{ "resource": "" }
q235850
LongRunningOperation.set_initial_status
train
def set_initial_status(self, response): """Process first response after initiating long running operation and set self.status attribute. :param requests.Response response: initial REST call response. """ self._raise_if_bad_http_status_and_method(response) if self._is_em...
python
{ "resource": "" }
q235851
LongRunningOperation.parse_resource
train
def parse_resource(self, response): """Assuming this response is a resource, use the deserialization callback to parse it. If body is empty, assuming no resource to return. """ self._raise_if_bad_http_status_and_method(response) if not self._is_empty(response): self.r...
python
{ "resource": "" }
q235852
LongRunningOperation.get_status_from_async
train
def get_status_from_async(self, response): """Process the latest status update retrieved from a 'azure-asyncoperation' header. :param requests.Response response: latest REST call response. :raises: BadResponse if response has no body, or body does not contain status. ""...
python
{ "resource": "" }
q235853
ARMPolling.initialize
train
def initialize(self, client, initial_response, deserialization_callback): """Set the initial status of this LRO. :param initial_response: The initial response of the poller :raises: CloudError if initial status is incorrect LRO state """ self._client = client self._respo...
python
{ "resource": "" }
q235854
worker
train
def worker(): """ Initialize the distributed environment. """ import torch import torch.distributed as dist from torch.multiprocessing import Process import numpy as np print("Initializing distributed pytorch") os.environ['MASTER_ADDR'] = str(args.master_addr) os.environ['MASTER_PORT'] = str(args.mast...
python
{ "resource": "" }
q235855
make_job
train
def make_job(name: str = '', run_name: str = '', num_tasks: int = 0, install_script: str = '', **kwargs ) -> backend.Job: """ Create a job using current backend. Blocks until all tasks are up and initialized. Args: name: name of the job run...
python
{ "resource": "" }
q235856
make_task
train
def make_task(name='', run_name='', **kwargs) -> Task: """Create task, also create dummy run if not specified.""" ncluster_globals.task_launched = True name = ncluster_globals.auto_assign_task_name_if_needed(name) # tmux can't use . for session names tmux_session = name.replace('...
python
{ "resource": "" }
q235857
Task._run_raw
train
def _run_raw(self, cmd, ignore_errors=False): """Runs command directly, skipping tmux interface""" # TODO: capture stdout/stderr for feature parity with aws_backend result = os.system(cmd) if result != 0: if ignore_errors: self.log(f"command ({cmd}) failed.") assert False, "_run_ra...
python
{ "resource": "" }
q235858
Task.upload
train
def upload(self, local_fn, remote_fn=None, dont_overwrite=False): """Uploads file to remote instance. If location not specified, dumps it into default directory. Creates missing directories in path name.""" # support wildcard through glob if '*' in local_fn: for local_subfn in glob.glob(local_fn)...
python
{ "resource": "" }
q235859
Task.logdir
train
def logdir(self): """Returns logging directory, creating one if necessary. See "Logdir" section of design doc on naming convention.""" run_name = ncluster_globals.get_run_for_task(self) logdir = ncluster_globals.get_logdir(run_name) if logdir: return logdir # create logdir. Only single task...
python
{ "resource": "" }
q235860
Run.run_with_output
train
def run_with_output(self, *args, **kwargs): """Runs command on every first job in the run, returns stdout.""" for job in self.jobs: job.run_with_output(*args, **kwargs)
python
{ "resource": "" }
q235861
Run._run_raw
train
def _run_raw(self, *args, **kwargs): """_run_raw on every job in the run.""" for job in self.jobs: job._run_raw(*args, **kwargs)
python
{ "resource": "" }
q235862
keypair_setup
train
def keypair_setup(): """Creates keypair if necessary, saves private key locally, returns contents of private key file.""" os.system('mkdir -p ' + u.PRIVATE_KEY_LOCATION) keypair_name = u.get_keypair_name() keypair = u.get_keypair_dict().get(keypair_name, None) keypair_fn = u.get_keypair_fn() if keypair:...
python
{ "resource": "" }
q235863
placement_group_setup
train
def placement_group_setup(group_name): """Creates placement_group group if necessary. Returns True if new placement_group group was created, False otherwise.""" existing_placement_groups = u.get_placement_group_dict() group = existing_placement_groups.get(group_name, None) if group: assert group.state =...
python
{ "resource": "" }
q235864
Task.upload
train
def upload(self, local_fn: str, remote_fn: str = '', dont_overwrite: bool = False): """Uploads given file to the task. If remote_fn is not specified, dumps it into task current directory with the same name. Args: local_fn: location of file locally remote_fn: location of file on tas...
python
{ "resource": "" }
q235865
Job._non_blocking_wrapper
train
def _non_blocking_wrapper(self, method, *args, **kwargs): """Runs given method on every task in the job. Blocks until all tasks finish. Propagates exception from first failed task.""" exceptions = [] def task_run(task): try: getattr(task, method)(*args, **kwargs) except Exception a...
python
{ "resource": "" }
q235866
get_default_vpc
train
def get_default_vpc(): """ Return default VPC or none if not present """ ec2 = get_ec2_resource() for vpc in ec2.vpcs.all(): if vpc.is_default: return vpc
python
{ "resource": "" }
q235867
get_subnet_dict
train
def get_subnet_dict(): """Returns dictionary of "availability zone" -> subnet for current VPC.""" subnet_dict = {} vpc = get_vpc() for subnet in vpc.subnets.all(): zone = subnet.availability_zone assert zone not in subnet_dict, "More than one subnet in %s, why?" % (zone,) subnet_dict[zone] = subnet ...
python
{ "resource": "" }
q235868
get_keypair_name
train
def get_keypair_name(): """Returns current keypair name.""" username = get_username() assert '-' not in username, "username must not contain -, change $USER" validate_aws_name(username) assert len(username) < 30 # to avoid exceeding AWS 127 char limit return get_prefix() + '-' + username
python
{ "resource": "" }
q235869
get_keypair_fn
train
def get_keypair_fn(): """Location of .pem file for current keypair""" keypair_name = get_keypair_name() account = get_account_number() region = get_region() fn = f'{PRIVATE_KEY_LOCATION}/{keypair_name}-{account}-{region}.pem' return fn
python
{ "resource": "" }
q235870
lookup_instance
train
def lookup_instance(name: str, instance_type: str = '', image_name: str = '', states: tuple = ('running', 'stopped', 'initializing')): """Looks up AWS instance for given instance name, like simple.worker. If no instance found in current AWS environment, returns None. """ ec2 = get_ec2_resour...
python
{ "resource": "" }
q235871
ssh_to_task
train
def ssh_to_task(task) -> paramiko.SSHClient: """Create ssh connection to task's machine returns Paramiko SSH client connected to host. """ username = task.ssh_username hostname = task.public_ip ssh_key_fn = get_keypair_fn() print(f"ssh -i {ssh_key_fn} {username}@{hostname}") pkey = paramiko.RSAKey.fr...
python
{ "resource": "" }
q235872
delete_efs_by_id
train
def delete_efs_by_id(efs_id): """Deletion sometimes fails, try several times.""" start_time = time.time() efs_client = get_efs_client() sys.stdout.write("deleting %s ... " % (efs_id,)) while True: try: response = efs_client.delete_file_system(FileSystemId=efs_id) if is_good_response(response):...
python
{ "resource": "" }
q235873
extract_attr_for_match
train
def extract_attr_for_match(items, **kwargs): """Helper method to get attribute value for an item matching some criterion. Specify target criteria value as dict, with target attribute having value -1 Example: to extract state of vpc matching given vpc id response = [{'State': 'available', 'VpcId': 'vpc-2bb...
python
{ "resource": "" }
q235874
get_instance_property
train
def get_instance_property(instance, property_name): """Retrieves property of an instance, keeps retrying until getting a non-None""" name = get_name(instance) while True: try: value = getattr(instance, property_name) if value is not None: break print(f"retrieving {property_name} on ...
python
{ "resource": "" }
q235875
wait_until_available
train
def wait_until_available(resource): """Waits until interval state becomes 'available'""" while True: resource.load() if resource.state == 'available': break time.sleep(RETRY_INTERVAL_SEC)
python
{ "resource": "" }
q235876
maybe_create_placement_group
train
def maybe_create_placement_group(name='', max_retries=10): """Creates placement_group group or reuses existing one. Crash if unable to create placement_group group. If name is empty, ignores request.""" if not name: return client = get_ec2_client() while True: try: client.describe_placement_...
python
{ "resource": "" }
q235877
is_chief
train
def is_chief(task: backend.Task, run_name: str): """Returns True if task is chief task in the corresponding run""" global run_task_dict if run_name not in run_task_dict: return True task_list = run_task_dict[run_name] assert task in task_list, f"Task {task.name} doesn't belong to run {run_name}" return ...
python
{ "resource": "" }
q235878
ossystem
train
def ossystem(cmd): """Like os.system, but returns output of command as string.""" p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) (stdout, stderr) = p.communicate() return stdout.decode('ascii')
python
{ "resource": "" }
q235879
_maybe_create_resources
train
def _maybe_create_resources(logging_task: Task = None): """Use heuristics to decide to possibly create resources""" def log(*args): if logging_task: logging_task.log(*args) else: util.log(*args) def should_create_resources(): """Check if gateway, keypair, vpc exist.""" prefix = u.get...
python
{ "resource": "" }
q235880
_set_aws_environment
train
def _set_aws_environment(task: Task = None): """Sets up AWS environment from NCLUSTER environment variables""" current_zone = os.environ.get('NCLUSTER_ZONE', '') current_region = os.environ.get('AWS_DEFAULT_REGION', '') def log(*args): if task: task.log(*args) else: util.log(*args) if cu...
python
{ "resource": "" }
q235881
Task.join
train
def join(self, ignore_errors=False): """Waits until last executed command completed.""" assert self._status_fn, "Asked to join a task which hasn't had any commands executed on it" check_interval = 0.2 status_fn = self._status_fn if not self.wait_for_file(status_fn, max_wait_sec=30): self.log(f...
python
{ "resource": "" }
q235882
Task._run_with_output_on_failure
train
def _run_with_output_on_failure(self, cmd, non_blocking=False, ignore_errors=False, max_wait_sec=365 * 24 * 3600, check_interval=0.2) -> str: """Experimental version of run propagates error messages to client. This...
python
{ "resource": "" }
q235883
Task.upload
train
def upload(self, local_fn: str, remote_fn: str = '', dont_overwrite: bool = False) -> None: """Uploads file to remote instance. If location not specified, dumps it into default directory. If remote location has files or directories with the same name, behavior is undefined.""" # support w...
python
{ "resource": "" }
q235884
_replace_lines
train
def _replace_lines(fn, startswith, new_line): """Replace lines starting with starts_with in fn with new_line.""" new_lines = [] for line in open(fn): if line.startswith(startswith): new_lines.append(new_line) else: new_lines.append(line) with open(fn, 'w') as f: f.write('\n'.join(new_lin...
python
{ "resource": "" }
q235885
now_micros
train
def now_micros(absolute=False) -> int: """Return current micros since epoch as integer.""" micros = int(time.time() * 1e6) if absolute: return micros return micros - EPOCH_MICROS
python
{ "resource": "" }
q235886
now_millis
train
def now_millis(absolute=False) -> int: """Return current millis since epoch as integer.""" millis = int(time.time() * 1e3) if absolute: return millis return millis - EPOCH_MICROS // 1000
python
{ "resource": "" }
q235887
install_pdb_handler
train
def install_pdb_handler(): """Make CTRL+\ break into gdb.""" import signal import pdb def handler(_signum, _frame): pdb.set_trace() signal.signal(signal.SIGQUIT, handler)
python
{ "resource": "" }
q235888
shell_add_echo
train
def shell_add_echo(script): """Goes over each line script, adds "echo cmd" in front of each cmd. ls a becomes echo * ls a ls a """ new_script = "" for cmd in script.split('\n'): cmd = cmd.strip() if not cmd: continue new_script += "echo \\* " + shlex.quote(cmd) + "\n" new_script...
python
{ "resource": "" }
q235889
random_id
train
def random_id(k=5): """Random id to use for AWS identifiers.""" # https://stackoverflow.com/questions/2257441/random-string-generation-with-upper-case-letters-and-digits-in-python return ''.join(random.choices(string.ascii_lowercase + string.digits, k=k))
python
{ "resource": "" }
q235890
alphanumeric_hash
train
def alphanumeric_hash(s: str, size=5): """Short alphanumeric string derived from hash of given string""" import hashlib import base64 hash_object = hashlib.md5(s.encode('ascii')) s = base64.b32encode(hash_object.digest()) result = s[:size].decode('ascii').lower() return result
python
{ "resource": "" }
q235891
is_bash_builtin
train
def is_bash_builtin(cmd): """Return true if command is invoking bash built-in """ # from compgen -b bash_builtins = ['alias', 'bg', 'bind', 'alias', 'bg', 'bind', 'break', 'builtin', 'caller', 'cd', 'command', 'compgen', 'complete', 'compopt', 'continue', 'declare', 'dirs',...
python
{ "resource": "" }
q235892
is_set
train
def is_set(name): """Helper method to check if given property is set""" val = os.environ.get(name, '0') assert val == '0' or val == '1', f"env var {name} has value {val}, expected 0 or 1" return val == '1'
python
{ "resource": "" }
q235893
assert_script_in_current_directory
train
def assert_script_in_current_directory(): """Assert fail if current directory is different from location of the script""" script = sys.argv[0] assert os.path.abspath(os.path.dirname(script)) == os.path.abspath( '.'), f"Change into directory of script {script} and run again."
python
{ "resource": "" }
q235894
load_fixtures
train
def load_fixtures(db, fixtures): """Loads the given fixtures into the database. """ conn = db.engine.connect() metadata = db.metadata for fixture in fixtures: if 'model' in fixture: module_name, class_name = fixture['model'].rsplit('.', 1) module = importlib.import_m...
python
{ "resource": "" }
q235895
MetaFixturesMixin.setup_handler
train
def setup_handler(setup_fixtures_fn, setup_fn): """Returns a function that adds fixtures handling to the setup method. Makes sure that fixtures are setup before calling the given setup method. """ def handler(obj): setup_fixtures_fn(obj) setup_fn(obj) ret...
python
{ "resource": "" }
q235896
MetaFixturesMixin.teardown_handler
train
def teardown_handler(teardown_fixtures_fn, teardown_fn): """Returns a function that adds fixtures handling to the teardown method. Calls the given teardown method first before calling the fixtures teardown. """ def handler(obj): teardown_fn(obj) teardown_fixtures...
python
{ "resource": "" }
q235897
MetaFixturesMixin.get_child_fn
train
def get_child_fn(attrs, names, bases): """Returns a function from the child class that matches one of the names. Searches the child class's set of methods (i.e., the attrs dict) for all the functions matching the given list of names. If more than one is found, an exception is raised, if...
python
{ "resource": "" }
q235898
print_msg
train
def print_msg(msg, header, file=sys.stdout): """Prints a boardered message to the screen""" DEFAULT_MSG_BLOCK_WIDTH = 60 # Calculate the length of the boarder on each side of the header and the # total length of the bottom boarder side_boarder_length = (DEFAULT_MSG_BLOCK_WIDTH - (len(header) + 2)) ...
python
{ "resource": "" }
q235899
can_persist_fixtures
train
def can_persist_fixtures(): """Returns True if it's possible to persist fixtures across tests. Flask-Fixtures uses the setUpClass and tearDownClass methods to persist fixtures across tests. These methods were added to unittest.TestCase in python 2.7. So, we can only persist fixtures when using python 2...
python
{ "resource": "" }