code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def authenticate(self, username, password, priv_lvl=TAC_PLUS_PRIV_LVL_MIN, authen_type=TAC_PLUS_AUTHEN_TYPE_ASCII, chap_ppp_id=None, chap_challenge=None, rem_addr=TAC_PLUS_VIRTUAL_REM_ADDR, port=TAC_PLUS_VIRTUAL_PORT): """ Authenticate to a ...
Authenticate to a TACACS+ server with a username and password. :param username: :param password: :param priv_lvl: :param authen_type: TAC_PLUS_AUTHEN_TYPE_ASCII, TAC_PLUS_AUTHEN_TYPE_PAP, TAC_PLUS_AUTHEN_TYPE_CHAP ...
Below is the the instruction that describes the task: ### Input: Authenticate to a TACACS+ server with a username and password. :param username: :param password: :param priv_lvl: :param authen_type: TAC_PLUS_AUTHEN_TYPE_ASCII, TAC_PLUS_AUTHEN_TYPE_P...
def get_timestamp(timezone_name, year, month, day, hour=0, minute=0): """Epoch timestamp from timezone, year, month, day, hour and minute.""" tz = pytz.timezone(timezone_name) tz_datetime = tz.localize(datetime(year, month, day, hour, minute)) timestamp = calendar.timegm(tz_datetime.utctimetuple()) ...
Epoch timestamp from timezone, year, month, day, hour and minute.
Below is the the instruction that describes the task: ### Input: Epoch timestamp from timezone, year, month, day, hour and minute. ### Response: def get_timestamp(timezone_name, year, month, day, hour=0, minute=0): """Epoch timestamp from timezone, year, month, day, hour and minute.""" tz = pytz.timezone(t...
def set_scroll_callback(window, cbfun): """ Sets the scroll callback. Wrapper for: GLFWscrollfun glfwSetScrollCallback(GLFWwindow* window, GLFWscrollfun cbfun); """ window_addr = ctypes.cast(ctypes.pointer(window), ctypes.POINTER(ctypes.c_long)).contents.value ...
Sets the scroll callback. Wrapper for: GLFWscrollfun glfwSetScrollCallback(GLFWwindow* window, GLFWscrollfun cbfun);
Below is the the instruction that describes the task: ### Input: Sets the scroll callback. Wrapper for: GLFWscrollfun glfwSetScrollCallback(GLFWwindow* window, GLFWscrollfun cbfun); ### Response: def set_scroll_callback(window, cbfun): """ Sets the scroll callback. Wrapper for: GL...
def openAnything(source, searchpaths=None): """URI, filename, or string --> stream This function lets you define parsers that take any input source (URL, pathname to local or network file, or actual data as a string) and deal with it in a uniform manner. Returned object is guaranteed to have...
URI, filename, or string --> stream This function lets you define parsers that take any input source (URL, pathname to local or network file, or actual data as a string) and deal with it in a uniform manner. Returned object is guaranteed to have all the basic stdio read methods (read, readline, r...
Below is the the instruction that describes the task: ### Input: URI, filename, or string --> stream This function lets you define parsers that take any input source (URL, pathname to local or network file, or actual data as a string) and deal with it in a uniform manner. Returned object is guaran...
def touidref(src, dst, src_relation, src_portal_type, fieldname): """Convert an archetypes reference in src/src_relation to a UIDReference in dst/fieldname. """ field = dst.getField(fieldname) refs = src.getRefs(relationship=src_relation) if len(refs) == 1: value = get_uid(refs[0]) ...
Convert an archetypes reference in src/src_relation to a UIDReference in dst/fieldname.
Below is the the instruction that describes the task: ### Input: Convert an archetypes reference in src/src_relation to a UIDReference in dst/fieldname. ### Response: def touidref(src, dst, src_relation, src_portal_type, fieldname): """Convert an archetypes reference in src/src_relation to a UIDReference ...
def auth(alias=None, url=None, cfg="~/.xnat_auth"): ''' Read connection details from an xnat_auth XML file Example: >>> import yaxil >>> auth = yaxil.auth('xnatastic') >>> auth.url, auth.username, auth.password ('https://www.xnatastic.org/', 'username', '********') :par...
Read connection details from an xnat_auth XML file Example: >>> import yaxil >>> auth = yaxil.auth('xnatastic') >>> auth.url, auth.username, auth.password ('https://www.xnatastic.org/', 'username', '********') :param alias: XNAT alias :type alias: str :param url: XNAT U...
Below is the the instruction that describes the task: ### Input: Read connection details from an xnat_auth XML file Example: >>> import yaxil >>> auth = yaxil.auth('xnatastic') >>> auth.url, auth.username, auth.password ('https://www.xnatastic.org/', 'username', '********') ...
def wrap_class(cls, error_threshold=None): ''' Wraps a class with reporting to errors backend by decorating each function of the class. Decorators are injected under the classmethod decorator if they exist. ''' methods = inspect.getmembers(cls, inspect.ismethod) + inspect.getmembers(cls, inspect...
Wraps a class with reporting to errors backend by decorating each function of the class. Decorators are injected under the classmethod decorator if they exist.
Below is the the instruction that describes the task: ### Input: Wraps a class with reporting to errors backend by decorating each function of the class. Decorators are injected under the classmethod decorator if they exist. ### Response: def wrap_class(cls, error_threshold=None): ''' Wraps a class...
def _completion_checker(async_id, context_id): """Check if all Async jobs within a Context have been run.""" if not context_id: logging.debug("Context for async %s does not exist", async_id) return context = FuriousContext.from_id(context_id) marker = FuriousCompletionMarker.get_by_id(...
Check if all Async jobs within a Context have been run.
Below is the the instruction that describes the task: ### Input: Check if all Async jobs within a Context have been run. ### Response: def _completion_checker(async_id, context_id): """Check if all Async jobs within a Context have been run.""" if not context_id: logging.debug("Context for async %s...
def add_user(self, user_name, role='user'): """ Calls CF's associate user with org. Valid roles include `user`, `auditor`, `manager`,`billing_manager` """ role_uri = self._get_role_uri(role=role) return self.api.put(path=role_uri, data={'username': user_name})
Calls CF's associate user with org. Valid roles include `user`, `auditor`, `manager`,`billing_manager`
Below is the the instruction that describes the task: ### Input: Calls CF's associate user with org. Valid roles include `user`, `auditor`, `manager`,`billing_manager` ### Response: def add_user(self, user_name, role='user'): """ Calls CF's associate user with org. Valid roles include `user...
def add_html_link(app, pagename, templatename, context, doctree): """As each page is built, collect page names for the sitemap""" base_url = app.config['html_theme_options'].get('base_url', '') if base_url: app.sitemap_links.append(base_url + pagename + ".html")
As each page is built, collect page names for the sitemap
Below is the the instruction that describes the task: ### Input: As each page is built, collect page names for the sitemap ### Response: def add_html_link(app, pagename, templatename, context, doctree): """As each page is built, collect page names for the sitemap""" base_url = app.config['html_theme_option...
def get_lat_variable(nc): ''' Returns the variable for latitude :param netcdf4.dataset nc: an open netcdf dataset object ''' if 'latitude' in nc.variables: return 'latitude' latitudes = nc.get_variables_by_attributes(standard_name="latitude") if latitudes: return latitudes[0...
Returns the variable for latitude :param netcdf4.dataset nc: an open netcdf dataset object
Below is the the instruction that describes the task: ### Input: Returns the variable for latitude :param netcdf4.dataset nc: an open netcdf dataset object ### Response: def get_lat_variable(nc): ''' Returns the variable for latitude :param netcdf4.dataset nc: an open netcdf dataset object ''...
def reset_for_retry(self): """Reset self for shard retry.""" self.retries += 1 self.last_work_item = "" self.active = True self.result_status = None self.input_finished = False self.counters_map = CountersMap() self.slice_id = 0 self.slice_start_time = None self.slice_request_id ...
Reset self for shard retry.
Below is the the instruction that describes the task: ### Input: Reset self for shard retry. ### Response: def reset_for_retry(self): """Reset self for shard retry.""" self.retries += 1 self.last_work_item = "" self.active = True self.result_status = None self.input_finished = False sel...
def to_utc_datetime(self, value): """ from value to datetime with tzinfo format (datetime.datetime instance) """ if isinstance(value, (six.integer_types, float, six.string_types)): value = self.to_naive_datetime(value) if isinstance(value, datetime.datetime): ...
from value to datetime with tzinfo format (datetime.datetime instance)
Below is the the instruction that describes the task: ### Input: from value to datetime with tzinfo format (datetime.datetime instance) ### Response: def to_utc_datetime(self, value): """ from value to datetime with tzinfo format (datetime.datetime instance) """ if isinstance(value,...
def get_changes(self, remove=True, only_current=False, resources=None, task_handle=taskhandle.NullTaskHandle()): """Get the changes this refactoring makes If `remove` is `False` the definition will not be removed. If `only_current` is `True`, the the current occurrence will...
Get the changes this refactoring makes If `remove` is `False` the definition will not be removed. If `only_current` is `True`, the the current occurrence will be inlined, only.
Below is the the instruction that describes the task: ### Input: Get the changes this refactoring makes If `remove` is `False` the definition will not be removed. If `only_current` is `True`, the the current occurrence will be inlined, only. ### Response: def get_changes(self, remove=True...
def parse_files(self, req, name, field): """Pull a file from the request.""" files = ((k, v) for k, v in req.POST.items() if hasattr(v, "file")) return core.get_value(MultiDict(files), name, field)
Pull a file from the request.
Below is the the instruction that describes the task: ### Input: Pull a file from the request. ### Response: def parse_files(self, req, name, field): """Pull a file from the request.""" files = ((k, v) for k, v in req.POST.items() if hasattr(v, "file")) return core.get_value(MultiDict(files...
def write_multiple_registers(slave_id, starting_address, values): """ Return ADU for Modbus function code 16: Write Multiple Registers. :param slave_id: Number of slave. :return: Byte array with ADU. """ function = WriteMultipleRegisters() function.starting_address = starting_address functi...
Return ADU for Modbus function code 16: Write Multiple Registers. :param slave_id: Number of slave. :return: Byte array with ADU.
Below is the the instruction that describes the task: ### Input: Return ADU for Modbus function code 16: Write Multiple Registers. :param slave_id: Number of slave. :return: Byte array with ADU. ### Response: def write_multiple_registers(slave_id, starting_address, values): """ Return ADU for Modbus f...
def check_order(self, order): """ order must be a subset of self.order """ own_order = self.order for item in order: if item not in own_order: raise ValueError(f'Order item {item} not found.') return order
order must be a subset of self.order
Below is the the instruction that describes the task: ### Input: order must be a subset of self.order ### Response: def check_order(self, order): """ order must be a subset of self.order """ own_order = self.order for item in order: if item not in own_order: raise ValueError(f'O...
def _prepare_configs(configs, requires_filters, temporal_timeouts): """ Overrides the filters specified in the decorator with the given ones :param configs: Field β†’ (Requirement, key, allow_none) dictionary :param requires_filters: Content of the 'requires.filter' component ...
Overrides the filters specified in the decorator with the given ones :param configs: Field β†’ (Requirement, key, allow_none) dictionary :param requires_filters: Content of the 'requires.filter' component property (field β†’ string) :param temporal_timeouts: Content...
Below is the the instruction that describes the task: ### Input: Overrides the filters specified in the decorator with the given ones :param configs: Field β†’ (Requirement, key, allow_none) dictionary :param requires_filters: Content of the 'requires.filter' component ...
def codepoint_included(self, codepoint): """Check if codepoint matches any of the defined codepoints.""" if self.codepoints == None: return True for cp in self.codepoints: mismatch = False for i in range(len(cp)): if (cp[i] is not None) and (cp...
Check if codepoint matches any of the defined codepoints.
Below is the the instruction that describes the task: ### Input: Check if codepoint matches any of the defined codepoints. ### Response: def codepoint_included(self, codepoint): """Check if codepoint matches any of the defined codepoints.""" if self.codepoints == None: return True ...
def create_args(line, namespace): """ Expand any meta-variable references in the argument list. """ args = [] # Using shlex.split handles quotes args and escape characters. for arg in shlex.split(line): if not arg: continue if arg[0] == '$': var_name = arg[1:] if var...
Expand any meta-variable references in the argument list.
Below is the the instruction that describes the task: ### Input: Expand any meta-variable references in the argument list. ### Response: def create_args(line, namespace): """ Expand any meta-variable references in the argument list. """ args = [] # Using shlex.split handles quotes args and escape chara...
def save(self): """ :return: save this OS instance on Ariane server (create or update) """ LOGGER.debug("OSInstance.save") post_payload = {} consolidated_osi_id = [] consolidated_ipa_id = [] consolidated_nic_id = [] consolidated_app_id = [] ...
:return: save this OS instance on Ariane server (create or update)
Below is the the instruction that describes the task: ### Input: :return: save this OS instance on Ariane server (create or update) ### Response: def save(self): """ :return: save this OS instance on Ariane server (create or update) """ LOGGER.debug("OSInstance.save") post_p...
def finding_path(cls, project, scan_config, scan_run, finding): """Return a fully-qualified finding string.""" return google.api_core.path_template.expand( "projects/{project}/scanConfigs/{scan_config}/scanRuns/{scan_run}/findings/{finding}", project=project, scan_con...
Return a fully-qualified finding string.
Below is the the instruction that describes the task: ### Input: Return a fully-qualified finding string. ### Response: def finding_path(cls, project, scan_config, scan_run, finding): """Return a fully-qualified finding string.""" return google.api_core.path_template.expand( "projects/{...
def _init_oauth(self, oauth_token, oauth_token_secret): "Store and initialize a verified set of OAuth credentials" self.oauth_token = oauth_token self.oauth_token_secret = oauth_token_secret self._oauth = OAuth1( self.consumer_key, client_secret=self.consumer_sec...
Store and initialize a verified set of OAuth credentials
Below is the the instruction that describes the task: ### Input: Store and initialize a verified set of OAuth credentials ### Response: def _init_oauth(self, oauth_token, oauth_token_secret): "Store and initialize a verified set of OAuth credentials" self.oauth_token = oauth_token self.oaut...
def cancelTask(self, *args, **kwargs): """ Cancel Task This method will cancel a task that is either `unscheduled`, `pending` or `running`. It will resolve the current run as `exception` with `reasonResolved` set to `canceled`. If the task isn't scheduled yet, ie. it doe...
Cancel Task This method will cancel a task that is either `unscheduled`, `pending` or `running`. It will resolve the current run as `exception` with `reasonResolved` set to `canceled`. If the task isn't scheduled yet, ie. it doesn't have any runs, an initial run will be added and resolv...
Below is the the instruction that describes the task: ### Input: Cancel Task This method will cancel a task that is either `unscheduled`, `pending` or `running`. It will resolve the current run as `exception` with `reasonResolved` set to `canceled`. If the task isn't scheduled yet, ie. ...
def match(self, pattern, screen=None, rect=None, offset=None, threshold=None, method=None): """Check if image position in screen Args: - pattern: Image file name or opencv image object - screen (PIL.Image): optional, if not None, screenshot method will be called - th...
Check if image position in screen Args: - pattern: Image file name or opencv image object - screen (PIL.Image): optional, if not None, screenshot method will be called - threshold (float): it depends on the image match method - method (string): choices on <templa...
Below is the the instruction that describes the task: ### Input: Check if image position in screen Args: - pattern: Image file name or opencv image object - screen (PIL.Image): optional, if not None, screenshot method will be called - threshold (float): it depends on the...
def get(self, server): """ Retrieve credentials for `server`. If no credentials are found, a `StoreError` will be raised. """ if not isinstance(server, six.binary_type): server = server.encode('utf-8') data = self._execute('get', server) result = json.load...
Retrieve credentials for `server`. If no credentials are found, a `StoreError` will be raised.
Below is the the instruction that describes the task: ### Input: Retrieve credentials for `server`. If no credentials are found, a `StoreError` will be raised. ### Response: def get(self, server): """ Retrieve credentials for `server`. If no credentials are found, a `StoreError` wil...
def full_s(self): """ Get the full singular value matrix of self Returns ------- Matrix : Matrix """ x = np.zeros((self.shape),dtype=np.float32) x[:self.s.shape[0],:self.s.shape[0]] = self.s.as_2d s = Matrix(x=x, row_names=self.row_names, ...
Get the full singular value matrix of self Returns ------- Matrix : Matrix
Below is the the instruction that describes the task: ### Input: Get the full singular value matrix of self Returns ------- Matrix : Matrix ### Response: def full_s(self): """ Get the full singular value matrix of self Returns ------- Matrix : Matrix ...
def push_front(self, value): '''Appends a copy of ``value`` to the beginning of the list.''' self.cache.push_front(self.value_pickler.dumps(value))
Appends a copy of ``value`` to the beginning of the list.
Below is the the instruction that describes the task: ### Input: Appends a copy of ``value`` to the beginning of the list. ### Response: def push_front(self, value): '''Appends a copy of ``value`` to the beginning of the list.''' self.cache.push_front(self.value_pickler.dumps(value))
def tv2(data,weight,Niter=50): """ chambolles tv regularized denoising weight should be around 2+1.5*noise_sigma """ prog = OCLProgram(abspath("kernels/tv2.cl")) data_im = OCLImage.from_array(data.astype(np,float32,copy=False)) pImgs = [ dev.createImage(data.shape[::-1], ...
chambolles tv regularized denoising weight should be around 2+1.5*noise_sigma
Below is the the instruction that describes the task: ### Input: chambolles tv regularized denoising weight should be around 2+1.5*noise_sigma ### Response: def tv2(data,weight,Niter=50): """ chambolles tv regularized denoising weight should be around 2+1.5*noise_sigma """ prog = OCLPr...
def _arith_method_SPARSE_SERIES(cls, op, special): """ Wrapper function for Series arithmetic operations, to avoid code duplication. """ op_name = _get_op_name(op, special) def wrapper(self, other): if isinstance(other, ABCDataFrame): return NotImplemented elif isins...
Wrapper function for Series arithmetic operations, to avoid code duplication.
Below is the the instruction that describes the task: ### Input: Wrapper function for Series arithmetic operations, to avoid code duplication. ### Response: def _arith_method_SPARSE_SERIES(cls, op, special): """ Wrapper function for Series arithmetic operations, to avoid code duplication. """ ...
def _update_record(self, record_id, name, address, ttl): """Updates an existing record.""" data = json.dumps({'record': {'name': name, 'content': address, 'ttl': ttl}}) headers = {'Content-Type': 'application/json'} ...
Updates an existing record.
Below is the the instruction that describes the task: ### Input: Updates an existing record. ### Response: def _update_record(self, record_id, name, address, ttl): """Updates an existing record.""" data = json.dumps({'record': {'name': name, 'content': address,...
def clean_description(self): """ Text content validation """ description = self.cleaned_data.get("description") validation_helper = safe_import_module(settings.FORUM_TEXT_VALIDATOR_HELPER_PATH) if validation_helper is not None: return validation_helper(self, d...
Text content validation
Below is the the instruction that describes the task: ### Input: Text content validation ### Response: def clean_description(self): """ Text content validation """ description = self.cleaned_data.get("description") validation_helper = safe_import_module(settings.FORUM_TEXT_V...
def get_item_admin_session(self, proxy): """Gets the ``OsidSession`` associated with the item administration service. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.assessment.ItemAdminSession) - an ``ItemAdminSession`` raise: NullArgument - ``proxy`` is ``null...
Gets the ``OsidSession`` associated with the item administration service. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.assessment.ItemAdminSession) - an ``ItemAdminSession`` raise: NullArgument - ``proxy`` is ``null`` raise: OperationFailed - unable to compl...
Below is the the instruction that describes the task: ### Input: Gets the ``OsidSession`` associated with the item administration service. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.assessment.ItemAdminSession) - an ``ItemAdminSession`` raise: NullArgument - ``...
def particle_covariance_mtx(weights,locations): """ Returns an estimate of the covariance of a distribution represented by a given set of SMC particle. :param weights: An array containing the weights of each particle. :param location: An array containing the locations of each partic...
Returns an estimate of the covariance of a distribution represented by a given set of SMC particle. :param weights: An array containing the weights of each particle. :param location: An array containing the locations of each particle. :rtype: :class:`numpy.ndarray`, shape ``(n_m...
Below is the the instruction that describes the task: ### Input: Returns an estimate of the covariance of a distribution represented by a given set of SMC particle. :param weights: An array containing the weights of each particle. :param location: An array containing the locations of ea...
def android_setup_view(request): """Set up a GCM session. This does *not* require a valid login session. Instead, a token from the client session is sent to the Android backend, which queries a POST request to this view. The "android_gcm_rand" is randomly set when the Android app is detected through ...
Set up a GCM session. This does *not* require a valid login session. Instead, a token from the client session is sent to the Android backend, which queries a POST request to this view. The "android_gcm_rand" is randomly set when the Android app is detected through the user agent. If it has the same val...
Below is the the instruction that describes the task: ### Input: Set up a GCM session. This does *not* require a valid login session. Instead, a token from the client session is sent to the Android backend, which queries a POST request to this view. The "android_gcm_rand" is randomly set when the Andro...
def clear(self): """Clears the line and returns cursor to the start. of line Returns ------- self """ if not self._enabled: return self self._stream.write('\r') self._stream.write(self.CLEAR_LINE) return self
Clears the line and returns cursor to the start. of line Returns ------- self
Below is the the instruction that describes the task: ### Input: Clears the line and returns cursor to the start. of line Returns ------- self ### Response: def clear(self): """Clears the line and returns cursor to the start. of line Returns ------- ...
def index_nearest(array, value): """ Finds index of nearest value in array. Args: array: numpy array value: Returns: int http://stackoverflow.com/questions/2566412/find-nearest-value-in-numpy-array """ idx = (np.abs(array-value)).argmin() return i...
Finds index of nearest value in array. Args: array: numpy array value: Returns: int http://stackoverflow.com/questions/2566412/find-nearest-value-in-numpy-array
Below is the the instruction that describes the task: ### Input: Finds index of nearest value in array. Args: array: numpy array value: Returns: int http://stackoverflow.com/questions/2566412/find-nearest-value-in-numpy-array ### Response: def index_nearest(array, va...
def _IsUnparsedFlagAccessAllowed(self, name): """Determine whether to allow unparsed flag access or not.""" if _UNPARSED_FLAG_ACCESS_ENV_NAME in os.environ: # We've been told explicitly what to do. allow_unparsed_flag_access = ( os.getenv(_UNPARSED_FLAG_ACCESS_ENV_NAME) == '1') elif se...
Determine whether to allow unparsed flag access or not.
Below is the the instruction that describes the task: ### Input: Determine whether to allow unparsed flag access or not. ### Response: def _IsUnparsedFlagAccessAllowed(self, name): """Determine whether to allow unparsed flag access or not.""" if _UNPARSED_FLAG_ACCESS_ENV_NAME in os.environ: # We've b...
def __read_frame(self): """*Attempt* to read a frame. If we get an EAGAIN on the frame header, it'll raise to our caller. If we get it *after* we already got the header, wait-out the rest of the frame. """ if self.__frame_header_cache is None: _logger.debug("Readin...
*Attempt* to read a frame. If we get an EAGAIN on the frame header, it'll raise to our caller. If we get it *after* we already got the header, wait-out the rest of the frame.
Below is the the instruction that describes the task: ### Input: *Attempt* to read a frame. If we get an EAGAIN on the frame header, it'll raise to our caller. If we get it *after* we already got the header, wait-out the rest of the frame. ### Response: def __read_frame(self): """*Attempt...
def sunset(self, date=None, zenith=None): """Calculate sunset times for locations. Args: date (datetime.date): Calculate rise or set for given date zenith (str): Calculate sunset events, or start of twilight times Returns: list of list of datetime.datetime: ...
Calculate sunset times for locations. Args: date (datetime.date): Calculate rise or set for given date zenith (str): Calculate sunset events, or start of twilight times Returns: list of list of datetime.datetime: The time for the sunset for each poin...
Below is the the instruction that describes the task: ### Input: Calculate sunset times for locations. Args: date (datetime.date): Calculate rise or set for given date zenith (str): Calculate sunset events, or start of twilight times Returns: list of list of dat...
def metric_history(slug, granularity="daily", since=None, to=None, with_data_table=False): """Template Tag to display a metric's history. * ``slug`` -- the metric's unique slug * ``granularity`` -- the granularity: daily, hourly, weekly, monthly, yearly * ``since`` -- a datetime obje...
Template Tag to display a metric's history. * ``slug`` -- the metric's unique slug * ``granularity`` -- the granularity: daily, hourly, weekly, monthly, yearly * ``since`` -- a datetime object or a string string matching one of the following patterns: "YYYY-mm-dd" for a date or "YYYY-mm-dd HH:MM:SS" ...
Below is the the instruction that describes the task: ### Input: Template Tag to display a metric's history. * ``slug`` -- the metric's unique slug * ``granularity`` -- the granularity: daily, hourly, weekly, monthly, yearly * ``since`` -- a datetime object or a string string matching one of the ...
def crossJoin(self, other): """Returns the cartesian product with another :class:`DataFrame`. :param other: Right side of the cartesian product. >>> df.select("age", "name").collect() [Row(age=2, name=u'Alice'), Row(age=5, name=u'Bob')] >>> df2.select("name", "height").collect(...
Returns the cartesian product with another :class:`DataFrame`. :param other: Right side of the cartesian product. >>> df.select("age", "name").collect() [Row(age=2, name=u'Alice'), Row(age=5, name=u'Bob')] >>> df2.select("name", "height").collect() [Row(name=u'Tom', height=80),...
Below is the the instruction that describes the task: ### Input: Returns the cartesian product with another :class:`DataFrame`. :param other: Right side of the cartesian product. >>> df.select("age", "name").collect() [Row(age=2, name=u'Alice'), Row(age=5, name=u'Bob')] >>> df2.sel...
def assertFileSizeAlmostEqual( self, filename, size, places=None, msg=None, delta=None): '''Fail if ``filename`` does not have the given ``size`` as determined by their difference rounded to the given number of decimal ``places`` (default 7) and comparing to zero, or if their...
Fail if ``filename`` does not have the given ``size`` as determined by their difference rounded to the given number of decimal ``places`` (default 7) and comparing to zero, or if their difference is greater than a given ``delta``. Parameters ---------- filename : str, by...
Below is the the instruction that describes the task: ### Input: Fail if ``filename`` does not have the given ``size`` as determined by their difference rounded to the given number of decimal ``places`` (default 7) and comparing to zero, or if their difference is greater than a given ``delta...
def compile_template(template, renderers, default, blacklist, whitelist, saltenv='base', sls='', input_data='', **kwargs): ''' Take the path to ...
Take the path to a template and return the high data structure derived from the template. Helpers: :param mask_value: Mask value for debugging purposes (prevent sensitive information etc) example: "mask_value="pass*". All "passwd", "password", "pass" will be masked (as text).
Below is the the instruction that describes the task: ### Input: Take the path to a template and return the high data structure derived from the template. Helpers: :param mask_value: Mask value for debugging purposes (prevent sensitive information etc) example: "mask_value="pass*". All...
def set_attr(self, attr_id, value): """Calls SQLSetConnectAttr with the given values. :param attr_id: the attribute ID (integer) to set. These are ODBC or driver constants. :parm value: the connection attribute value to set. At this time only integer values are supported...
Calls SQLSetConnectAttr with the given values. :param attr_id: the attribute ID (integer) to set. These are ODBC or driver constants. :parm value: the connection attribute value to set. At this time only integer values are supported.
Below is the the instruction that describes the task: ### Input: Calls SQLSetConnectAttr with the given values. :param attr_id: the attribute ID (integer) to set. These are ODBC or driver constants. :parm value: the connection attribute value to set. At this time only intege...
def poll(self, id): """Poll with a given id. Parameters ---------- id : int Poll id. Returns ------- an :class:`ApiQuery` of :class:`Poll` Raises ------ :class:`NotFound` If a poll with the requested id doesn't ex...
Poll with a given id. Parameters ---------- id : int Poll id. Returns ------- an :class:`ApiQuery` of :class:`Poll` Raises ------ :class:`NotFound` If a poll with the requested id doesn't exist.
Below is the the instruction that describes the task: ### Input: Poll with a given id. Parameters ---------- id : int Poll id. Returns ------- an :class:`ApiQuery` of :class:`Poll` Raises ------ :class:`NotFound` If a...
def _normalized_cookie_tuples(self, attrs_set): """Return list of tuples containing normalised cookie information. attrs_set is the list of lists of key,value pairs extracted from the Set-Cookie or Set-Cookie2 headers. Tuples are name, value, standard, rest, where name and value are th...
Return list of tuples containing normalised cookie information. attrs_set is the list of lists of key,value pairs extracted from the Set-Cookie or Set-Cookie2 headers. Tuples are name, value, standard, rest, where name and value are the cookie name and value, standard is a dictionary c...
Below is the the instruction that describes the task: ### Input: Return list of tuples containing normalised cookie information. attrs_set is the list of lists of key,value pairs extracted from the Set-Cookie or Set-Cookie2 headers. Tuples are name, value, standard, rest, where name and va...
def reduce(self, body): ''' remove nodes from a list ''' i = 0 while i < len(body): stmnt = body[i] if self.visit(stmnt): body.pop(i) else: i += 1
remove nodes from a list
Below is the the instruction that describes the task: ### Input: remove nodes from a list ### Response: def reduce(self, body): ''' remove nodes from a list ''' i = 0 while i < len(body): stmnt = body[i] if self.visit(stmnt): body.pop(...
def season_id(x): """takes in 4-digit years and returns API formatted seasonID Input Values: YYYY Used in: """ if len(str(x)) == 4: try: return "".join(["2", str(x)]) except ValueError: raise ValueError("Enter the four digit year for the first half of the ...
takes in 4-digit years and returns API formatted seasonID Input Values: YYYY Used in:
Below is the the instruction that describes the task: ### Input: takes in 4-digit years and returns API formatted seasonID Input Values: YYYY Used in: ### Response: def season_id(x): """takes in 4-digit years and returns API formatted seasonID Input Values: YYYY Used in: """ if l...
def scopes(self, name=None, pk=None, status=ScopeStatus.ACTIVE, **kwargs): # type: (Optional[str], Optional[str], Optional[str], **Any) -> List[Scope] """Return all scopes visible / accessible for the logged in user. If additional `keyword=value` arguments are provided, these are added to the r...
Return all scopes visible / accessible for the logged in user. If additional `keyword=value` arguments are provided, these are added to the request parameters. Please refer to the documentation of the KE-chain API for additional query parameters. :param name: if provided, filter the search for...
Below is the the instruction that describes the task: ### Input: Return all scopes visible / accessible for the logged in user. If additional `keyword=value` arguments are provided, these are added to the request parameters. Please refer to the documentation of the KE-chain API for additional query...
def read_all(self): """Returns the 2 byte Header ROM and all 120 byte static memory. """ log.debug("read all static memory") cmd = "\x00\x00\x00" + self.uid return self.transceive(cmd)
Returns the 2 byte Header ROM and all 120 byte static memory.
Below is the the instruction that describes the task: ### Input: Returns the 2 byte Header ROM and all 120 byte static memory. ### Response: def read_all(self): """Returns the 2 byte Header ROM and all 120 byte static memory. """ log.debug("read all static memory") cmd = "\x00\x00\x...
def drawPoint(self, x, y, silent=True): """ Draws a point on the current :py:class:`Layer` with the current :py:class:`Brush`. Coordinates are relative to the original layer size WITHOUT downsampling applied. :param x1: Point X coordinate. :param y1: Point Y coordinate. :rtype: Nothing. """ start = tim...
Draws a point on the current :py:class:`Layer` with the current :py:class:`Brush`. Coordinates are relative to the original layer size WITHOUT downsampling applied. :param x1: Point X coordinate. :param y1: Point Y coordinate. :rtype: Nothing.
Below is the the instruction that describes the task: ### Input: Draws a point on the current :py:class:`Layer` with the current :py:class:`Brush`. Coordinates are relative to the original layer size WITHOUT downsampling applied. :param x1: Point X coordinate. :param y1: Point Y coordinate. :rtype: Nothing...
def compute_Pi_V_given_J(self, CDR3_seq, V_usage_mask, J_usage_mask): """Compute Pi_V conditioned on J. This function returns the Pi array from the model factors of the V genomic contributions, P(V, J)*P(delV|V). This corresponds to V(J)_{x_1}. For clarity in parsing the a...
Compute Pi_V conditioned on J. This function returns the Pi array from the model factors of the V genomic contributions, P(V, J)*P(delV|V). This corresponds to V(J)_{x_1}. For clarity in parsing the algorithm implementation, we include which instance attributes are used i...
Below is the the instruction that describes the task: ### Input: Compute Pi_V conditioned on J. This function returns the Pi array from the model factors of the V genomic contributions, P(V, J)*P(delV|V). This corresponds to V(J)_{x_1}. For clarity in parsing the algorithm imp...
def get_instance(self, payload): """ Build an instance of ThisMonthInstance :param dict payload: Payload response from the API :returns: twilio.rest.api.v2010.account.usage.record.this_month.ThisMonthInstance :rtype: twilio.rest.api.v2010.account.usage.record.this_month.ThisMon...
Build an instance of ThisMonthInstance :param dict payload: Payload response from the API :returns: twilio.rest.api.v2010.account.usage.record.this_month.ThisMonthInstance :rtype: twilio.rest.api.v2010.account.usage.record.this_month.ThisMonthInstance
Below is the the instruction that describes the task: ### Input: Build an instance of ThisMonthInstance :param dict payload: Payload response from the API :returns: twilio.rest.api.v2010.account.usage.record.this_month.ThisMonthInstance :rtype: twilio.rest.api.v2010.account.usage.record.th...
def copy(self, *, shallow=False): """Return a copy of a table.""" table = type(self)() for label in self.labels: if shallow: column = self[label] else: column = np.copy(self[label]) self._add_column_and_format(table, label, colu...
Return a copy of a table.
Below is the the instruction that describes the task: ### Input: Return a copy of a table. ### Response: def copy(self, *, shallow=False): """Return a copy of a table.""" table = type(self)() for label in self.labels: if shallow: column = self[label] ...
def waveform_to_examples(data, sample_rate): """Converts audio waveform into an array of examples for VGGish. Args: data: np.array of either one dimension (mono) or two dimensions (multi-channel, with the outer dimension representing channels). Each sample is generally expected to lie in the range ...
Converts audio waveform into an array of examples for VGGish. Args: data: np.array of either one dimension (mono) or two dimensions (multi-channel, with the outer dimension representing channels). Each sample is generally expected to lie in the range [-1.0, +1.0], although this is not required....
Below is the the instruction that describes the task: ### Input: Converts audio waveform into an array of examples for VGGish. Args: data: np.array of either one dimension (mono) or two dimensions (multi-channel, with the outer dimension representing channels). Each sample is generally expected t...
def as_ul(self, current_linkable=False, class_current="active_link", before_1="", after_1="", before_all="", after_all=""): """ It returns menu as ul """ return self.__do_menu("as_ul", current_linkable, class_current, before_1=before_1, after_1...
It returns menu as ul
Below is the the instruction that describes the task: ### Input: It returns menu as ul ### Response: def as_ul(self, current_linkable=False, class_current="active_link", before_1="", after_1="", before_all="", after_all=""): """ It returns menu as ul """ return self.__...
def set_filling(self, populations): """Sets the orbital enenergies for on the reference of the free case. By setting the desired local populations on every orbital. Then generate the necesary operators to respect such configuraion""" populations = np.asarray(populations) # # s...
Sets the orbital enenergies for on the reference of the free case. By setting the desired local populations on every orbital. Then generate the necesary operators to respect such configuraion
Below is the the instruction that describes the task: ### Input: Sets the orbital enenergies for on the reference of the free case. By setting the desired local populations on every orbital. Then generate the necesary operators to respect such configuraion ### Response: def set_filling(self, po...
def start_date(self) -> Optional[datetime.date]: """ Returns the start date of the set of intervals, or ``None`` if empty. """ if not self.intervals: return None return self.start_datetime().date()
Returns the start date of the set of intervals, or ``None`` if empty.
Below is the the instruction that describes the task: ### Input: Returns the start date of the set of intervals, or ``None`` if empty. ### Response: def start_date(self) -> Optional[datetime.date]: """ Returns the start date of the set of intervals, or ``None`` if empty. """ if not ...
def __placeSellShortOrder(self, tick): ''' place short sell order''' share=math.floor(self.__strategy.getAccountCopy().getCash() / float(tick.close)) sellShortOrder=Order(accountId=self.__strategy.accountId, action=Action.SELL_SHORT, ...
place short sell order
Below is the the instruction that describes the task: ### Input: place short sell order ### Response: def __placeSellShortOrder(self, tick): ''' place short sell order''' share=math.floor(self.__strategy.getAccountCopy().getCash() / float(tick.close)) sellShortOrder=Order(accountId=self.__s...
def _iter_grouped_shortcut(self): """Fast version of `_iter_grouped` that yields Variables without metadata """ var = self._obj.variable for indices in self._group_indices: yield var[{self._group_dim: indices}]
Fast version of `_iter_grouped` that yields Variables without metadata
Below is the the instruction that describes the task: ### Input: Fast version of `_iter_grouped` that yields Variables without metadata ### Response: def _iter_grouped_shortcut(self): """Fast version of `_iter_grouped` that yields Variables without metadata """ var = self._o...
def content(self, value): """ Setter for **self.__content** attribute. :param value: Attribute value. :type value: list """ if value is not None: assert type(value) is list, "'{0}' attribute: '{1}' type is not 'list'!".format("content", value) self._...
Setter for **self.__content** attribute. :param value: Attribute value. :type value: list
Below is the the instruction that describes the task: ### Input: Setter for **self.__content** attribute. :param value: Attribute value. :type value: list ### Response: def content(self, value): """ Setter for **self.__content** attribute. :param value: Attribute value. ...
def route_has_dead_links(root, machine): """Quickly determine if a route uses any dead links. Parameters ---------- root : :py:class:`~rig.place_and_route.routing_tree.RoutingTree` The root of the RoutingTree which contains nothing but RoutingTrees (i.e. no vertices and links). mach...
Quickly determine if a route uses any dead links. Parameters ---------- root : :py:class:`~rig.place_and_route.routing_tree.RoutingTree` The root of the RoutingTree which contains nothing but RoutingTrees (i.e. no vertices and links). machine : :py:class:`~rig.place_and_route.Machine` ...
Below is the the instruction that describes the task: ### Input: Quickly determine if a route uses any dead links. Parameters ---------- root : :py:class:`~rig.place_and_route.routing_tree.RoutingTree` The root of the RoutingTree which contains nothing but RoutingTrees (i.e. no vertices...
def _save(self, stateName, path): """save into 'stateName' to pyz-path""" print('saving...') state = {'session': dict(self.opts), 'dialogs': self.dialogs.saveState()} self.sigSave.emit(state) self.saveThread.prepare(stateName, path, self.tmp_dir_session...
save into 'stateName' to pyz-path
Below is the the instruction that describes the task: ### Input: save into 'stateName' to pyz-path ### Response: def _save(self, stateName, path): """save into 'stateName' to pyz-path""" print('saving...') state = {'session': dict(self.opts), 'dialogs': self.dialogs.s...
def _construct_production_name(glyph_name, data=None): """Return the production name for a glyph name from the GlyphData.xml database according to the AGL specification. This should be run only if there is no official entry with a production name in it. Handles single glyphs (e.g. "brevecomb") and...
Return the production name for a glyph name from the GlyphData.xml database according to the AGL specification. This should be run only if there is no official entry with a production name in it. Handles single glyphs (e.g. "brevecomb") and ligatures (e.g. "brevecomb_acutecomb"). Returns None when...
Below is the the instruction that describes the task: ### Input: Return the production name for a glyph name from the GlyphData.xml database according to the AGL specification. This should be run only if there is no official entry with a production name in it. Handles single glyphs (e.g. "brevecom...
def _from_derivatives(xi, yi, x, order=None, der=0, extrapolate=False): """ Convenience function for interpolate.BPoly.from_derivatives. Construct a piecewise polynomial in the Bernstein basis, compatible with the specified values and derivatives at breakpoints. Parameters ---------- xi : ...
Convenience function for interpolate.BPoly.from_derivatives. Construct a piecewise polynomial in the Bernstein basis, compatible with the specified values and derivatives at breakpoints. Parameters ---------- xi : array_like sorted 1D array of x-coordinates yi : array_like or list of a...
Below is the the instruction that describes the task: ### Input: Convenience function for interpolate.BPoly.from_derivatives. Construct a piecewise polynomial in the Bernstein basis, compatible with the specified values and derivatives at breakpoints. Parameters ---------- xi : array_like ...
def recoverString(self, strIndex, withIndex=False): ''' This will return the string that starts at the given index @param strIndex - the index of the string we want to recover @return - string that we found starting at the specified '$' index ''' retNums = [] indi...
This will return the string that starts at the given index @param strIndex - the index of the string we want to recover @return - string that we found starting at the specified '$' index
Below is the the instruction that describes the task: ### Input: This will return the string that starts at the given index @param strIndex - the index of the string we want to recover @return - string that we found starting at the specified '$' index ### Response: def recoverString(self, strIndex,...
def load_genotypes(self): """Prepares the files for genotype parsing. :return: None """ if self.file_index < len(self.archives): self.current_file = self.archives[self.file_index] info_filename = self.current_file.replace(Parser.gen_ext, Parser.info_ext) ...
Prepares the files for genotype parsing. :return: None
Below is the the instruction that describes the task: ### Input: Prepares the files for genotype parsing. :return: None ### Response: def load_genotypes(self): """Prepares the files for genotype parsing. :return: None """ if self.file_index < len(self.archives): ...
def setup_editorstack(self, parent, layout): """Setup editorstack's layout""" layout.setSpacing(1) self.fname_label = QLabel() self.fname_label.setStyleSheet( "QLabel {margin: 0px; padding: 3px;}") layout.addWidget(self.fname_label) menu_btn = creat...
Setup editorstack's layout
Below is the the instruction that describes the task: ### Input: Setup editorstack's layout ### Response: def setup_editorstack(self, parent, layout): """Setup editorstack's layout""" layout.setSpacing(1) self.fname_label = QLabel() self.fname_label.setStyleSheet( ...
def parse_options(arguments): """Parse command line arguments. The parsing logic is fairly simple. It can only parse long-style parameters of the form:: --key value Several parameters can be defined in the environment and will be used unless explicitly overridden with command-line argument...
Parse command line arguments. The parsing logic is fairly simple. It can only parse long-style parameters of the form:: --key value Several parameters can be defined in the environment and will be used unless explicitly overridden with command-line arguments. The access key, secret and en...
Below is the the instruction that describes the task: ### Input: Parse command line arguments. The parsing logic is fairly simple. It can only parse long-style parameters of the form:: --key value Several parameters can be defined in the environment and will be used unless explicitly overr...
def run_migrations_offline(): """Run migrations in 'offline' mode. This configures the context with just a URL and not an Engine, though an Engine is acceptable here as well. By skipping the Engine creation we don't even need a DBAPI to be available. Calls to context.execute() here emit the g...
Run migrations in 'offline' mode. This configures the context with just a URL and not an Engine, though an Engine is acceptable here as well. By skipping the Engine creation we don't even need a DBAPI to be available. Calls to context.execute() here emit the given string to the script output.
Below is the the instruction that describes the task: ### Input: Run migrations in 'offline' mode. This configures the context with just a URL and not an Engine, though an Engine is acceptable here as well. By skipping the Engine creation we don't even need a DBAPI to be available. Calls to c...
def decode_list(cls, obj, element_type): # type: (List[Any], ConjureTypeType) -> List[Any] """Decodes json into a list, handling conversion of the elements. Args: obj: the json object to decode element_type: a class object which is the conjure type of the...
Decodes json into a list, handling conversion of the elements. Args: obj: the json object to decode element_type: a class object which is the conjure type of the elements in this list. Returns: A python list where the elements are instances of type ...
Below is the the instruction that describes the task: ### Input: Decodes json into a list, handling conversion of the elements. Args: obj: the json object to decode element_type: a class object which is the conjure type of the elements in this list. Returns: ...
def add_and_rename_file(self, filename: str, new_filename: str) -> None: """ Copies the specified file into the working directory of this sandbox and renames it to new_filename. """ dest = os.path.join( self.name + ':' + SANDBOX_WORKING_DIR_NAME, new_filen...
Copies the specified file into the working directory of this sandbox and renames it to new_filename.
Below is the the instruction that describes the task: ### Input: Copies the specified file into the working directory of this sandbox and renames it to new_filename. ### Response: def add_and_rename_file(self, filename: str, new_filename: str) -> None: """ Copies the specified file into the...
def get_suppliers_per_page(self, per_page=1000, page=1, params=None): """ Get suppliers per page :param per_page: How many objects per page. Default: 1000 :param page: Which page. Default: 1 :param params: Search parameters. Default: {} :return: list """ ...
Get suppliers per page :param per_page: How many objects per page. Default: 1000 :param page: Which page. Default: 1 :param params: Search parameters. Default: {} :return: list
Below is the the instruction that describes the task: ### Input: Get suppliers per page :param per_page: How many objects per page. Default: 1000 :param page: Which page. Default: 1 :param params: Search parameters. Default: {} :return: list ### Response: def get_suppliers_per_page...
def detect_Massimini2004(dat_orig, s_freq, time, opts): """Slow wave detection based on Massimini et al., 2004. Parameters ---------- dat_orig : ndarray (dtype='float') vector with the data for one channel s_freq : float sampling frequency time : ndarray (dtype='float') ...
Slow wave detection based on Massimini et al., 2004. Parameters ---------- dat_orig : ndarray (dtype='float') vector with the data for one channel s_freq : float sampling frequency time : ndarray (dtype='float') vector with the time points for each sample opts : instance...
Below is the the instruction that describes the task: ### Input: Slow wave detection based on Massimini et al., 2004. Parameters ---------- dat_orig : ndarray (dtype='float') vector with the data for one channel s_freq : float sampling frequency time : ndarray (dtype='float') ...
def _edges2conns(G, edge_data=False): """Create a mapping from graph edges to agent connections to be created. :param G: NetworkX's Graph or DiGraph which has :attr:`addr` attribute for each node. :param bool edge_data: If ``True``, stores also edge data to the returned dictionary....
Create a mapping from graph edges to agent connections to be created. :param G: NetworkX's Graph or DiGraph which has :attr:`addr` attribute for each node. :param bool edge_data: If ``True``, stores also edge data to the returned dictionary. :returns: A dictionary where ke...
Below is the the instruction that describes the task: ### Input: Create a mapping from graph edges to agent connections to be created. :param G: NetworkX's Graph or DiGraph which has :attr:`addr` attribute for each node. :param bool edge_data: If ``True``, stores also edge data to ...
def operator_from_str(op): """ Return the operator associated to the given string `op`. raises: `KeyError` if invalid string. >>> assert operator_from_str("==")(1, 1) and operator_from_str("+")(1,1) == 2 """ d = {"==": operator.eq, "!=": operator.ne, ">": operator.gt,...
Return the operator associated to the given string `op`. raises: `KeyError` if invalid string. >>> assert operator_from_str("==")(1, 1) and operator_from_str("+")(1,1) == 2
Below is the the instruction that describes the task: ### Input: Return the operator associated to the given string `op`. raises: `KeyError` if invalid string. >>> assert operator_from_str("==")(1, 1) and operator_from_str("+")(1,1) == 2 ### Response: def operator_from_str(op): """ Return...
def update_roles_gce(use_cache=True, cache_expiration=86400, cache_path="~/.gcetools/instances", group_name=None, region=None, zone=None): """ Dynamically update fabric's roles by using assigning the tags associated with each machine in Google Compute Engine. use_cache - will store a local cache in ~/....
Dynamically update fabric's roles by using assigning the tags associated with each machine in Google Compute Engine. use_cache - will store a local cache in ~/.gcetools/ cache_expiration - cache expiration in seconds (default: 1 day) cache_path - the path to store instances data (default: ~/.gcetools/i...
Below is the the instruction that describes the task: ### Input: Dynamically update fabric's roles by using assigning the tags associated with each machine in Google Compute Engine. use_cache - will store a local cache in ~/.gcetools/ cache_expiration - cache expiration in seconds (default: 1 day) ...
def _load_file(self): """Load all entries from json backing file """ if not os.path.exists(self.file): return {} with open(self.file, "r") as infile: data = json.load(infile) return data
Load all entries from json backing file
Below is the the instruction that describes the task: ### Input: Load all entries from json backing file ### Response: def _load_file(self): """Load all entries from json backing file """ if not os.path.exists(self.file): return {} with open(self.file, "r") as infile: ...
def write_index_and_rst_files(self, overwrite: bool = False, mock: bool = False) -> None: """ Writes both the individual RST files and the index. Args: overwrite: allow existing files to be overwritten? mock: pretend to write, but don't ...
Writes both the individual RST files and the index. Args: overwrite: allow existing files to be overwritten? mock: pretend to write, but don't
Below is the the instruction that describes the task: ### Input: Writes both the individual RST files and the index. Args: overwrite: allow existing files to be overwritten? mock: pretend to write, but don't ### Response: def write_index_and_rst_files(self, overwrite: bool = False,...
def train(hparams, *args): """Train your awesome model. :param hparams: The arguments to run the model with. """ # Initialize experiments and track all the hyperparameters exp = Experiment( name=hparams.test_tube_exp_name, # Location to save the metrics. save_dir=hparams.log...
Train your awesome model. :param hparams: The arguments to run the model with.
Below is the the instruction that describes the task: ### Input: Train your awesome model. :param hparams: The arguments to run the model with. ### Response: def train(hparams, *args): """Train your awesome model. :param hparams: The arguments to run the model with. """ # Initialize experimen...
def learn(self, state_arr, limit=1000): ''' Learning and searching the optimal solution. Args: state_arr: `np.ndarray` of initial state. limit: The maximum number of iterative updates based on value iteration algorithms. ''' while se...
Learning and searching the optimal solution. Args: state_arr: `np.ndarray` of initial state. limit: The maximum number of iterative updates based on value iteration algorithms.
Below is the the instruction that describes the task: ### Input: Learning and searching the optimal solution. Args: state_arr: `np.ndarray` of initial state. limit: The maximum number of iterative updates based on value iteration algorithms. ### Response: def ...
def get_moments(model,x): ''' Moments (mean and sdev.) of a GP model at x ''' input_dim = model.X.shape[1] x = reshape(x,input_dim) fmin = min(model.predict(model.X)[0]) m, v = model.predict(x) s = np.sqrt(np.clip(v, 0, np.inf)) return (m,s, fmin)
Moments (mean and sdev.) of a GP model at x
Below is the the instruction that describes the task: ### Input: Moments (mean and sdev.) of a GP model at x ### Response: def get_moments(model,x): ''' Moments (mean and sdev.) of a GP model at x ''' input_dim = model.X.shape[1] x = reshape(x,input_dim) fmin = min(model.predict(model.X)[0...
def compress_multiple_pdfs(source_directory, output_directory, ghostscript_binary): """Compress all PDF files in the current directory and place the output in the given output directory. This is a generator function that first yields the amount of files to be compressed, and then yields the output path of e...
Compress all PDF files in the current directory and place the output in the given output directory. This is a generator function that first yields the amount of files to be compressed, and then yields the output path of each file. Args: source_directory (str): Filepath to the source directory. ...
Below is the the instruction that describes the task: ### Input: Compress all PDF files in the current directory and place the output in the given output directory. This is a generator function that first yields the amount of files to be compressed, and then yields the output path of each file. Args: ...
def _Complete(self): """Marks the hunt as completed.""" self._RemoveForemanRule() if "w" in self.hunt_obj.mode: self.hunt_obj.Set(self.hunt_obj.Schema.STATE("COMPLETED")) self.hunt_obj.Flush()
Marks the hunt as completed.
Below is the the instruction that describes the task: ### Input: Marks the hunt as completed. ### Response: def _Complete(self): """Marks the hunt as completed.""" self._RemoveForemanRule() if "w" in self.hunt_obj.mode: self.hunt_obj.Set(self.hunt_obj.Schema.STATE("COMPLETED")) self.hunt_ob...
def compose(self, to, subject, text): """Login required. Sends POST to send a message to a user. Returns True or raises :class:`exceptions.UnexpectedResponse` if non-"truthy" value in response. URL: ``http://www.reddit.com/api/compose/`` :param to: username or :class`things.A...
Login required. Sends POST to send a message to a user. Returns True or raises :class:`exceptions.UnexpectedResponse` if non-"truthy" value in response. URL: ``http://www.reddit.com/api/compose/`` :param to: username or :class`things.Account` of user to send to :param subject...
Below is the the instruction that describes the task: ### Input: Login required. Sends POST to send a message to a user. Returns True or raises :class:`exceptions.UnexpectedResponse` if non-"truthy" value in response. URL: ``http://www.reddit.com/api/compose/`` :param to: usernam...
def mob_suite_targets(self, database_name='mob_suite'): """ Download MOB-suite databases :param database_name: name of current database """ logging.info('Download MOB-suite databases') # NOTE: This requires mob_suite >=1.4.9.1. Versions before that don't have the -d optio...
Download MOB-suite databases :param database_name: name of current database
Below is the the instruction that describes the task: ### Input: Download MOB-suite databases :param database_name: name of current database ### Response: def mob_suite_targets(self, database_name='mob_suite'): """ Download MOB-suite databases :param database_name: name of current d...
def genstis(outname): """ Generate TestCases from cmdfile according to the pattern in patternfile""" pattern="""class stisS%d(countrateCase): def setUp(self): self.obsmode="%s" self.spectrum="%s" self.setglobal(__file__) self.runpy()\n""" speclist=['/grp/hst/cdbs/calspec...
Generate TestCases from cmdfile according to the pattern in patternfile
Below is the the instruction that describes the task: ### Input: Generate TestCases from cmdfile according to the pattern in patternfile ### Response: def genstis(outname): """ Generate TestCases from cmdfile according to the pattern in patternfile""" pattern="""class stisS%d(countrateCase): def setUp(...
def register_service(cls, service): """Add a service to the thread's StackInABox instance. :param service: StackInABoxService instance to add to the test For return value and errors see StackInABox.register() """ logger.debug('Registering service {0}'.format(service.name)) ...
Add a service to the thread's StackInABox instance. :param service: StackInABoxService instance to add to the test For return value and errors see StackInABox.register()
Below is the the instruction that describes the task: ### Input: Add a service to the thread's StackInABox instance. :param service: StackInABoxService instance to add to the test For return value and errors see StackInABox.register() ### Response: def register_service(cls, service): """A...
def set_color(self, value, callb=None, duration=0, rapid=False): """Convenience method to set the colour status of the device This method will send a LightSetColor message to the device, and request callb be executed when an ACK is received. The default callback will simply cache the value. ...
Convenience method to set the colour status of the device This method will send a LightSetColor message to the device, and request callb be executed when an ACK is received. The default callback will simply cache the value. :param value: The new state, a dictionary onf int with 4 keys Hue,...
Below is the the instruction that describes the task: ### Input: Convenience method to set the colour status of the device This method will send a LightSetColor message to the device, and request callb be executed when an ACK is received. The default callback will simply cache the value. ...
def check_deleted(session, rev_id, title=None, timestamp=None, radius=defaults.RADIUS, before=None, window=None, rvprop=None): """ Checks the revert status of a deleted revision. With this method, you can determine whether an edit is a 'reverting' edit, was 'reverted' by...
Checks the revert status of a deleted revision. With this method, you can determine whether an edit is a 'reverting' edit, was 'reverted' by another edit and/or was 'reverted_to' by another edit. :Parameters: session : :class:`mwapi.Session` An API session to make use of rev_id...
Below is the the instruction that describes the task: ### Input: Checks the revert status of a deleted revision. With this method, you can determine whether an edit is a 'reverting' edit, was 'reverted' by another edit and/or was 'reverted_to' by another edit. :Parameters: session : :class:`mw...
def nowarnings(func): """Create a function wrapped in a context that ignores warnings. """ @functools.wraps(func) def new_func(*args, **kwargs): with warnings.catch_warnings(): warnings.simplefilter('ignore') return func(*args, **kwargs) return new_func
Create a function wrapped in a context that ignores warnings.
Below is the the instruction that describes the task: ### Input: Create a function wrapped in a context that ignores warnings. ### Response: def nowarnings(func): """Create a function wrapped in a context that ignores warnings. """ @functools.wraps(func) def new_func(*args, **kwargs): with ...
def GetKernelParams(time, flux, errors, kernel='Basic', mask=[], giter=3, gmaxf=200, guess=None): ''' Optimizes the GP by training it on the current de-trended light curve. Returns the white noise amplitude, red noise amplitude, and red noise timescale. :param array_like time: T...
Optimizes the GP by training it on the current de-trended light curve. Returns the white noise amplitude, red noise amplitude, and red noise timescale. :param array_like time: The time array :param array_like flux: The flux array :param array_like errors: The flux errors array :param array_like...
Below is the the instruction that describes the task: ### Input: Optimizes the GP by training it on the current de-trended light curve. Returns the white noise amplitude, red noise amplitude, and red noise timescale. :param array_like time: The time array :param array_like flux: The flux array ...
def _sync_extract(self, from_path, method, to_path): """Returns `to_path` once resource has been extracted there.""" to_path_tmp = '%s%s_%s' % (to_path, constants.INCOMPLETE_SUFFIX, uuid.uuid4().hex) try: for path, handle in iter_archive(from_path, method): _copy...
Returns `to_path` once resource has been extracted there.
Below is the the instruction that describes the task: ### Input: Returns `to_path` once resource has been extracted there. ### Response: def _sync_extract(self, from_path, method, to_path): """Returns `to_path` once resource has been extracted there.""" to_path_tmp = '%s%s_%s' % (to_path, constants.INCOMPL...
def p_ConstValue_float(p): """ConstValue : FLOAT""" p[0] = model.Value(type=model.Value.FLOAT, value=p[1])
ConstValue : FLOAT
Below is the the instruction that describes the task: ### Input: ConstValue : FLOAT ### Response: def p_ConstValue_float(p): """ConstValue : FLOAT""" p[0] = model.Value(type=model.Value.FLOAT, value=p[1])
def transcripts(context, build, hgnc_id, json): """Show all transcripts in the database""" LOG.info("Running scout view transcripts") adapter = context.obj['adapter'] if not json: click.echo("Chromosome\tstart\tend\ttranscript_id\thgnc_id\trefseq\tis_primary") for tx_obj in adapter.transcri...
Show all transcripts in the database
Below is the the instruction that describes the task: ### Input: Show all transcripts in the database ### Response: def transcripts(context, build, hgnc_id, json): """Show all transcripts in the database""" LOG.info("Running scout view transcripts") adapter = context.obj['adapter'] if not json: ...
def _show_shortcuts(shortcuts, name=None): """Display shortcuts.""" name = name or '' print('') if name: name = ' for ' + name print('Keyboard shortcuts' + name) for name in sorted(shortcuts): shortcut = _get_shortcut_string(shortcuts[name]) if not name.startswith('_'): ...
Display shortcuts.
Below is the the instruction that describes the task: ### Input: Display shortcuts. ### Response: def _show_shortcuts(shortcuts, name=None): """Display shortcuts.""" name = name or '' print('') if name: name = ' for ' + name print('Keyboard shortcuts' + name) for name in sorted(shor...
def db_set_assoc(self, server_url, handle, secret, issued, lifetime, assoc_type): """ Set an association. This is implemented as a method because REPLACE INTO is not supported by PostgreSQL (and is not standard SQL). """ result = self.db_get_assoc(server_url, handle) ...
Set an association. This is implemented as a method because REPLACE INTO is not supported by PostgreSQL (and is not standard SQL).
Below is the the instruction that describes the task: ### Input: Set an association. This is implemented as a method because REPLACE INTO is not supported by PostgreSQL (and is not standard SQL). ### Response: def db_set_assoc(self, server_url, handle, secret, issued, lifetime, assoc_type): ...
def list_files(self, id=None, path="/"): """ List files in an allocation directory. https://www.nomadproject.io/docs/http/client-fs-ls.html arguments: - id - path returns: list raises: - nomad.api.exceptions.Bas...
List files in an allocation directory. https://www.nomadproject.io/docs/http/client-fs-ls.html arguments: - id - path returns: list raises: - nomad.api.exceptions.BaseNomadException - nomad.api.exceptions....
Below is the the instruction that describes the task: ### Input: List files in an allocation directory. https://www.nomadproject.io/docs/http/client-fs-ls.html arguments: - id - path returns: list raises: - nomad.ap...
def _TSKFileTimeCopyToStatTimeTuple(self, tsk_file, time_value): """Copies a SleuthKit file object time value to a stat timestamp tuple. Args: tsk_file (pytsk3.File): TSK file. time_value (str): name of the time value. Returns: tuple[int, int]: number of seconds since 1970-01-01 00:00:00...
Copies a SleuthKit file object time value to a stat timestamp tuple. Args: tsk_file (pytsk3.File): TSK file. time_value (str): name of the time value. Returns: tuple[int, int]: number of seconds since 1970-01-01 00:00:00 and fraction of second in 100 nano seconds intervals. The num...
Below is the the instruction that describes the task: ### Input: Copies a SleuthKit file object time value to a stat timestamp tuple. Args: tsk_file (pytsk3.File): TSK file. time_value (str): name of the time value. Returns: tuple[int, int]: number of seconds since 1970-01-01 00:00:00 an...