code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def set_pending_symbol(self, pending_symbol=None): """Sets the context's ``pending_symbol`` with the given unicode sequence and resets the context's ``value``. If the input is None, an empty :class:`CodePointArray` is used. """ if pending_symbol is None: pending_symbol = Cod...
Sets the context's ``pending_symbol`` with the given unicode sequence and resets the context's ``value``. If the input is None, an empty :class:`CodePointArray` is used.
Below is the the instruction that describes the task: ### Input: Sets the context's ``pending_symbol`` with the given unicode sequence and resets the context's ``value``. If the input is None, an empty :class:`CodePointArray` is used. ### Response: def set_pending_symbol(self, pending_symbol=None): ...
def norm(self, x): """Return the norm of ``x``. Parameters ---------- x : `LinearSpaceElement` Element whose norm to compute. Returns ------- norm : float Norm of ``x``. """ if x not in self: raise LinearSpaceT...
Return the norm of ``x``. Parameters ---------- x : `LinearSpaceElement` Element whose norm to compute. Returns ------- norm : float Norm of ``x``.
Below is the the instruction that describes the task: ### Input: Return the norm of ``x``. Parameters ---------- x : `LinearSpaceElement` Element whose norm to compute. Returns ------- norm : float Norm of ``x``. ### Response: def norm(self,...
def find(self, table_name, constraints=None, *, columns=None, order_by=None): """Returns the first record that matches the given criteria. :table_name: the name of the table to search on :constraints: is any construct that can be parsed by SqlWriter.parse_constraints. :columns: either a string or a lis...
Returns the first record that matches the given criteria. :table_name: the name of the table to search on :constraints: is any construct that can be parsed by SqlWriter.parse_constraints. :columns: either a string or a list of column names :order_by: the order by clause
Below is the the instruction that describes the task: ### Input: Returns the first record that matches the given criteria. :table_name: the name of the table to search on :constraints: is any construct that can be parsed by SqlWriter.parse_constraints. :columns: either a string or a list of column name...
def annotatethreads(self): """ Use prokka to annotate each strain """ # Move the files to subfolders and create objects self.runmetadata = createobject.ObjectCreation(self) # Fix headers self.headers() printtime('Performing prokka analyses', self.start) ...
Use prokka to annotate each strain
Below is the the instruction that describes the task: ### Input: Use prokka to annotate each strain ### Response: def annotatethreads(self): """ Use prokka to annotate each strain """ # Move the files to subfolders and create objects self.runmetadata = createobject.ObjectCre...
def trace_scan(loop_fn, initial_state, elems, trace_fn, parallel_iterations=10, name=None): """A simplified version of `tf.scan` that has configurable tracing. This function repeatedly calls `loop_fn(state, elem)`, where `state` is the `i...
A simplified version of `tf.scan` that has configurable tracing. This function repeatedly calls `loop_fn(state, elem)`, where `state` is the `initial_state` during the first iteration, and the return value of `loop_fn` for every iteration thereafter. `elem` is a slice of `elements` along the first dimension, a...
Below is the the instruction that describes the task: ### Input: A simplified version of `tf.scan` that has configurable tracing. This function repeatedly calls `loop_fn(state, elem)`, where `state` is the `initial_state` during the first iteration, and the return value of `loop_fn` for every iteration there...
def HTMLcolor(canvas, color): "returns Tk color in form '#rrggbb' or '#rgb'" if color: # r, g, b \in [0..2**16] r, g, b = ["%02x" % (c // 256) for c in canvas.winfo_rgb(color)] if (r[0] == r[1]) and (g[0] == g[1]) and (b[0] == b[1]): # shorter form #rgb return "#" + r[0] + g[0] + b[0] else: return ...
returns Tk color in form '#rrggbb' or '#rgb
Below is the the instruction that describes the task: ### Input: returns Tk color in form '#rrggbb' or '#rgb ### Response: def HTMLcolor(canvas, color): "returns Tk color in form '#rrggbb' or '#rgb'" if color: # r, g, b \in [0..2**16] r, g, b = ["%02x" % (c // 256) for c in canvas.winfo_rgb(color)] if (r...
def log(self): """ Return recent log entries as a string. """ logserv = self.system.request_service('LogStoreService') return logserv.lastlog(html=False)
Return recent log entries as a string.
Below is the the instruction that describes the task: ### Input: Return recent log entries as a string. ### Response: def log(self): """ Return recent log entries as a string. """ logserv = self.system.request_service('LogStoreService') return logserv.lastlog(html=False)
def update_server_filter_action(self, request, table=None): """Update the table server side filter action. It is done based on the current filter. The filter info may be stored in the session and this will restore it. """ if not table: table = self.get_table() ...
Update the table server side filter action. It is done based on the current filter. The filter info may be stored in the session and this will restore it.
Below is the the instruction that describes the task: ### Input: Update the table server side filter action. It is done based on the current filter. The filter info may be stored in the session and this will restore it. ### Response: def update_server_filter_action(self, request, table=None): ...
def edit_task(self, task_name, **kwargs): """ Change the name of a Task owned by this Job. This will affect the historical data available for this Task, e.g. past run logs will no longer be accessible. """ logger.debug('Job {0} editing task {1}'.format(self.name, task_name)) ...
Change the name of a Task owned by this Job. This will affect the historical data available for this Task, e.g. past run logs will no longer be accessible.
Below is the the instruction that describes the task: ### Input: Change the name of a Task owned by this Job. This will affect the historical data available for this Task, e.g. past run logs will no longer be accessible. ### Response: def edit_task(self, task_name, **kwargs): """ Change th...
def save_batches(server_context, assay_id, batches): # type: (ServerContext, int, List[Batch]) -> Union[List[Batch], None] """ Saves a modified batches. :param server_context: A LabKey server context. See utils.create_server_context. :param assay_id: The assay protocol id. :param batches: The Ba...
Saves a modified batches. :param server_context: A LabKey server context. See utils.create_server_context. :param assay_id: The assay protocol id. :param batches: The Batch(es) to save. :return:
Below is the the instruction that describes the task: ### Input: Saves a modified batches. :param server_context: A LabKey server context. See utils.create_server_context. :param assay_id: The assay protocol id. :param batches: The Batch(es) to save. :return: ### Response: def save_batches(server_c...
def reward_explore(self): """ Add an exploration reward """ if not 'explore' in self.mode: return mode = self.mode['explore'] if mode and mode['reward'] and self.__test_cond(mode): self.player.stats['reward'] += mode['reward'] self.play...
Add an exploration reward
Below is the the instruction that describes the task: ### Input: Add an exploration reward ### Response: def reward_explore(self): """ Add an exploration reward """ if not 'explore' in self.mode: return mode = self.mode['explore'] if mode and mode['reward...
def _history_move(self, p_step): """ Changes current value of the command-line to the value obtained from history_tmp list with index calculated by addition of p_step to the current position in the command history (history_pos attribute). Also saves value of the command-line (be...
Changes current value of the command-line to the value obtained from history_tmp list with index calculated by addition of p_step to the current position in the command history (history_pos attribute). Also saves value of the command-line (before changing it) to history_tmp for potentia...
Below is the the instruction that describes the task: ### Input: Changes current value of the command-line to the value obtained from history_tmp list with index calculated by addition of p_step to the current position in the command history (history_pos attribute). Also saves value of the ...
def time_vs_parameter(self, parameter, bp, merge=False, merge_method='mean', masked=False): """To get the parameter of either a specfic base-pair/step or a DNA segment as a function of time. parameters ---------- parameter : str Name of a base-pair or base-step or helical pa...
To get the parameter of either a specfic base-pair/step or a DNA segment as a function of time. parameters ---------- parameter : str Name of a base-pair or base-step or helical parameter. For details about accepted keywords, see ``parameter`` in the method :...
Below is the the instruction that describes the task: ### Input: To get the parameter of either a specfic base-pair/step or a DNA segment as a function of time. parameters ---------- parameter : str Name of a base-pair or base-step or helical parameter. For details a...
def keys(self, pattern, *, encoding=_NOTSET): """Returns all keys matching pattern.""" return self.execute(b'KEYS', pattern, encoding=encoding)
Returns all keys matching pattern.
Below is the the instruction that describes the task: ### Input: Returns all keys matching pattern. ### Response: def keys(self, pattern, *, encoding=_NOTSET): """Returns all keys matching pattern.""" return self.execute(b'KEYS', pattern, encoding=encoding)
def download_channel_image(self, channel_name, plate_name, well_name, well_pos_y, well_pos_x, cycle_index=0, tpoint=0, zplane=0, correct=True, align =False): '''Downloads a channel image. Parameters ---------- channel_name: str name of the channel ...
Downloads a channel image. Parameters ---------- channel_name: str name of the channel plate_name: str name of the plate well_name: str name of the well well_pos_x: int zero-based x cooridinate of the acquisition site withi...
Below is the the instruction that describes the task: ### Input: Downloads a channel image. Parameters ---------- channel_name: str name of the channel plate_name: str name of the plate well_name: str name of the well well_pos_x: i...
def pass_obj(f): """Similar to :func:`pass_context`, but only pass the object on the context onwards (:attr:`Context.obj`). This is useful if that object represents the state of a nested system. """ def new_func(*args, **kwargs): return f(get_current_context().obj, *args, **kwargs) retu...
Similar to :func:`pass_context`, but only pass the object on the context onwards (:attr:`Context.obj`). This is useful if that object represents the state of a nested system.
Below is the the instruction that describes the task: ### Input: Similar to :func:`pass_context`, but only pass the object on the context onwards (:attr:`Context.obj`). This is useful if that object represents the state of a nested system. ### Response: def pass_obj(f): """Similar to :func:`pass_conte...
def add(self, origin, rel, target, attrs=None, rid=None): ''' Add one relationship to the extent origin - origin of the relationship (similar to an RDF subject) rel - type IRI of the relationship (similar to an RDF predicate) target - target of the relationship (similar to an RD...
Add one relationship to the extent origin - origin of the relationship (similar to an RDF subject) rel - type IRI of the relationship (similar to an RDF predicate) target - target of the relationship (similar to an RDF object), a boolean, floating point or unicode object attrs - optiona...
Below is the the instruction that describes the task: ### Input: Add one relationship to the extent origin - origin of the relationship (similar to an RDF subject) rel - type IRI of the relationship (similar to an RDF predicate) target - target of the relationship (similar to an RDF object)...
def write_STELLA_model(self,name): """ Write an initial model in a format that may easily be read by the radiation hydrodynamics code STELLA. Parameters ---------- name : string an identifier for the model. There are two output files from this met...
Write an initial model in a format that may easily be read by the radiation hydrodynamics code STELLA. Parameters ---------- name : string an identifier for the model. There are two output files from this method, which will be <name>.hyd and <name>.abn, which ...
Below is the the instruction that describes the task: ### Input: Write an initial model in a format that may easily be read by the radiation hydrodynamics code STELLA. Parameters ---------- name : string an identifier for the model. There are two output files from ...
def interpolate_intervals(intervals, labels, time_points, fill_value=None): """Assign labels to a set of points in time given a set of intervals. Time points that do not lie within an interval are mapped to `fill_value`. Parameters ---------- intervals : np.ndarray, shape=(n, 2) An array o...
Assign labels to a set of points in time given a set of intervals. Time points that do not lie within an interval are mapped to `fill_value`. Parameters ---------- intervals : np.ndarray, shape=(n, 2) An array of time intervals, as returned by :func:`mir_eval.io.load_intervals()`. ...
Below is the the instruction that describes the task: ### Input: Assign labels to a set of points in time given a set of intervals. Time points that do not lie within an interval are mapped to `fill_value`. Parameters ---------- intervals : np.ndarray, shape=(n, 2) An array of time interva...
def is_decimal(self): """Determine if a data record is of the type float.""" dt = DATA_TYPES['decimal'] if type(self.data) in dt['type']: self.type = 'DECIMAL' num_split = str(self.data).split('.', 1) self.len = len(num_split[0]) self.len_decimal =...
Determine if a data record is of the type float.
Below is the the instruction that describes the task: ### Input: Determine if a data record is of the type float. ### Response: def is_decimal(self): """Determine if a data record is of the type float.""" dt = DATA_TYPES['decimal'] if type(self.data) in dt['type']: self.type = '...
def get(self, url): """ Get the response for the given enclosure URL """ self._query() return Enclosure(self._resp.get(url), url)
Get the response for the given enclosure URL
Below is the the instruction that describes the task: ### Input: Get the response for the given enclosure URL ### Response: def get(self, url): """ Get the response for the given enclosure URL """ self._query() return Enclosure(self._resp.get(url), url)
def _prepare_disks(self, disks_name): """format disks to xfs and mount it""" fstab = '/etc/fstab' for disk in tqdm(disks_name.split(',')): sudo('umount /dev/{0}'.format(disk), warn_only=True) if sudo('mkfs.xfs -f /dev/{0}'.format(disk), warn_only=True).failed: ...
format disks to xfs and mount it
Below is the the instruction that describes the task: ### Input: format disks to xfs and mount it ### Response: def _prepare_disks(self, disks_name): """format disks to xfs and mount it""" fstab = '/etc/fstab' for disk in tqdm(disks_name.split(',')): sudo('umount /dev/{0}'.f...
def device_add(self, mountpoint, *device): """ Add one or more devices to btrfs filesystem mounted under `mountpoint` :param mountpoint: mount point of the btrfs system :param devices: one ore more devices to add :return: """ if len(device) == 0: retu...
Add one or more devices to btrfs filesystem mounted under `mountpoint` :param mountpoint: mount point of the btrfs system :param devices: one ore more devices to add :return:
Below is the the instruction that describes the task: ### Input: Add one or more devices to btrfs filesystem mounted under `mountpoint` :param mountpoint: mount point of the btrfs system :param devices: one ore more devices to add :return: ### Response: def device_add(self, mountpoint, *de...
def float_pack(x, size): """Convert a Python float x into a 64-bit unsigned integer with the same byte representation.""" if size == 8: MIN_EXP = -1021 # = sys.float_info.min_exp MAX_EXP = 1024 # = sys.float_info.max_exp MANT_DIG = 53 # = sys.float_info.mant_dig BITS = 64 elif size == 4: ...
Convert a Python float x into a 64-bit unsigned integer with the same byte representation.
Below is the the instruction that describes the task: ### Input: Convert a Python float x into a 64-bit unsigned integer with the same byte representation. ### Response: def float_pack(x, size): """Convert a Python float x into a 64-bit unsigned integer with the same byte representation.""" if size == 8: ...
def bulkSave(self, docs, onDuplicate="error", **params) : """Parameter docs must be either an iterrable of documents or dictionnaries. This function will return the number of documents, created and updated, and will raise an UpdateError exception if there's at least one error. params are any par...
Parameter docs must be either an iterrable of documents or dictionnaries. This function will return the number of documents, created and updated, and will raise an UpdateError exception if there's at least one error. params are any parameters from arango's documentation
Below is the the instruction that describes the task: ### Input: Parameter docs must be either an iterrable of documents or dictionnaries. This function will return the number of documents, created and updated, and will raise an UpdateError exception if there's at least one error. params are any par...
def _find_identity_pool_ids(name, pool_id, conn): ''' Given identity pool name (or optionally a pool_id and name will be ignored), find and return list of matching identity pool id's. ''' ids = [] if pool_id is None: for pools in __utils__['boto3.paged_call'](conn.list_identity_pools, ...
Given identity pool name (or optionally a pool_id and name will be ignored), find and return list of matching identity pool id's.
Below is the the instruction that describes the task: ### Input: Given identity pool name (or optionally a pool_id and name will be ignored), find and return list of matching identity pool id's. ### Response: def _find_identity_pool_ids(name, pool_id, conn): ''' Given identity pool name (or optionally ...
def _internal_convert(inp): """ Converts file in IDX format provided by file-like input into numpy.ndarray and returns it. """ ''' Converts file in IDX format provided by file-like input into numpy.ndarray and returns it. ''' # Read the "magic number" - 4 bytes. try: mn ...
Converts file in IDX format provided by file-like input into numpy.ndarray and returns it.
Below is the the instruction that describes the task: ### Input: Converts file in IDX format provided by file-like input into numpy.ndarray and returns it. ### Response: def _internal_convert(inp): """ Converts file in IDX format provided by file-like input into numpy.ndarray and returns it. ""...
def enable(soft_fail=False): """ Enable ufw :param soft_fail: If set to True silently disables IPv6 support in ufw, otherwise a UFWIPv6Error exception is raised when IP6 support is broken. :returns: True if ufw is successfully enabled """ if is_enable...
Enable ufw :param soft_fail: If set to True silently disables IPv6 support in ufw, otherwise a UFWIPv6Error exception is raised when IP6 support is broken. :returns: True if ufw is successfully enabled
Below is the the instruction that describes the task: ### Input: Enable ufw :param soft_fail: If set to True silently disables IPv6 support in ufw, otherwise a UFWIPv6Error exception is raised when IP6 support is broken. :returns: True if ufw is successfully enab...
def create(model_config, batch_size, normalize=True, num_workers=0, augmentations=None): """ Create a MNIST dataset, normalized """ path = model_config.data_dir('mnist') train_dataset = datasets.MNIST(path, train=True, download=True) test_dataset = datasets.MNIST(path, train=False, download=True) ...
Create a MNIST dataset, normalized
Below is the the instruction that describes the task: ### Input: Create a MNIST dataset, normalized ### Response: def create(model_config, batch_size, normalize=True, num_workers=0, augmentations=None): """ Create a MNIST dataset, normalized """ path = model_config.data_dir('mnist') train_dataset = da...
def stereo2mono(x): ''' This function converts the input signal (stored in a numpy array) to MONO (if it is STEREO) ''' if isinstance(x, int): return -1 if x.ndim==1: return x elif x.ndim==2: if x.shape[1]==1: return x.flatten() else: i...
This function converts the input signal (stored in a numpy array) to MONO (if it is STEREO)
Below is the the instruction that describes the task: ### Input: This function converts the input signal (stored in a numpy array) to MONO (if it is STEREO) ### Response: def stereo2mono(x): ''' This function converts the input signal (stored in a numpy array) to MONO (if it is STEREO) ''' ...
def call_ext_prog(self, prog, timeout=300, stderr=True, chroot=True, runat=None): """Execute a command independantly of the output gathering part of sosreport. """ return self.get_command_output(prog, timeout=timeout, stderr=stderr, ...
Execute a command independantly of the output gathering part of sosreport.
Below is the the instruction that describes the task: ### Input: Execute a command independantly of the output gathering part of sosreport. ### Response: def call_ext_prog(self, prog, timeout=300, stderr=True, chroot=True, runat=None): """Execute a command independantly of the...
def mark_confirmation_as_clear(self, confirmation_id): """ Mark confirmation as clear :param confirmation_id: the confirmation id :return Response """ return self._create_put_request( resource=CONFIRMATIONS, billomat_id=confirmation_id, ...
Mark confirmation as clear :param confirmation_id: the confirmation id :return Response
Below is the the instruction that describes the task: ### Input: Mark confirmation as clear :param confirmation_id: the confirmation id :return Response ### Response: def mark_confirmation_as_clear(self, confirmation_id): """ Mark confirmation as clear :param confirmation_...
def report(self, name, owner=None, **kwargs): """ Create the Report TI object. Args: owner: name: **kwargs: Return: """ return Report(self.tcex, name, owner=owner, **kwargs)
Create the Report TI object. Args: owner: name: **kwargs: Return:
Below is the the instruction that describes the task: ### Input: Create the Report TI object. Args: owner: name: **kwargs: Return: ### Response: def report(self, name, owner=None, **kwargs): """ Create the Report TI object. Args: ...
def total_score(paired_dats, p=2, test=StatTests.ks): '''Calculates the p-norm of the distances that have been calculated from the statistical test that has been applied on all the paired datasets. Parameters: paired_dats: a list of tuples or where each tuple contains the p...
Calculates the p-norm of the distances that have been calculated from the statistical test that has been applied on all the paired datasets. Parameters: paired_dats: a list of tuples or where each tuple contains the paired data lists from two datasets Options: p : ...
Below is the the instruction that describes the task: ### Input: Calculates the p-norm of the distances that have been calculated from the statistical test that has been applied on all the paired datasets. Parameters: paired_dats: a list of tuples or where each tuple contai...
def update_aliases(self, body, params=None): """ Update specified aliases. `<http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-aliases.html>`_ :arg body: The definition of `actions` to perform :arg master_timeout: Specify timeout for connection to master ...
Update specified aliases. `<http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-aliases.html>`_ :arg body: The definition of `actions` to perform :arg master_timeout: Specify timeout for connection to master :arg request_timeout: Request timeout
Below is the the instruction that describes the task: ### Input: Update specified aliases. `<http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-aliases.html>`_ :arg body: The definition of `actions` to perform :arg master_timeout: Specify timeout for connection to master...
def val_to_mrc(code, val): """ Convert one single `val` to MRC. This function may be used for control fields in MARC records. Args:, code (str): Code of the field. val (str): Value of the field. Returns: str: Correctly padded MRC line with field. """ code = str(cod...
Convert one single `val` to MRC. This function may be used for control fields in MARC records. Args:, code (str): Code of the field. val (str): Value of the field. Returns: str: Correctly padded MRC line with field.
Below is the the instruction that describes the task: ### Input: Convert one single `val` to MRC. This function may be used for control fields in MARC records. Args:, code (str): Code of the field. val (str): Value of the field. Returns: str: Correctly padded MRC line with fie...
def custom_model(self, func): """ Run custom model provided by user. To Do, 1. Define custom function's parameters, its data types, and return types Parameters ---------- func : function Custom function Returns ------- dict ...
Run custom model provided by user. To Do, 1. Define custom function's parameters, its data types, and return types Parameters ---------- func : function Custom function Returns ------- dict Custom function's metrics
Below is the the instruction that describes the task: ### Input: Run custom model provided by user. To Do, 1. Define custom function's parameters, its data types, and return types Parameters ---------- func : function Custom function Returns ...
def ensure_crossplat_path(path, winroot='C:'): r""" ensure_crossplat_path Args: path (str): Returns: str: crossplat_path Example(DOCTEST): >>> # ENABLE_DOCTEST >>> from utool.util_path import * # NOQA >>> path = r'C:\somedir' >>> cplat_path = ensur...
r""" ensure_crossplat_path Args: path (str): Returns: str: crossplat_path Example(DOCTEST): >>> # ENABLE_DOCTEST >>> from utool.util_path import * # NOQA >>> path = r'C:\somedir' >>> cplat_path = ensure_crossplat_path(path) >>> result = cplat_p...
Below is the the instruction that describes the task: ### Input: r""" ensure_crossplat_path Args: path (str): Returns: str: crossplat_path Example(DOCTEST): >>> # ENABLE_DOCTEST >>> from utool.util_path import * # NOQA >>> path = r'C:\somedir' >>> ...
def spec(self) -> list: """Returns prefix unary operators list. Sets only one regex for all items in the dict.""" spec = [item for op, pat in self.ops.items() for item in [('{' + op, {'pat': pat, 'postf': self.postf, 'regex': None}), (...
Returns prefix unary operators list. Sets only one regex for all items in the dict.
Below is the the instruction that describes the task: ### Input: Returns prefix unary operators list. Sets only one regex for all items in the dict. ### Response: def spec(self) -> list: """Returns prefix unary operators list. Sets only one regex for all items in the dict.""" spec =...
def map_forecast_estimate(self): """ get the prior and posterior forecast (prediction) expectations. Returns ------- pandas.DataFrame : pandas.DataFrame dataframe with prior and posterior forecast expected values """ assert self.forecasts is not None ...
get the prior and posterior forecast (prediction) expectations. Returns ------- pandas.DataFrame : pandas.DataFrame dataframe with prior and posterior forecast expected values
Below is the the instruction that describes the task: ### Input: get the prior and posterior forecast (prediction) expectations. Returns ------- pandas.DataFrame : pandas.DataFrame dataframe with prior and posterior forecast expected values ### Response: def map_forecast_estima...
def get(self,dimlist): ''' get dimensions :parameter dimlist: list of dimensions ''' out=() for i,d in enumerate(dimlist): out+=(super(dimStr, self).get(d,None),) return out
get dimensions :parameter dimlist: list of dimensions
Below is the the instruction that describes the task: ### Input: get dimensions :parameter dimlist: list of dimensions ### Response: def get(self,dimlist): ''' get dimensions :parameter dimlist: list of dimensions ''' out=() for i,d in enumerate(dimlis...
def set(self, uri, content, **meta): """ Dispatches private update/create handlers """ try: node = self._update(uri, content, **meta) created = False except NodeDoesNotExist: node = self._create(uri, content, **meta) created = True ...
Dispatches private update/create handlers
Below is the the instruction that describes the task: ### Input: Dispatches private update/create handlers ### Response: def set(self, uri, content, **meta): """ Dispatches private update/create handlers """ try: node = self._update(uri, content, **meta) crea...
def depth(sequence, func=max, _depth=0): """ Find the nesting depth of a nested sequence """ if isinstance(sequence, dict): sequence = list(sequence.values()) depth_list = [depth(item, func=func, _depth=_depth + 1) for item in sequence if (isinstance(item, dict) or util_typ...
Find the nesting depth of a nested sequence
Below is the the instruction that describes the task: ### Input: Find the nesting depth of a nested sequence ### Response: def depth(sequence, func=max, _depth=0): """ Find the nesting depth of a nested sequence """ if isinstance(sequence, dict): sequence = list(sequence.values()) depth...
def construct(cls: Type['Model'], values: 'DictAny', fields_set: 'SetStr') -> 'Model': """ Creates a new model and set __values__ without any validation, thus values should already be trusted. Chances are you don't want to use this method directly. """ m = cls.__new__(cls) ...
Creates a new model and set __values__ without any validation, thus values should already be trusted. Chances are you don't want to use this method directly.
Below is the the instruction that describes the task: ### Input: Creates a new model and set __values__ without any validation, thus values should already be trusted. Chances are you don't want to use this method directly. ### Response: def construct(cls: Type['Model'], values: 'DictAny', fields_set: 'SetS...
def set_stage_for_epoch(self, epoch_start, name, attr='stage', save=True): """Change the stage for one specific epoch. Parameters ---------- epoch_start : int start time of the epoch, in seconds name : str description of the stage or qualifier. at...
Change the stage for one specific epoch. Parameters ---------- epoch_start : int start time of the epoch, in seconds name : str description of the stage or qualifier. attr : str, optional either 'stage' or 'quality' save : bool ...
Below is the the instruction that describes the task: ### Input: Change the stage for one specific epoch. Parameters ---------- epoch_start : int start time of the epoch, in seconds name : str description of the stage or qualifier. attr : str, optiona...
def no_route_found(self, request): """ Default callback for route not found :param request HttpRequest :rtype: Response """ response_obj = OrderedDict() response_obj["status"] = False response_obj["exceptions"] = { "message": "No route found fo...
Default callback for route not found :param request HttpRequest :rtype: Response
Below is the the instruction that describes the task: ### Input: Default callback for route not found :param request HttpRequest :rtype: Response ### Response: def no_route_found(self, request): """ Default callback for route not found :param request HttpRequest :rty...
def create_or_update_events_directly_for_course_timetable(self, course_id, course_section_id=None, events=None, events_code=None, events_end_at=None, events_location_name=None, events_start_at=None): """ Create or update events directly for a course timetable. Creates and updates "timetable...
Create or update events directly for a course timetable. Creates and updates "timetable" events for a course or course section. Similar to {api:CalendarEventsApiController#set_course_timetable setting a course timetable}, but instead of generating a list of events based on a timetable sched...
Below is the the instruction that describes the task: ### Input: Create or update events directly for a course timetable. Creates and updates "timetable" events for a course or course section. Similar to {api:CalendarEventsApiController#set_course_timetable setting a course timetable}, ...
def footprints_from_place(place, footprint_type='building', retain_invalid=False): """ Get footprints within the boundaries of some place. The query must be geocodable and OSM must have polygon boundaries for the geocode result. If OSM does not have a polygon for this place, you can instead get its...
Get footprints within the boundaries of some place. The query must be geocodable and OSM must have polygon boundaries for the geocode result. If OSM does not have a polygon for this place, you can instead get its footprints using the footprints_from_address function, which geocodes the place name to a ...
Below is the the instruction that describes the task: ### Input: Get footprints within the boundaries of some place. The query must be geocodable and OSM must have polygon boundaries for the geocode result. If OSM does not have a polygon for this place, you can instead get its footprints using the foot...
def minor_min_width(G): """Computes a lower bound for the treewidth of graph G. Parameters ---------- G : NetworkX graph The graph on which to compute a lower bound on the treewidth. Returns ------- lb : int A lower bound on the treewidth. Examples -------- Thi...
Computes a lower bound for the treewidth of graph G. Parameters ---------- G : NetworkX graph The graph on which to compute a lower bound on the treewidth. Returns ------- lb : int A lower bound on the treewidth. Examples -------- This example computes a lower boun...
Below is the the instruction that describes the task: ### Input: Computes a lower bound for the treewidth of graph G. Parameters ---------- G : NetworkX graph The graph on which to compute a lower bound on the treewidth. Returns ------- lb : int A lower bound on the treewid...
def coordinates(self, x, y): '''return coordinates of a pixel in the map''' state = self.state return state.mt.coord_from_area(x, y, state.lat, state.lon, state.width, state.ground_width)
return coordinates of a pixel in the map
Below is the the instruction that describes the task: ### Input: return coordinates of a pixel in the map ### Response: def coordinates(self, x, y): '''return coordinates of a pixel in the map''' state = self.state return state.mt.coord_from_area(x, y, state.lat, state.lon, state.width, sta...
def cached(size): """A caching decorator based on parameter objects""" def decorator(func): cached_func = _Cached(func, size) return lambda *a, **kw: cached_func(*a, **kw) return decorator
A caching decorator based on parameter objects
Below is the the instruction that describes the task: ### Input: A caching decorator based on parameter objects ### Response: def cached(size): """A caching decorator based on parameter objects""" def decorator(func): cached_func = _Cached(func, size) return lambda *a, **kw: cached_func(*a,...
def remove(self, document_id, namespace, timestamp): """Removes documents from Solr The input is a python dictionary that represents a mongo document. """ self.solr.delete(id=u(document_id), commit=(self.auto_commit_interval == 0))
Removes documents from Solr The input is a python dictionary that represents a mongo document.
Below is the the instruction that describes the task: ### Input: Removes documents from Solr The input is a python dictionary that represents a mongo document. ### Response: def remove(self, document_id, namespace, timestamp): """Removes documents from Solr The input is a python dictionar...
def _finalize_ticks(self, axis, dimensions, xticks, yticks, zticks): """ Finalizes the ticks on the axes based on the supplied ticks and Elements. Sets the axes position as well as tick positions, labels and fontsize. """ ndims = len(dimensions) if dimensions else 0 ...
Finalizes the ticks on the axes based on the supplied ticks and Elements. Sets the axes position as well as tick positions, labels and fontsize.
Below is the the instruction that describes the task: ### Input: Finalizes the ticks on the axes based on the supplied ticks and Elements. Sets the axes position as well as tick positions, labels and fontsize. ### Response: def _finalize_ticks(self, axis, dimensions, xticks, yticks, zticks): ...
def p_UnionType(p): """UnionType : "(" UnionMemberType or UnionMemberType UnionMemberTypes ")" """ t = [p[2]] + [p[4]] + p[5] p[0] = model.UnionType(t=t)
UnionType : "(" UnionMemberType or UnionMemberType UnionMemberTypes ")"
Below is the the instruction that describes the task: ### Input: UnionType : "(" UnionMemberType or UnionMemberType UnionMemberTypes ")" ### Response: def p_UnionType(p): """UnionType : "(" UnionMemberType or UnionMemberType UnionMemberTypes ")" """ t = [p[2]] + [p[4]] + p[5] p[0] = model.UnionType(t=t)
def get_instance(self, payload): """ Build an instance of InstalledAddOnExtensionInstance :param dict payload: Payload response from the API :returns: twilio.rest.preview.marketplace.installed_add_on.installed_add_on_extension.InstalledAddOnExtensionInstance :rtype: twilio.rest...
Build an instance of InstalledAddOnExtensionInstance :param dict payload: Payload response from the API :returns: twilio.rest.preview.marketplace.installed_add_on.installed_add_on_extension.InstalledAddOnExtensionInstance :rtype: twilio.rest.preview.marketplace.installed_add_on.installed_add_o...
Below is the the instruction that describes the task: ### Input: Build an instance of InstalledAddOnExtensionInstance :param dict payload: Payload response from the API :returns: twilio.rest.preview.marketplace.installed_add_on.installed_add_on_extension.InstalledAddOnExtensionInstance :rt...
def getattr(self, name, default: Any = _missing): """ Convenience method equivalent to ``deep_getattr(mcs_args.clsdict, mcs_args.bases, 'attr_name'[, default])`` """ return deep_getattr(self.clsdict, self.bases, name, default)
Convenience method equivalent to ``deep_getattr(mcs_args.clsdict, mcs_args.bases, 'attr_name'[, default])``
Below is the the instruction that describes the task: ### Input: Convenience method equivalent to ``deep_getattr(mcs_args.clsdict, mcs_args.bases, 'attr_name'[, default])`` ### Response: def getattr(self, name, default: Any = _missing): """ Convenience method equivalent to ``deep_ge...
def iterkeys(self, key_type=None, return_all_keys=False): """ Returns an iterator over the dictionary's keys. @param key_type if specified, iterator for a dictionary of this type will be used. Otherwise (if not specified) tuples containing all (multiple) keys ...
Returns an iterator over the dictionary's keys. @param key_type if specified, iterator for a dictionary of this type will be used. Otherwise (if not specified) tuples containing all (multiple) keys for this dictionary will be generated. @param return_al...
Below is the the instruction that describes the task: ### Input: Returns an iterator over the dictionary's keys. @param key_type if specified, iterator for a dictionary of this type will be used. Otherwise (if not specified) tuples containing all (multiple) keys ...
def _extract_from_url(self, url): """Try to extract from the article URL - simple but might work as a fallback""" # Regex by Newspaper3k - https://github.com/codelucas/newspaper/blob/master/newspaper/urls.py m = re.search(re_pub_date, url) if m: return self.parse_date_str(m...
Try to extract from the article URL - simple but might work as a fallback
Below is the the instruction that describes the task: ### Input: Try to extract from the article URL - simple but might work as a fallback ### Response: def _extract_from_url(self, url): """Try to extract from the article URL - simple but might work as a fallback""" # Regex by Newspaper3k - https...
def Iaax(mt, x, *args): """ (Iä)x : Returns the present value of annuity-certain at the beginning of the first year and increasing linerly. Arithmetically increasing annuity-anticipatory """ return Sx(mt, x) / Dx(mt, x)
(Iä)x : Returns the present value of annuity-certain at the beginning of the first year and increasing linerly. Arithmetically increasing annuity-anticipatory
Below is the the instruction that describes the task: ### Input: (Iä)x : Returns the present value of annuity-certain at the beginning of the first year and increasing linerly. Arithmetically increasing annuity-anticipatory ### Response: def Iaax(mt, x, *args): """ (Iä)x : Returns the present value of ann...
def flow_pipe(Diam, HeadLoss, Length, Nu, PipeRough, KMinor): """Return the the flow in a straight pipe. This function works for both major and minor losses and works whether the flow is laminar or turbulent. """ #Inputs do not need to be checked here because they are checked by #functions this...
Return the the flow in a straight pipe. This function works for both major and minor losses and works whether the flow is laminar or turbulent.
Below is the the instruction that describes the task: ### Input: Return the the flow in a straight pipe. This function works for both major and minor losses and works whether the flow is laminar or turbulent. ### Response: def flow_pipe(Diam, HeadLoss, Length, Nu, PipeRough, KMinor): """Return the the...
def get_distutils_option(option, commands): """ Returns the value of the given distutils option. Parameters ---------- option : str The name of the option commands : list of str The list of commands on which this option is available Returns ------- val : str or None ...
Returns the value of the given distutils option. Parameters ---------- option : str The name of the option commands : list of str The list of commands on which this option is available Returns ------- val : str or None the value of the given distutils option. If th...
Below is the the instruction that describes the task: ### Input: Returns the value of the given distutils option. Parameters ---------- option : str The name of the option commands : list of str The list of commands on which this option is available Returns ------- val...
def to_unicode(value): """Converts a string argument to a unicode string. If the argument is already a unicode string or None, it is returned unchanged. Otherwise it must be a byte string and is decoded as utf8. """ if isinstance(value, _TO_UNICODE_TYPES): return value assert isinstanc...
Converts a string argument to a unicode string. If the argument is already a unicode string or None, it is returned unchanged. Otherwise it must be a byte string and is decoded as utf8.
Below is the the instruction that describes the task: ### Input: Converts a string argument to a unicode string. If the argument is already a unicode string or None, it is returned unchanged. Otherwise it must be a byte string and is decoded as utf8. ### Response: def to_unicode(value): """Converts a...
def MaxPooling( inputs, pool_size, strides=None, padding='valid', data_format='channels_last'): """ Same as `tf.layers.MaxPooling2D`. Default strides is equal to pool_size. """ if strides is None: strides = pool_size layer = tf.layers.MaxPooling2D(pool...
Same as `tf.layers.MaxPooling2D`. Default strides is equal to pool_size.
Below is the the instruction that describes the task: ### Input: Same as `tf.layers.MaxPooling2D`. Default strides is equal to pool_size. ### Response: def MaxPooling( inputs, pool_size, strides=None, padding='valid', data_format='channels_last'): """ Same as `tf.lay...
def get_pings(sc, app=None, build_id=None, channel=None, doc_type='saved_session', fraction=1.0, schema=None, source_name='telemetry', source_version='4', submission_date=None, version=None): """ Returns a RDD of Telemetry submissions for a given filtering criteria. :param sc: an in...
Returns a RDD of Telemetry submissions for a given filtering criteria. :param sc: an instance of SparkContext :param app: an application name, e.g.: "Firefox" :param channel: a channel name, e.g.: "nightly" :param version: the application version, e.g.: "40.0a1" :param build_id: a build_id or a ran...
Below is the the instruction that describes the task: ### Input: Returns a RDD of Telemetry submissions for a given filtering criteria. :param sc: an instance of SparkContext :param app: an application name, e.g.: "Firefox" :param channel: a channel name, e.g.: "nightly" :param version: the applica...
def type(self): """Returns 'number', 'string', 'date' or 'unknown' based on the type of the value""" if isinstance(self.value, numbers.Number): return "number" if isinstance(self.value, basestring): return "string" return "unknown"
Returns 'number', 'string', 'date' or 'unknown' based on the type of the value
Below is the the instruction that describes the task: ### Input: Returns 'number', 'string', 'date' or 'unknown' based on the type of the value ### Response: def type(self): """Returns 'number', 'string', 'date' or 'unknown' based on the type of the value""" if isinstance(self.value, numbers.Number...
def individual_weights(self): """Read individual weights from the load cells in grams. Returns ------- weight : float The sensor weight in grams. """ weights = self._raw_weights() if weights.shape[1] == 0: return np.zeros(weights.shape[0])...
Read individual weights from the load cells in grams. Returns ------- weight : float The sensor weight in grams.
Below is the the instruction that describes the task: ### Input: Read individual weights from the load cells in grams. Returns ------- weight : float The sensor weight in grams. ### Response: def individual_weights(self): """Read individual weights from the load cells i...
def get_image(self, image): """ Generates a tuple of the full image name and tag, that should be used when creating a new container. This implementation applies the following rules: * If the image name starts with ``/``, the following image name is returned. * If ``/`` is found...
Generates a tuple of the full image name and tag, that should be used when creating a new container. This implementation applies the following rules: * If the image name starts with ``/``, the following image name is returned. * If ``/`` is found anywhere else in the image name, it is assumed ...
Below is the the instruction that describes the task: ### Input: Generates a tuple of the full image name and tag, that should be used when creating a new container. This implementation applies the following rules: * If the image name starts with ``/``, the following image name is returned. ...
def get_agents(): """Provides a list of hostnames / IPs of all agents in the cluster""" agent_list = [] agents = __get_all_agents() for agent in agents: agent_list.append(agent["hostname"]) return agent_list
Provides a list of hostnames / IPs of all agents in the cluster
Below is the the instruction that describes the task: ### Input: Provides a list of hostnames / IPs of all agents in the cluster ### Response: def get_agents(): """Provides a list of hostnames / IPs of all agents in the cluster""" agent_list = [] agents = __get_all_agents() for agent in agents: ...
def save_token(self): """ Saves the token dict in the specified file :return bool: Success / Failure """ if self.token is None: raise ValueError('You have to set the "token" first.') try: if not self.token_path.parent.exists(): sel...
Saves the token dict in the specified file :return bool: Success / Failure
Below is the the instruction that describes the task: ### Input: Saves the token dict in the specified file :return bool: Success / Failure ### Response: def save_token(self): """ Saves the token dict in the specified file :return bool: Success / Failure """ if self....
def run(**kwargs): """ This function was necessary to separate from main() to accommodate for server startup path on system 3.0, which is server.main. In the case where the api is on system 3.0, server.main will redirect to this function with an additional argument of 'patch_old_init'. kwargs are he...
This function was necessary to separate from main() to accommodate for server startup path on system 3.0, which is server.main. In the case where the api is on system 3.0, server.main will redirect to this function with an additional argument of 'patch_old_init'. kwargs are hence used to allow the use o...
Below is the the instruction that describes the task: ### Input: This function was necessary to separate from main() to accommodate for server startup path on system 3.0, which is server.main. In the case where the api is on system 3.0, server.main will redirect to this function with an additional argum...
def get_conf(self): ''' Combine the CherryPy configuration with the rest_cherrypy config values pulled from the master config and return the CherryPy configuration ''' conf = { 'global': { 'server.socket_host': self.apiopts.get('host', '0.0.0.0'), ...
Combine the CherryPy configuration with the rest_cherrypy config values pulled from the master config and return the CherryPy configuration
Below is the the instruction that describes the task: ### Input: Combine the CherryPy configuration with the rest_cherrypy config values pulled from the master config and return the CherryPy configuration ### Response: def get_conf(self): ''' Combine the CherryPy configuration with the rest...
def le(self, event_property, value): """A less-than-or-equal-to filter chain. >>> request_time = EventExpression('request', 'elapsed_ms') >>> filtered = request_time.le('elapsed_ms', 500) >>> print(filtered) request(elapsed_ms).le(elapsed_ms, 500) """ c = self.co...
A less-than-or-equal-to filter chain. >>> request_time = EventExpression('request', 'elapsed_ms') >>> filtered = request_time.le('elapsed_ms', 500) >>> print(filtered) request(elapsed_ms).le(elapsed_ms, 500)
Below is the the instruction that describes the task: ### Input: A less-than-or-equal-to filter chain. >>> request_time = EventExpression('request', 'elapsed_ms') >>> filtered = request_time.le('elapsed_ms', 500) >>> print(filtered) request(elapsed_ms).le(elapsed_ms, 500) ### Respon...
def discharge_required_response(macaroon, path, cookie_suffix_name, message=None): ''' Get response content and headers from a discharge macaroons error. @param macaroon may hold a macaroon that, when discharged, may allow access to a service. @param path holds the URL p...
Get response content and headers from a discharge macaroons error. @param macaroon may hold a macaroon that, when discharged, may allow access to a service. @param path holds the URL path to be associated with the macaroon. The macaroon is potentially valid for all URLs under the given path. @param...
Below is the the instruction that describes the task: ### Input: Get response content and headers from a discharge macaroons error. @param macaroon may hold a macaroon that, when discharged, may allow access to a service. @param path holds the URL path to be associated with the macaroon. The macaro...
def parse(self, stream, template, predefines=True, orig_filename=None, keep_successful=False, printf=True): """Parse the data stream using the template (e.g. parse the 010 template and interpret the template using the stream as the data source). :stream: The input data stream :template:...
Parse the data stream using the template (e.g. parse the 010 template and interpret the template using the stream as the data source). :stream: The input data stream :template: The template to parse the stream with :keep_successful: Return whatever was successfully parsed before an erro...
Below is the the instruction that describes the task: ### Input: Parse the data stream using the template (e.g. parse the 010 template and interpret the template using the stream as the data source). :stream: The input data stream :template: The template to parse the stream with :ke...
def post_public_key(self, path, data, is_json=True): '''Make a post request using a public key.''' post_data = { 'public_key': self.public_key } post_data.update(data) return self._post(path, post_data, is_json)
Make a post request using a public key.
Below is the the instruction that describes the task: ### Input: Make a post request using a public key. ### Response: def post_public_key(self, path, data, is_json=True): '''Make a post request using a public key.''' post_data = { 'public_key': self.public_key } post_da...
def get_as_string_with_default(self, key, default_value): """ Converts map element into a string or returns default value if conversion is not possible. :param key: an index of element to get. :param default_value: the default value :return: string value ot the element or defa...
Converts map element into a string or returns default value if conversion is not possible. :param key: an index of element to get. :param default_value: the default value :return: string value ot the element or default value if conversion is not supported.
Below is the the instruction that describes the task: ### Input: Converts map element into a string or returns default value if conversion is not possible. :param key: an index of element to get. :param default_value: the default value :return: string value ot the element or default value...
def luhn(n): """Validate that a string made of numeric characters verify Luhn test. Used by siret validator. from http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers#Python https://en.wikipedia.org/wiki/Luhn_algorithm """ r = [int(ch) for ch in str(n)][::-1] return (sum(r[0::2]...
Validate that a string made of numeric characters verify Luhn test. Used by siret validator. from http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers#Python https://en.wikipedia.org/wiki/Luhn_algorithm
Below is the the instruction that describes the task: ### Input: Validate that a string made of numeric characters verify Luhn test. Used by siret validator. from http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers#Python https://en.wikipedia.org/wiki/Luhn_algorithm ### Response: def luhn...
def ListCommands(self): """Print a list of currently available commands and their descriptions.""" print 'Available commands:' commands = dict(self.commands) for plugin in self.plugins: commands.update(plugin.commands) for com in sorted(commands): if not com.startswith('_'): self...
Print a list of currently available commands and their descriptions.
Below is the the instruction that describes the task: ### Input: Print a list of currently available commands and their descriptions. ### Response: def ListCommands(self): """Print a list of currently available commands and their descriptions.""" print 'Available commands:' commands = dict(self.command...
def mass_properties(self): """ Returns the mass properties of the current mesh. Assumes uniform density, and result is probably garbage if mesh isn't watertight. Returns ---------- properties : dict With keys: 'volume' : in global units^...
Returns the mass properties of the current mesh. Assumes uniform density, and result is probably garbage if mesh isn't watertight. Returns ---------- properties : dict With keys: 'volume' : in global units^3 'mass' : From specified dens...
Below is the the instruction that describes the task: ### Input: Returns the mass properties of the current mesh. Assumes uniform density, and result is probably garbage if mesh isn't watertight. Returns ---------- properties : dict With keys: 'volume' ...
def source_ports(self): """ Source ports for this blacklist entry. If no ports are specified (i.e. ALL ports), 'ANY' is returned. :rtype: str """ start_port = self.blacklist.get('BlacklistEntrySourcePort') if start_port is not None: return '{}...
Source ports for this blacklist entry. If no ports are specified (i.e. ALL ports), 'ANY' is returned. :rtype: str
Below is the the instruction that describes the task: ### Input: Source ports for this blacklist entry. If no ports are specified (i.e. ALL ports), 'ANY' is returned. :rtype: str ### Response: def source_ports(self): """ Source ports for this blacklist entry. If no ports ar...
def seed(cache_dir=CACHE_DIR, product=DEFAULT_PRODUCT, bounds=None, max_download_tiles=9, **kwargs): """Seed the DEM to given bounds. :param cache_dir: Root of the DEM cache folder. :param product: DEM product choice. :param bounds: Output bounds in 'left bottom right top' order. :param max_downloa...
Seed the DEM to given bounds. :param cache_dir: Root of the DEM cache folder. :param product: DEM product choice. :param bounds: Output bounds in 'left bottom right top' order. :param max_download_tiles: Maximum number of tiles to process. :param kwargs: Pass additional kwargs to ensure_tiles.
Below is the the instruction that describes the task: ### Input: Seed the DEM to given bounds. :param cache_dir: Root of the DEM cache folder. :param product: DEM product choice. :param bounds: Output bounds in 'left bottom right top' order. :param max_download_tiles: Maximum number of tiles to pro...
def shellsafe(s, quote='', doescape=True): """Returns the value string, wrapped in the specified quotes (if not empty), but checks and raises an Exception if the string is at risk of causing code injection""" if sys.version[0] == '2' and not isinstance(s,unicode): #pylint: disable=undefined-variable s =...
Returns the value string, wrapped in the specified quotes (if not empty), but checks and raises an Exception if the string is at risk of causing code injection
Below is the the instruction that describes the task: ### Input: Returns the value string, wrapped in the specified quotes (if not empty), but checks and raises an Exception if the string is at risk of causing code injection ### Response: def shellsafe(s, quote='', doescape=True): """Returns the value string, ...
def get_result(self): """ Get the result of this transfer. """ while self._result is None: if len(self.daplink._commands_to_read) > 0: self.daplink._read_packet() else: assert not self.daplink._crnt_cmd.get_empty() s...
Get the result of this transfer.
Below is the the instruction that describes the task: ### Input: Get the result of this transfer. ### Response: def get_result(self): """ Get the result of this transfer. """ while self._result is None: if len(self.daplink._commands_to_read) > 0: self.dap...
def get_peers(self): """Get all known nodes and their 'state' """ node = NodeLeader.Instance() result = {"connected": [], "unconnected": [], "bad": []} connected_peers = [] for peer in node.Peers: result['connected'].append({"address": peer.host, ...
Get all known nodes and their 'state'
Below is the the instruction that describes the task: ### Input: Get all known nodes and their 'state' ### Response: def get_peers(self): """Get all known nodes and their 'state' """ node = NodeLeader.Instance() result = {"connected": [], "unconnected": [], "bad": []} connected_peer...
def values(self): """ Return the list of values. """ def collect(d): if d is None or d.get('FIRST') is None: return [] vals = [d['FIRST']] vals.extend(collect(d.get('REST'))) return vals return collect(self)
Return the list of values.
Below is the the instruction that describes the task: ### Input: Return the list of values. ### Response: def values(self): """ Return the list of values. """ def collect(d): if d is None or d.get('FIRST') is None: return [] vals = [d['FIRST']...
def quantstr(typestr, num, plural_suffix='s'): r""" Heuristically generates an english phrase relating to the quantity of something. This is useful for writing user messages. Args: typestr (str): singular form of the word num (int): quanity of the type plural_suffix (str): heur...
r""" Heuristically generates an english phrase relating to the quantity of something. This is useful for writing user messages. Args: typestr (str): singular form of the word num (int): quanity of the type plural_suffix (str): heurstic plural form (default = 's') Returns: ...
Below is the the instruction that describes the task: ### Input: r""" Heuristically generates an english phrase relating to the quantity of something. This is useful for writing user messages. Args: typestr (str): singular form of the word num (int): quanity of the type plural_...
def _try_convert_value(conversion_finder, attr_name: str, attr_value: S, desired_attr_type: Type[T], logger: Logger, options: Dict[str, Dict[str, Any]]) -> T: """ Utility method to try to use provided conversion_finder to convert attr_value into desired_attr_type. If n...
Utility method to try to use provided conversion_finder to convert attr_value into desired_attr_type. If no conversion is required, the conversion finder is not even used (it can be None) :param conversion_finder: :param attr_name: :param attr_value: :param desired_attr_type: ...
Below is the the instruction that describes the task: ### Input: Utility method to try to use provided conversion_finder to convert attr_value into desired_attr_type. If no conversion is required, the conversion finder is not even used (it can be None) :param conversion_finder: :param attr_...
def Angle(self, other): """ Returns the angle in radians between self and other. """ return math.atan2(self.CrossProd(other).Norm2(), self.DotProd(other))
Returns the angle in radians between self and other.
Below is the the instruction that describes the task: ### Input: Returns the angle in radians between self and other. ### Response: def Angle(self, other): """ Returns the angle in radians between self and other. """ return math.atan2(self.CrossProd(other).Norm2(), self.DotPro...
def run(self): """Execute the process""" env = dict(os.environ) file_path = self.file.real_path path_folders = self.pycore.project.get_source_folders() + \ self.pycore.project.get_python_path_folders() env['PYTHONPATH'] = os.pathsep.join(folder.real_path ...
Execute the process
Below is the the instruction that describes the task: ### Input: Execute the process ### Response: def run(self): """Execute the process""" env = dict(os.environ) file_path = self.file.real_path path_folders = self.pycore.project.get_source_folders() + \ self.pycore.proj...
def _proxy_info(minion_id, api_url, email, secret_key, fqdn_separator): ''' retrieve a dict of a device that exists in nsot :param minion_id: str :param api_url: str :param email: str :param secret_key: str :param fqdn_separator: str :return: dict ''' device_info = {} if fqd...
retrieve a dict of a device that exists in nsot :param minion_id: str :param api_url: str :param email: str :param secret_key: str :param fqdn_separator: str :return: dict
Below is the the instruction that describes the task: ### Input: retrieve a dict of a device that exists in nsot :param minion_id: str :param api_url: str :param email: str :param secret_key: str :param fqdn_separator: str :return: dict ### Response: def _proxy_info(minion_id, api_url, ema...
def _credentials_found_in_envars(): """Check for credentials in envars. Returns: bool: ``True`` if at least one is found, otherwise ``False``. """ return any([os.getenv('PAN_ACCESS_TOKEN'), os.getenv('PAN_CLIENT_ID'), os.getenv('PAN_C...
Check for credentials in envars. Returns: bool: ``True`` if at least one is found, otherwise ``False``.
Below is the the instruction that describes the task: ### Input: Check for credentials in envars. Returns: bool: ``True`` if at least one is found, otherwise ``False``. ### Response: def _credentials_found_in_envars(): """Check for credentials in envars. Returns: b...
def pot_to_rpole_aligned(pot, sma, q, F, d, component=1): """ Transforms surface potential to polar radius """ q = q_for_component(q, component=component) Phi = pot_for_component(pot, q, component=component) logger.debug("libphobe.roche_pole(q={}, F={}, d={}, Omega={})".format(q, F, d, pot)) ...
Transforms surface potential to polar radius
Below is the the instruction that describes the task: ### Input: Transforms surface potential to polar radius ### Response: def pot_to_rpole_aligned(pot, sma, q, F, d, component=1): """ Transforms surface potential to polar radius """ q = q_for_component(q, component=component) Phi = pot_for_co...
def remote_file_size(self, remote_cmd="", remote_file=None): """Get the file size of the remote file.""" if remote_file is None: if self.direction == "put": remote_file = self.dest_file elif self.direction == "get": remote_file = self.source_file ...
Get the file size of the remote file.
Below is the the instruction that describes the task: ### Input: Get the file size of the remote file. ### Response: def remote_file_size(self, remote_cmd="", remote_file=None): """Get the file size of the remote file.""" if remote_file is None: if self.direction == "put": ...
def duplicate_key_line_numbers(messages, source): """Yield line numbers of duplicate keys.""" messages = [ message for message in messages if isinstance(message, pyflakes.messages.MultiValueRepeatedKeyLiteral)] if messages: # Filter out complex cases. We don't want to bother trying ...
Yield line numbers of duplicate keys.
Below is the the instruction that describes the task: ### Input: Yield line numbers of duplicate keys. ### Response: def duplicate_key_line_numbers(messages, source): """Yield line numbers of duplicate keys.""" messages = [ message for message in messages if isinstance(message, pyflakes.mes...
def file_signature(file_name: str) -> Optional[Tuple]: """ Return an identity signature for file name :param file_name: name of file :return: mode, size, last modified time if file exists, otherwise none """ try: st = os.stat(file_name) except FileNotFoundError: return None ...
Return an identity signature for file name :param file_name: name of file :return: mode, size, last modified time if file exists, otherwise none
Below is the the instruction that describes the task: ### Input: Return an identity signature for file name :param file_name: name of file :return: mode, size, last modified time if file exists, otherwise none ### Response: def file_signature(file_name: str) -> Optional[Tuple]: """ Return an identi...
def _from_dict(cls, _dict): """Initialize a UnalignedElement object from a json dictionary.""" args = {} if 'document_label' in _dict: args['document_label'] = _dict.get('document_label') if 'location' in _dict: args['location'] = Location._from_dict(_dict.get('lo...
Initialize a UnalignedElement object from a json dictionary.
Below is the the instruction that describes the task: ### Input: Initialize a UnalignedElement object from a json dictionary. ### Response: def _from_dict(cls, _dict): """Initialize a UnalignedElement object from a json dictionary.""" args = {} if 'document_label' in _dict: args...
def normalize_date(tmy_date, year): """change TMY3 date to an arbitrary year. Args: tmy_date (datetime): date to mangle. year (int): desired year. Returns: (None) """ month = tmy_date.month day = tmy_date.day - 1 hour = tmy_date.hour # hack to get around 24:00 n...
change TMY3 date to an arbitrary year. Args: tmy_date (datetime): date to mangle. year (int): desired year. Returns: (None)
Below is the the instruction that describes the task: ### Input: change TMY3 date to an arbitrary year. Args: tmy_date (datetime): date to mangle. year (int): desired year. Returns: (None) ### Response: def normalize_date(tmy_date, year): """change TMY3 date to an arbitrary ye...
def clip_out_of_image(self): """ Clip off all parts from all polygons that are outside of the image. NOTE: The result can contain less polygons than the input did. That happens when a polygon is fully outside of the image plane. NOTE: The result can also contain *more* polygons...
Clip off all parts from all polygons that are outside of the image. NOTE: The result can contain less polygons than the input did. That happens when a polygon is fully outside of the image plane. NOTE: The result can also contain *more* polygons than the input did. That happens when di...
Below is the the instruction that describes the task: ### Input: Clip off all parts from all polygons that are outside of the image. NOTE: The result can contain less polygons than the input did. That happens when a polygon is fully outside of the image plane. NOTE: The result can also con...
def coerce(self, value): """Convert text values into boolean values. True values are (case insensitive): 'yes', 'true', '1'. False values are (case insensitive): 'no', 'false', '0'. Args: value (str or bool): The value to coerce. Raises: TypeE...
Convert text values into boolean values. True values are (case insensitive): 'yes', 'true', '1'. False values are (case insensitive): 'no', 'false', '0'. Args: value (str or bool): The value to coerce. Raises: TypeError: If the value is not a bool or s...
Below is the the instruction that describes the task: ### Input: Convert text values into boolean values. True values are (case insensitive): 'yes', 'true', '1'. False values are (case insensitive): 'no', 'false', '0'. Args: value (str or bool): The value to coerce. ...
def search_genius_web(self, search_term, per_page=5): """Use the web-version of Genius search""" endpoint = "search/multi?" params = {'per_page': per_page, 'q': search_term} # This endpoint is not part of the API, requires different formatting url = "https://genius.com/api/" + e...
Use the web-version of Genius search
Below is the the instruction that describes the task: ### Input: Use the web-version of Genius search ### Response: def search_genius_web(self, search_term, per_page=5): """Use the web-version of Genius search""" endpoint = "search/multi?" params = {'per_page': per_page, 'q': search_term} ...