code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def stream(self, opNames=[], *args, **kwargs): """ Yield specific operations (e.g. comments) only :param array opNames: List of operations to filter for :param int start: Start at this block :param int stop: Stop at this block :param str mode: We here have the ch...
Yield specific operations (e.g. comments) only :param array opNames: List of operations to filter for :param int start: Start at this block :param int stop: Stop at this block :param str mode: We here have the choice between * "head": the last block ...
Below is the the instruction that describes the task: ### Input: Yield specific operations (e.g. comments) only :param array opNames: List of operations to filter for :param int start: Start at this block :param int stop: Stop at this block :param str mode: We here h...
def apparent_dip_correction(axes): """ Produces a two-dimensional rotation matrix that rotates a projected dataset to correct for apparent dip """ a1 = axes[0].copy() a1[-1] = 0 cosa = angle(axes[0],a1,cos=True) _ = 1-cosa**2 if _ > 1e-12: sina = N.sqrt(_) if cosa < 0...
Produces a two-dimensional rotation matrix that rotates a projected dataset to correct for apparent dip
Below is the the instruction that describes the task: ### Input: Produces a two-dimensional rotation matrix that rotates a projected dataset to correct for apparent dip ### Response: def apparent_dip_correction(axes): """ Produces a two-dimensional rotation matrix that rotates a projected dataset t...
def keybd_event(bVk: int, bScan: int, dwFlags: int, dwExtraInfo: int) -> None: """keybd_event from Win32.""" ctypes.windll.user32.keybd_event(bVk, bScan, dwFlags, dwExtraInfo)
keybd_event from Win32.
Below is the the instruction that describes the task: ### Input: keybd_event from Win32. ### Response: def keybd_event(bVk: int, bScan: int, dwFlags: int, dwExtraInfo: int) -> None: """keybd_event from Win32.""" ctypes.windll.user32.keybd_event(bVk, bScan, dwFlags, dwExtraInfo)
def _parse_document(self): """Parse system.profile doc, copy all values to member variables.""" self._reset() doc = self._profile_doc self._split_tokens_calculated = True self._split_tokens = None self._duration_calculated = True self._duration = doc[u'millis']...
Parse system.profile doc, copy all values to member variables.
Below is the the instruction that describes the task: ### Input: Parse system.profile doc, copy all values to member variables. ### Response: def _parse_document(self): """Parse system.profile doc, copy all values to member variables.""" self._reset() doc = self._profile_doc self....
def buildhtmlheader(self): """generate HTML header content""" #Highcharts lib/ needs to make sure it's up to date if self.drilldown_flag: self.add_JSsource('https://code.highcharts.com/maps/modules/drilldown.js') self.header_css = [ '<link href="%s" rel=...
generate HTML header content
Below is the the instruction that describes the task: ### Input: generate HTML header content ### Response: def buildhtmlheader(self): """generate HTML header content""" #Highcharts lib/ needs to make sure it's up to date if self.drilldown_flag: self.add_JSsource('https...
async def open_session(self, request: BaseRequestWebsocket) -> Session: """Open and return a Session using the request.""" return await ensure_coroutine(self.session_interface.open_session)(self, request)
Open and return a Session using the request.
Below is the the instruction that describes the task: ### Input: Open and return a Session using the request. ### Response: async def open_session(self, request: BaseRequestWebsocket) -> Session: """Open and return a Session using the request.""" return await ensure_coroutine(self.session_interface...
def clean_time(time_string): """Return a datetime from the Amazon-provided datetime string""" # Get a timezone-aware datetime object from the string time = dateutil.parser.parse(time_string) if not settings.USE_TZ: # If timezone support is not active, convert the time to UTC and # remove...
Return a datetime from the Amazon-provided datetime string
Below is the the instruction that describes the task: ### Input: Return a datetime from the Amazon-provided datetime string ### Response: def clean_time(time_string): """Return a datetime from the Amazon-provided datetime string""" # Get a timezone-aware datetime object from the string time = dateutil....
def SetFileAttributes(filepath, *attrs): """ Set file attributes. e.g.: SetFileAttributes('C:\\foo', 'hidden') Each attr must be either a numeric value, a constant defined in jaraco.windows.filesystem.api, or one of the nice names defined in this function. """ nice_names = collections.defaultdict( lambda k...
Set file attributes. e.g.: SetFileAttributes('C:\\foo', 'hidden') Each attr must be either a numeric value, a constant defined in jaraco.windows.filesystem.api, or one of the nice names defined in this function.
Below is the the instruction that describes the task: ### Input: Set file attributes. e.g.: SetFileAttributes('C:\\foo', 'hidden') Each attr must be either a numeric value, a constant defined in jaraco.windows.filesystem.api, or one of the nice names defined in this function. ### Response: def SetFileAttrib...
def _current_web_port(self): """ return just the port number for the web container, or None if not running """ info = inspect_container(self._get_container_name('web')) if info is None: return None try: if not info['State']['Running']: ...
return just the port number for the web container, or None if not running
Below is the the instruction that describes the task: ### Input: return just the port number for the web container, or None if not running ### Response: def _current_web_port(self): """ return just the port number for the web container, or None if not running """ inf...
def get_storer(self, key): """ return the storer object for a key, raise if not in the file """ group = self.get_node(key) if group is None: raise KeyError('No object named {key} in the file'.format(key=key)) s = self._create_storer(group) s.infer_axes() retu...
return the storer object for a key, raise if not in the file
Below is the the instruction that describes the task: ### Input: return the storer object for a key, raise if not in the file ### Response: def get_storer(self, key): """ return the storer object for a key, raise if not in the file """ group = self.get_node(key) if group is None: ...
def main(): """Main function calls the test functs""" print("Python version %s" % sys.version) print("Testing compatibility for function defined with *args") test_func_args(func_old_args) test_func_args(func_new) print("Testing compatibility for function defined with **kwargs") test_func_...
Main function calls the test functs
Below is the the instruction that describes the task: ### Input: Main function calls the test functs ### Response: def main(): """Main function calls the test functs""" print("Python version %s" % sys.version) print("Testing compatibility for function defined with *args") test_func_args(func_old_...
def CrearPlantillaPDF(self, papel="A4", orientacion="portrait"): "Iniciar la creación del archivo PDF" # genero el renderizador con propiedades del PDF t = Template( format=papel, orientation=orientacion, title="F 1116 B/C %s" % (self.NroOrden), ...
Iniciar la creación del archivo PDF
Below is the the instruction that describes the task: ### Input: Iniciar la creación del archivo PDF ### Response: def CrearPlantillaPDF(self, papel="A4", orientacion="portrait"): "Iniciar la creación del archivo PDF" # genero el renderizador con propiedades del PDF t = Template( ...
def safestr(value): '''Ensure type to string serialization''' if not value or isinstance(value, (int, float, bool, long)): return value elif isinstance(value, (date, datetime)): return value.isoformat() else: return unicode(value)
Ensure type to string serialization
Below is the the instruction that describes the task: ### Input: Ensure type to string serialization ### Response: def safestr(value): '''Ensure type to string serialization''' if not value or isinstance(value, (int, float, bool, long)): return value elif isinstance(value, (date, datetime)): ...
def get_comment_form_for_create(self, reference_id, comment_record_types): """Gets the comment form for creating new comments. A new form should be requested for each create transaction. arg: reference_id (osid.id.Id): the ``Id`` for the reference object arg: comm...
Gets the comment form for creating new comments. A new form should be requested for each create transaction. arg: reference_id (osid.id.Id): the ``Id`` for the reference object arg: comment_record_types (osid.type.Type[]): array of comment record types ...
Below is the the instruction that describes the task: ### Input: Gets the comment form for creating new comments. A new form should be requested for each create transaction. arg: reference_id (osid.id.Id): the ``Id`` for the reference object arg: comment_record_types ...
def gen_df_forcing( path_csv_in='SSss_YYYY_data_tt.csv', url_base=url_repo_input,)->pd.DataFrame: '''Generate description info of supy forcing data into a dataframe Parameters ---------- path_csv_in : str, optional path to the input csv file relative to url_base (the default is ...
Generate description info of supy forcing data into a dataframe Parameters ---------- path_csv_in : str, optional path to the input csv file relative to url_base (the default is '/input_files/SSss_YYYY_data_tt.csv']) url_base : urlpath.URL, optional URL to the input files of repo base (...
Below is the the instruction that describes the task: ### Input: Generate description info of supy forcing data into a dataframe Parameters ---------- path_csv_in : str, optional path to the input csv file relative to url_base (the default is '/input_files/SSss_YYYY_data_tt.csv']) url_base ...
def window_size(self): """ Returns: namedtuple: eg Size(width=320, height=568) """ value = self.http.get('/window/size').value w = roundint(value['width']) h = roundint(value['height']) return namedtuple('Size', ['width', 'height'])(w, ...
Returns: namedtuple: eg Size(width=320, height=568)
Below is the the instruction that describes the task: ### Input: Returns: namedtuple: eg Size(width=320, height=568) ### Response: def window_size(self): """ Returns: namedtuple: eg Size(width=320, height=568) """ value = self....
def p_const_vector_elem_list(p): """ const_number_list : expr """ if p[1] is None: return if not is_static(p[1]): if isinstance(p[1], symbols.UNARY): tmp = make_constexpr(p.lineno(1), p[1]) else: api.errmsg.syntax_error_not_constant(p.lexer.lineno) ...
const_number_list : expr
Below is the the instruction that describes the task: ### Input: const_number_list : expr ### Response: def p_const_vector_elem_list(p): """ const_number_list : expr """ if p[1] is None: return if not is_static(p[1]): if isinstance(p[1], symbols.UNARY): tmp = make_const...
def get_loss_func(self, C=1.0, k=1): """Get loss function of VAE. The loss value is equal to ELBO (Evidence Lower Bound) multiplied by -1. Args: C (int): Usually this is 1.0. Can be changed to control the second term of ELBO bound, which works as regularizat...
Get loss function of VAE. The loss value is equal to ELBO (Evidence Lower Bound) multiplied by -1. Args: C (int): Usually this is 1.0. Can be changed to control the second term of ELBO bound, which works as regularization. k (int): Number of Monte Carlo ...
Below is the the instruction that describes the task: ### Input: Get loss function of VAE. The loss value is equal to ELBO (Evidence Lower Bound) multiplied by -1. Args: C (int): Usually this is 1.0. Can be changed to control the second term of ELBO bound, which...
def send_request(self, kind, url_components, **kwargs): """ Send a request for this resource to the API Parameters ---------- kind: str, {'get', 'delete', 'put', 'post', 'head'} """ return self.api.send_request(kind, self.resource_path, url_components, ...
Send a request for this resource to the API Parameters ---------- kind: str, {'get', 'delete', 'put', 'post', 'head'}
Below is the the instruction that describes the task: ### Input: Send a request for this resource to the API Parameters ---------- kind: str, {'get', 'delete', 'put', 'post', 'head'} ### Response: def send_request(self, kind, url_components, **kwargs): """ Send a request fo...
def well(self, well_x=1, well_y=1): """ScanWellData of specific well. Parameters ---------- well_x : int well_y : int Returns ------- lxml.objectify.ObjectifiedElement """ xpath = './ScanWellData' xpath += _xpath_attrib('WellX', w...
ScanWellData of specific well. Parameters ---------- well_x : int well_y : int Returns ------- lxml.objectify.ObjectifiedElement
Below is the the instruction that describes the task: ### Input: ScanWellData of specific well. Parameters ---------- well_x : int well_y : int Returns ------- lxml.objectify.ObjectifiedElement ### Response: def well(self, well_x=1, well_y=1): """Sc...
def _low_level_dispatch(pcapdev, devname, pktqueue): ''' Thread entrypoint for doing low-level receive and dispatch for a single pcap device. ''' while LLNetReal.running: # a non-zero timeout value is ok here; this is an # independent thread that handles i...
Thread entrypoint for doing low-level receive and dispatch for a single pcap device.
Below is the the instruction that describes the task: ### Input: Thread entrypoint for doing low-level receive and dispatch for a single pcap device. ### Response: def _low_level_dispatch(pcapdev, devname, pktqueue): ''' Thread entrypoint for doing low-level receive and dispatch for...
def fix_encoding_and_explain(text): """ Re-decodes text that has been decoded incorrectly, and also return a "plan" indicating all the steps required to fix it. The resulting plan could be used with :func:`ftfy.fixes.apply_plan` to fix additional strings that are broken in the same way. """ ...
Re-decodes text that has been decoded incorrectly, and also return a "plan" indicating all the steps required to fix it. The resulting plan could be used with :func:`ftfy.fixes.apply_plan` to fix additional strings that are broken in the same way.
Below is the the instruction that describes the task: ### Input: Re-decodes text that has been decoded incorrectly, and also return a "plan" indicating all the steps required to fix it. The resulting plan could be used with :func:`ftfy.fixes.apply_plan` to fix additional strings that are broken in the ...
def washburn(target, surface_tension='pore.surface_tension', contact_angle='pore.contact_angle', diameter='throat.diameter'): r""" Computes the capillary entry pressure assuming the throat in a cylindrical tube. Parameters ---------- target : OpenPNM Object The...
r""" Computes the capillary entry pressure assuming the throat in a cylindrical tube. Parameters ---------- target : OpenPNM Object The object for which these values are being calculated. This controls the length of the calculated array, and also provides access to other ne...
Below is the the instruction that describes the task: ### Input: r""" Computes the capillary entry pressure assuming the throat in a cylindrical tube. Parameters ---------- target : OpenPNM Object The object for which these values are being calculated. This controls the length ...
def _group_get_hostnames(self, group_name): """ Recursively fetch a list of each unique hostname that belongs in or under the group. This includes hosts in children groups. """ hostnames = [] hosts_section = self._get_section(group_name, 'hosts') if hosts_section...
Recursively fetch a list of each unique hostname that belongs in or under the group. This includes hosts in children groups.
Below is the the instruction that describes the task: ### Input: Recursively fetch a list of each unique hostname that belongs in or under the group. This includes hosts in children groups. ### Response: def _group_get_hostnames(self, group_name): """ Recursively fetch a list of each unique...
def preprocess_belscript(lines): """ Convert any multi-line SET statements into single line SET statements""" set_flag = False for line in lines: if set_flag is False and re.match("SET", line): set_flag = True set_line = [line.rstrip()] # SET following SET el...
Convert any multi-line SET statements into single line SET statements
Below is the the instruction that describes the task: ### Input: Convert any multi-line SET statements into single line SET statements ### Response: def preprocess_belscript(lines): """ Convert any multi-line SET statements into single line SET statements""" set_flag = False for line in lines: ...
def get_jamo_class(jamo): """Determine if a jamo character is a lead, vowel, or tail. Integers and U+11xx characters are valid arguments. HCJ consonants are not valid here. get_jamo_class should return the class ["lead" | "vowel" | "tail"] of a given character or integer. Note: jamo class dire...
Determine if a jamo character is a lead, vowel, or tail. Integers and U+11xx characters are valid arguments. HCJ consonants are not valid here. get_jamo_class should return the class ["lead" | "vowel" | "tail"] of a given character or integer. Note: jamo class directly corresponds to the Unicode 7...
Below is the the instruction that describes the task: ### Input: Determine if a jamo character is a lead, vowel, or tail. Integers and U+11xx characters are valid arguments. HCJ consonants are not valid here. get_jamo_class should return the class ["lead" | "vowel" | "tail"] of a given character or...
def upload_file(self, simple_upload_url, chunked_upload_url, file_obj, chunk_size=CHUNK_SIZE, force_chunked=False, extra_data=None): """ Generic method to upload files to AmigoCloud. Can be used for different API endpoints. `file_obj` could be a fi...
Generic method to upload files to AmigoCloud. Can be used for different API endpoints. `file_obj` could be a file-like object or a filepath. If the size of the file is greater than MAX_SIZE_SIMPLE_UPLOAD (8MB) `chunked_upload_url` will be used, otherwise `simple_upload_url` will ...
Below is the the instruction that describes the task: ### Input: Generic method to upload files to AmigoCloud. Can be used for different API endpoints. `file_obj` could be a file-like object or a filepath. If the size of the file is greater than MAX_SIZE_SIMPLE_UPLOAD (8MB) `chunked_...
def daily_forecast_at_coords(self, lat, lon, limit=None): """ Queries the OWM Weather API for daily weather forecast for the specified geographic coordinate (eg: latitude: 51.5073509, longitude: -0.1277583). A *Forecaster* object is returned, containing a *Forecast* instance cove...
Queries the OWM Weather API for daily weather forecast for the specified geographic coordinate (eg: latitude: 51.5073509, longitude: -0.1277583). A *Forecaster* object is returned, containing a *Forecast* instance covering a global streak of fourteen days by default: this instance encaps...
Below is the the instruction that describes the task: ### Input: Queries the OWM Weather API for daily weather forecast for the specified geographic coordinate (eg: latitude: 51.5073509, longitude: -0.1277583). A *Forecaster* object is returned, containing a *Forecast* instance covering a gl...
def perform_extended_selection(self, event=None): """ Performs extended word selection. :param event: QMouseEvent """ TextHelper(self.editor).select_extended_word( continuation_chars=self.continuation_characters) if event: event.accept()
Performs extended word selection. :param event: QMouseEvent
Below is the the instruction that describes the task: ### Input: Performs extended word selection. :param event: QMouseEvent ### Response: def perform_extended_selection(self, event=None): """ Performs extended word selection. :param event: QMouseEvent """ TextHelper...
def p_delays_floatnumber(self, p): 'delays : DELAY floatnumber' p[0] = DelayStatement(FloatConst( p[2], lineno=p.lineno(1)), lineno=p.lineno(1)) p.set_lineno(0, p.lineno(1))
delays : DELAY floatnumber
Below is the the instruction that describes the task: ### Input: delays : DELAY floatnumber ### Response: def p_delays_floatnumber(self, p): 'delays : DELAY floatnumber' p[0] = DelayStatement(FloatConst( p[2], lineno=p.lineno(1)), lineno=p.lineno(1)) p.set_lineno(0, p.lineno(1))
def _is_builtin_module(module): """Is builtin or part of standard library """ if (not hasattr(module, '__file__')) or module.__name__ in sys.builtin_module_names: return True if module.__name__ in _stdlib._STD_LIB_MODULES: return True amp = os.path.abspath(module.__file__) if 's...
Is builtin or part of standard library
Below is the the instruction that describes the task: ### Input: Is builtin or part of standard library ### Response: def _is_builtin_module(module): """Is builtin or part of standard library """ if (not hasattr(module, '__file__')) or module.__name__ in sys.builtin_module_names: return True ...
def services(doc): """View for getting services""" for service_id, service in doc.get('services', {}).items(): service_type = service.get('service_type') org = doc['_id'] service['id'] = service_id service['organisation_id'] = org yield service_id, service yield ...
View for getting services
Below is the the instruction that describes the task: ### Input: View for getting services ### Response: def services(doc): """View for getting services""" for service_id, service in doc.get('services', {}).items(): service_type = service.get('service_type') org = doc['_id'] service...
def get_checksum32(oqparam, hazard=False): """ Build an unsigned 32 bit integer from the input files of a calculation. :param oqparam: an OqParam instance :param hazard: if True, consider only the hazard files :returns: the checkume """ # NB: using adler32 & 0xffffffff is the documented way...
Build an unsigned 32 bit integer from the input files of a calculation. :param oqparam: an OqParam instance :param hazard: if True, consider only the hazard files :returns: the checkume
Below is the the instruction that describes the task: ### Input: Build an unsigned 32 bit integer from the input files of a calculation. :param oqparam: an OqParam instance :param hazard: if True, consider only the hazard files :returns: the checkume ### Response: def get_checksum32(oqparam, hazard=Fa...
def traverse(self, node): """Traverse the document tree rooted at node. node : docutil node current root node to traverse """ old_level = self.current_level if isinstance(node, nodes.section): if 'level' in node: self.current_level = node[...
Traverse the document tree rooted at node. node : docutil node current root node to traverse
Below is the the instruction that describes the task: ### Input: Traverse the document tree rooted at node. node : docutil node current root node to traverse ### Response: def traverse(self, node): """Traverse the document tree rooted at node. node : docutil node c...
def get_closest(cls, *locale_codes: str) -> "Locale": """Returns the closest match for the given locale code.""" for code in locale_codes: if not code: continue code = code.replace("-", "_") parts = code.split("_") if len(parts) > 2: ...
Returns the closest match for the given locale code.
Below is the the instruction that describes the task: ### Input: Returns the closest match for the given locale code. ### Response: def get_closest(cls, *locale_codes: str) -> "Locale": """Returns the closest match for the given locale code.""" for code in locale_codes: if not code: ...
def ParseFileSystemsStruct(struct_class, fs_count, data): """Take the struct type and parse it into a list of structs.""" results = [] cstr = lambda x: x.split(b"\x00", 1)[0] for count in range(0, fs_count): struct_size = struct_class.GetSize() s_data = data[count * struct_size:(count + 1) * struct_size...
Take the struct type and parse it into a list of structs.
Below is the the instruction that describes the task: ### Input: Take the struct type and parse it into a list of structs. ### Response: def ParseFileSystemsStruct(struct_class, fs_count, data): """Take the struct type and parse it into a list of structs.""" results = [] cstr = lambda x: x.split(b"\x00", 1)[...
def dumps_content(self): """Return a string representing the matrix in LaTeX syntax. Returns ------- str """ import numpy as np string = '' shape = self.matrix.shape for (y, x), value in np.ndenumerate(self.matrix): if x: ...
Return a string representing the matrix in LaTeX syntax. Returns ------- str
Below is the the instruction that describes the task: ### Input: Return a string representing the matrix in LaTeX syntax. Returns ------- str ### Response: def dumps_content(self): """Return a string representing the matrix in LaTeX syntax. Returns ------- ...
def diff(left, right): """ Take two VCALENDAR components, compare VEVENTs and VTODOs in them, return a list of object pairs containing just UID and the bits that didn't match, using None for objects that weren't present in one version or the other. When there are multiple ContentLines in one VE...
Take two VCALENDAR components, compare VEVENTs and VTODOs in them, return a list of object pairs containing just UID and the bits that didn't match, using None for objects that weren't present in one version or the other. When there are multiple ContentLines in one VEVENT, for instance many DESCRIP...
Below is the the instruction that describes the task: ### Input: Take two VCALENDAR components, compare VEVENTs and VTODOs in them, return a list of object pairs containing just UID and the bits that didn't match, using None for objects that weren't present in one version or the other. When there a...
def get_platform_info(): """Gets platform info :return: platform info """ try: system_name = platform.system() release_name = platform.release() except: system_name = "Unknown" release_name = "Unknown" return { ...
Gets platform info :return: platform info
Below is the the instruction that describes the task: ### Input: Gets platform info :return: platform info ### Response: def get_platform_info(): """Gets platform info :return: platform info """ try: system_name = platform.system() release_name = p...
def merge(self, other_rel): """ Ingest another DistributedReliability and add its contents to the current object. Args: other_rel: a Distributed reliability object. """ if other_rel.thresholds.size == self.thresholds.size and np.all(other_rel.thresholds == self.thres...
Ingest another DistributedReliability and add its contents to the current object. Args: other_rel: a Distributed reliability object.
Below is the the instruction that describes the task: ### Input: Ingest another DistributedReliability and add its contents to the current object. Args: other_rel: a Distributed reliability object. ### Response: def merge(self, other_rel): """ Ingest another DistributedReliabil...
def emailComment(comment, obj, request): """Send an email to the author about a new comment""" if not obj.author.frog_prefs.get().json()['emailComments']: return if obj.author == request.user: return html = render_to_string('frog/comment_email.html', { 'user': comment.user, ...
Send an email to the author about a new comment
Below is the the instruction that describes the task: ### Input: Send an email to the author about a new comment ### Response: def emailComment(comment, obj, request): """Send an email to the author about a new comment""" if not obj.author.frog_prefs.get().json()['emailComments']: return if ob...
def _hole_end(self, position, ignore=None): """ Retrieves the end of hole index from position. :param position: :type position: :param ignore: :type ignore: :return: :rtype: """ for rindex in range(position, self.max_end): for s...
Retrieves the end of hole index from position. :param position: :type position: :param ignore: :type ignore: :return: :rtype:
Below is the the instruction that describes the task: ### Input: Retrieves the end of hole index from position. :param position: :type position: :param ignore: :type ignore: :return: :rtype: ### Response: def _hole_end(self, position, ignore=None): """ ...
def run(self, input): """Runs :attr:`executable` with ``input`` as stdin. :class:`AssetHandlerError` exception is raised, if execution is failed, otherwise stdout is returned. """ p = self.get_process() output, errors = p.communicate(input=input.encode('utf-8')) i...
Runs :attr:`executable` with ``input`` as stdin. :class:`AssetHandlerError` exception is raised, if execution is failed, otherwise stdout is returned.
Below is the the instruction that describes the task: ### Input: Runs :attr:`executable` with ``input`` as stdin. :class:`AssetHandlerError` exception is raised, if execution is failed, otherwise stdout is returned. ### Response: def run(self, input): """Runs :attr:`executable` with ``input...
def check( state_engine, nameop, block_id, checked_ops ): """ Given a NAMESPACE_PREORDER nameop, see if we can preorder it. It must be unqiue. Return True if accepted. Return False if not. """ namespace_id_hash = nameop['preorder_hash'] consensus_hash = nameop['consensus_hash'] tok...
Given a NAMESPACE_PREORDER nameop, see if we can preorder it. It must be unqiue. Return True if accepted. Return False if not.
Below is the the instruction that describes the task: ### Input: Given a NAMESPACE_PREORDER nameop, see if we can preorder it. It must be unqiue. Return True if accepted. Return False if not. ### Response: def check( state_engine, nameop, block_id, checked_ops ): """ Given a NAMESPACE_PREORDER...
def opt_pagesize(self, pagesize): """ Get or set the page size of the query output """ if pagesize != "auto": pagesize = int(pagesize) self.conf["pagesize"] = pagesize
Get or set the page size of the query output
Below is the the instruction that describes the task: ### Input: Get or set the page size of the query output ### Response: def opt_pagesize(self, pagesize): """ Get or set the page size of the query output """ if pagesize != "auto": pagesize = int(pagesize) self.conf["pagesize"...
def swarm(self, predictedField=None, swarmParams=None): """ Runs a swarm on data and swarm description found within the given working directory. If no predictedField is provided, it is assumed that the first stream listed in the streamIds provided to the Menorah constructor is the predicted fi...
Runs a swarm on data and swarm description found within the given working directory. If no predictedField is provided, it is assumed that the first stream listed in the streamIds provided to the Menorah constructor is the predicted field. :param predictedField: (string) :param swarmParams...
Below is the the instruction that describes the task: ### Input: Runs a swarm on data and swarm description found within the given working directory. If no predictedField is provided, it is assumed that the first stream listed in the streamIds provided to the Menorah constructor is the predicted f...
def create_button_label(icon, font_size=constants.FONT_SIZE_NORMAL): """Create a button label with a chosen icon. :param icon: The icon :param font_size: The size of the icon :return: The created label """ label = Gtk.Label() set_label_markup(label, '&#x' + icon + ';', constants.ICON_FONT, ...
Create a button label with a chosen icon. :param icon: The icon :param font_size: The size of the icon :return: The created label
Below is the the instruction that describes the task: ### Input: Create a button label with a chosen icon. :param icon: The icon :param font_size: The size of the icon :return: The created label ### Response: def create_button_label(icon, font_size=constants.FONT_SIZE_NORMAL): """Create a button l...
def draw(self, label, expire): """ Return a Serial number for this resource queue, after bootstrapping. """ # get next number with self.client.pipeline() as pipe: pipe.msetnx({self.keys.dispenser: 0, self.keys.indicator: 1}) pipe.incr(self.keys.dispenser) ...
Return a Serial number for this resource queue, after bootstrapping.
Below is the the instruction that describes the task: ### Input: Return a Serial number for this resource queue, after bootstrapping. ### Response: def draw(self, label, expire): """ Return a Serial number for this resource queue, after bootstrapping. """ # get next number w...
def highlight(self, rect, color="red", seconds=None): """ Simulates a transparent rectangle over the specified ``rect`` on the screen. Actually takes a screenshot of the region and displays with a rectangle border in a borderless window (due to Tkinter limitations) If a Tkinter root wi...
Simulates a transparent rectangle over the specified ``rect`` on the screen. Actually takes a screenshot of the region and displays with a rectangle border in a borderless window (due to Tkinter limitations) If a Tkinter root window has already been created somewhere else, uses that in...
Below is the the instruction that describes the task: ### Input: Simulates a transparent rectangle over the specified ``rect`` on the screen. Actually takes a screenshot of the region and displays with a rectangle border in a borderless window (due to Tkinter limitations) If a Tkinter root...
def img(self): '''return a cv image for the icon''' SlipThumbnail.img(self) if self.rotation: # rotate the image mat = cv2.getRotationMatrix2D((self.height//2, self.width//2), -self.rotation, 1.0) self._rotated = cv2.warpAffine(self._img, mat, (self.height, s...
return a cv image for the icon
Below is the the instruction that describes the task: ### Input: return a cv image for the icon ### Response: def img(self): '''return a cv image for the icon''' SlipThumbnail.img(self) if self.rotation: # rotate the image mat = cv2.getRotationMatrix2D((self.height/...
def _proxy(self): """ Generate an instance context for the instance, the context is capable of performing various actions. All instance actions are proxied to the context :returns: TerminatingSipDomainContext for this TerminatingSipDomainInstance :rtype: twilio.rest.trunking.v1...
Generate an instance context for the instance, the context is capable of performing various actions. All instance actions are proxied to the context :returns: TerminatingSipDomainContext for this TerminatingSipDomainInstance :rtype: twilio.rest.trunking.v1.trunk.terminating_sip_domain.Terminat...
Below is the the instruction that describes the task: ### Input: Generate an instance context for the instance, the context is capable of performing various actions. All instance actions are proxied to the context :returns: TerminatingSipDomainContext for this TerminatingSipDomainInstance ...
def fft(a, n=None, axis=-1, norm=None): """ Compute the one-dimensional discrete Fourier Transform. This function computes the one-dimensional *n*-point discrete Fourier Transform (DFT) with the efficient Fast Fourier Transform (FFT) algorithm [CT]. Parameters ---------- a : array_like...
Compute the one-dimensional discrete Fourier Transform. This function computes the one-dimensional *n*-point discrete Fourier Transform (DFT) with the efficient Fast Fourier Transform (FFT) algorithm [CT]. Parameters ---------- a : array_like Input array, can be complex. n : int, o...
Below is the the instruction that describes the task: ### Input: Compute the one-dimensional discrete Fourier Transform. This function computes the one-dimensional *n*-point discrete Fourier Transform (DFT) with the efficient Fast Fourier Transform (FFT) algorithm [CT]. Parameters ---------- ...
def render_cheetah_tmpl(tmplstr, context, tmplpath=None): ''' Render a Cheetah template. ''' from Cheetah.Template import Template return salt.utils.data.decode(Template(tmplstr, searchList=[context]))
Render a Cheetah template.
Below is the the instruction that describes the task: ### Input: Render a Cheetah template. ### Response: def render_cheetah_tmpl(tmplstr, context, tmplpath=None): ''' Render a Cheetah template. ''' from Cheetah.Template import Template return salt.utils.data.decode(Template(tmplstr, searchList...
def appendData(self, content): """ Add characters to the element's pcdata. """ if self.pcdata is not None: self.pcdata += content else: self.pcdata = content
Add characters to the element's pcdata.
Below is the the instruction that describes the task: ### Input: Add characters to the element's pcdata. ### Response: def appendData(self, content): """ Add characters to the element's pcdata. """ if self.pcdata is not None: self.pcdata += content else: self.pcdata = content
def _zforce(self,R,z,phi=0.,t=0.): """ NAME: _zforce PURPOSE: evaluate the vertical force for this potential INPUT: R - Galactocentric cylindrical radius z - vertical height phi - azimuth t - time OUTPUT: ...
NAME: _zforce PURPOSE: evaluate the vertical force for this potential INPUT: R - Galactocentric cylindrical radius z - vertical height phi - azimuth t - time OUTPUT: the vertical force HISTORY: 2011-0...
Below is the the instruction that describes the task: ### Input: NAME: _zforce PURPOSE: evaluate the vertical force for this potential INPUT: R - Galactocentric cylindrical radius z - vertical height phi - azimuth t - time OUT...
def header_body_from_content(content): """\ Tries to extract the header and the message from the cable content. The header is something like UNCLASSIFIED ... SUBJECT ... REF ... while the message begins usually with a summary 1. SUMMARY ... ... 10. ......
\ Tries to extract the header and the message from the cable content. The header is something like UNCLASSIFIED ... SUBJECT ... REF ... while the message begins usually with a summary 1. SUMMARY ... ... 10. ... Returns (header, msg) or (None, None...
Below is the the instruction that describes the task: ### Input: \ Tries to extract the header and the message from the cable content. The header is something like UNCLASSIFIED ... SUBJECT ... REF ... while the message begins usually with a summary 1. SUMMARY ... ...
def parallel_apply(func, arg_iterable, **kwargs): """Apply function to iterable with parallelisation and a tqdm progress bar. Roughly equivalent to >>> [func(*func_pre_args, x, *func_args, **func_kwargs) for x in arg_iterable] but will **not** necessarily return results in input order. ...
Apply function to iterable with parallelisation and a tqdm progress bar. Roughly equivalent to >>> [func(*func_pre_args, x, *func_args, **func_kwargs) for x in arg_iterable] but will **not** necessarily return results in input order. Parameters ---------- func: function Func...
Below is the the instruction that describes the task: ### Input: Apply function to iterable with parallelisation and a tqdm progress bar. Roughly equivalent to >>> [func(*func_pre_args, x, *func_args, **func_kwargs) for x in arg_iterable] but will **not** necessarily return results in input ...
def remove_masquerade(zone=None, permanent=True): ''' Remove masquerade on a zone. If zone is omitted, default zone will be used. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' firewalld.remove_masquerade To remove masquerade on a specific zone .. cod...
Remove masquerade on a zone. If zone is omitted, default zone will be used. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' firewalld.remove_masquerade To remove masquerade on a specific zone .. code-block:: bash salt '*' firewalld.remove_masquerade d...
Below is the the instruction that describes the task: ### Input: Remove masquerade on a zone. If zone is omitted, default zone will be used. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' firewalld.remove_masquerade To remove masquerade on a specific zone ...
def get_page_full_export(self, page_id): """ Get full page info for export and body html code """ try: result = self._request('/getpagefullexport/', {'pageid': page_id}) return TildaPage(**result) except NetworkError: return ...
Get full page info for export and body html code
Below is the the instruction that describes the task: ### Input: Get full page info for export and body html code ### Response: def get_page_full_export(self, page_id): """ Get full page info for export and body html code """ try: result = self._request('/getpagefullexport/', ...
def elemc(item, inset): """ Determine whether an item is an element of a character set. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/elemc_c.html :param item: Item to be tested. :type item: str :param inset: Set to be tested. :type inset: spiceypy.utils.support_types.SpiceCell ...
Determine whether an item is an element of a character set. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/elemc_c.html :param item: Item to be tested. :type item: str :param inset: Set to be tested. :type inset: spiceypy.utils.support_types.SpiceCell :return: True if item is an eleme...
Below is the the instruction that describes the task: ### Input: Determine whether an item is an element of a character set. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/elemc_c.html :param item: Item to be tested. :type item: str :param inset: Set to be tested. :type inset: spiceyp...
def override_root_main_ref(config, remotes, banner): """Override root_ref or banner_main_ref with tags in config if user requested. :param sphinxcontrib.versioning.lib.Config config: Runtime configuration. :param iter remotes: List of dicts from Versions.remotes. :param bool banner: Evaluate banner mai...
Override root_ref or banner_main_ref with tags in config if user requested. :param sphinxcontrib.versioning.lib.Config config: Runtime configuration. :param iter remotes: List of dicts from Versions.remotes. :param bool banner: Evaluate banner main ref instead of root ref. :return: If root/main ref ex...
Below is the the instruction that describes the task: ### Input: Override root_ref or banner_main_ref with tags in config if user requested. :param sphinxcontrib.versioning.lib.Config config: Runtime configuration. :param iter remotes: List of dicts from Versions.remotes. :param bool banner: Evaluate b...
def get_object(model, meteor_id, *args, **kwargs): """Return an object for the given meteor_id.""" # Django model._meta is now public API -> pylint: disable=W0212 meta = model._meta if isinstance(meta.pk, AleaIdField): # meteor_id is the primary key return model.objects.filter(*args, **k...
Return an object for the given meteor_id.
Below is the the instruction that describes the task: ### Input: Return an object for the given meteor_id. ### Response: def get_object(model, meteor_id, *args, **kwargs): """Return an object for the given meteor_id.""" # Django model._meta is now public API -> pylint: disable=W0212 meta = model._meta ...
def GetTransactionResults(self): """ Get the execution results of the transaction. Returns: None: if the transaction has no references. list: of TransactionResult objects. """ if self.References is None: return None results = [] ...
Get the execution results of the transaction. Returns: None: if the transaction has no references. list: of TransactionResult objects.
Below is the the instruction that describes the task: ### Input: Get the execution results of the transaction. Returns: None: if the transaction has no references. list: of TransactionResult objects. ### Response: def GetTransactionResults(self): """ Get the executi...
def to_pydatetime(self): """ Converts datetime2 object into Python's datetime.datetime object @return: naive datetime.datetime """ return datetime.datetime.combine(self._date.to_pydate(), self._time.to_pytime())
Converts datetime2 object into Python's datetime.datetime object @return: naive datetime.datetime
Below is the the instruction that describes the task: ### Input: Converts datetime2 object into Python's datetime.datetime object @return: naive datetime.datetime ### Response: def to_pydatetime(self): """ Converts datetime2 object into Python's datetime.datetime object @return: nai...
def schemaValidateDoc(self, ctxt): """Validate a document tree in memory. """ if ctxt is None: ctxt__o = None else: ctxt__o = ctxt._o ret = libxml2mod.xmlSchemaValidateDoc(ctxt__o, self._o) return ret
Validate a document tree in memory.
Below is the the instruction that describes the task: ### Input: Validate a document tree in memory. ### Response: def schemaValidateDoc(self, ctxt): """Validate a document tree in memory. """ if ctxt is None: ctxt__o = None else: ctxt__o = ctxt._o ret = libxml2mod.xmlSchemaValidate...
def _apply_axis_properties(self, axis, rot=None, fontsize=None): """ Tick creation within matplotlib is reasonably expensive and is internally deferred until accessed as Ticks are created/destroyed multiple times per draw. It's therefore beneficial for us to avoid accessing u...
Tick creation within matplotlib is reasonably expensive and is internally deferred until accessed as Ticks are created/destroyed multiple times per draw. It's therefore beneficial for us to avoid accessing unless we will act on the Tick.
Below is the the instruction that describes the task: ### Input: Tick creation within matplotlib is reasonably expensive and is internally deferred until accessed as Ticks are created/destroyed multiple times per draw. It's therefore beneficial for us to avoid accessing unless we...
def convolutional_layer_series(initial_size, layer_sequence): """ Execute a series of convolutional layer transformations to the size number """ size = initial_size for filter_size, padding, stride in layer_sequence: size = convolution_size_equation(size, filter_size, padding, stride) return s...
Execute a series of convolutional layer transformations to the size number
Below is the the instruction that describes the task: ### Input: Execute a series of convolutional layer transformations to the size number ### Response: def convolutional_layer_series(initial_size, layer_sequence): """ Execute a series of convolutional layer transformations to the size number """ size = i...
def error(self, message): """Prints error message, then help.""" sys.stderr.write('error: %s\n\n' % message) self.print_help() sys.exit(2)
Prints error message, then help.
Below is the the instruction that describes the task: ### Input: Prints error message, then help. ### Response: def error(self, message): """Prints error message, then help.""" sys.stderr.write('error: %s\n\n' % message) self.print_help() sys.exit(2)
def mb_handler(self, args): '''Handler for mb command''' if len(args) == 1: raise InvalidArgument('No s3 bucketname provided') self.validate('cmd|s3', args) self.s3handler().create_bucket(args[1])
Handler for mb command
Below is the the instruction that describes the task: ### Input: Handler for mb command ### Response: def mb_handler(self, args): '''Handler for mb command''' if len(args) == 1: raise InvalidArgument('No s3 bucketname provided') self.validate('cmd|s3', args) self.s3handler().create_bucket(ar...
def _periodicfeatures_worker(task): ''' This is a parallel worker for the drivers below. ''' pfpickle, lcbasedir, outdir, starfeatures, kwargs = task try: return get_periodicfeatures(pfpickle, lcbasedir, outdir, ...
This is a parallel worker for the drivers below.
Below is the the instruction that describes the task: ### Input: This is a parallel worker for the drivers below. ### Response: def _periodicfeatures_worker(task): ''' This is a parallel worker for the drivers below. ''' pfpickle, lcbasedir, outdir, starfeatures, kwargs = task try: ...
def from_object(self, instance: Union[object, str]) -> None: """Load the configuration from a Python object. This can be used to reference modules or objects within modules for example, .. code-block:: python app.config.from_object('module') app.config.from_obj...
Load the configuration from a Python object. This can be used to reference modules or objects within modules for example, .. code-block:: python app.config.from_object('module') app.config.from_object('module.instance') from module import instance ...
Below is the the instruction that describes the task: ### Input: Load the configuration from a Python object. This can be used to reference modules or objects within modules for example, .. code-block:: python app.config.from_object('module') app.config.from_object...
def registry_adapter(obj, request): """ Adapter for rendering a :class:`pyramid_urireferencer.models.RegistryResponse` to json. :param pyramid_urireferencer.models.RegistryResponse obj: The response to be rendered. :rtype: :class:`dict` """ return { 'query_uri': obj.query_uri, '...
Adapter for rendering a :class:`pyramid_urireferencer.models.RegistryResponse` to json. :param pyramid_urireferencer.models.RegistryResponse obj: The response to be rendered. :rtype: :class:`dict`
Below is the the instruction that describes the task: ### Input: Adapter for rendering a :class:`pyramid_urireferencer.models.RegistryResponse` to json. :param pyramid_urireferencer.models.RegistryResponse obj: The response to be rendered. :rtype: :class:`dict` ### Response: def registry_adapter(obj, requ...
def IPID_count(lst, funcID=lambda x: x[1].id, funcpres=lambda x: x[1].summary()): # noqa: E501 """Identify IP id values classes in a list of packets lst: a list of packets funcID: a function that returns IP id values funcpres: a function used to summarize packets""" idlst = [funcID(e) for e in lst] ...
Identify IP id values classes in a list of packets lst: a list of packets funcID: a function that returns IP id values funcpres: a function used to summarize packets
Below is the the instruction that describes the task: ### Input: Identify IP id values classes in a list of packets lst: a list of packets funcID: a function that returns IP id values funcpres: a function used to summarize packets ### Response: def IPID_count(lst, funcID=lambda x: x[1].id, funcpres=lambda ...
def filter(self, extractions, case_sensitive=False) -> List[Extraction]: """filters out the extraction if extracted value is in the blacklist""" filtered_extractions = [] if not isinstance(extractions, list): extractions = [extractions] for extraction in extractions: ...
filters out the extraction if extracted value is in the blacklist
Below is the the instruction that describes the task: ### Input: filters out the extraction if extracted value is in the blacklist ### Response: def filter(self, extractions, case_sensitive=False) -> List[Extraction]: """filters out the extraction if extracted value is in the blacklist""" filtered_...
def mixed_list_file(cls, filename, values, bits): """ Write a list of mixed values to a file. If a file of the same name exists, it's contents are replaced. See L{HexInput.mixed_list_file} for a description of the file format. @type filename: str @param filename: Name ...
Write a list of mixed values to a file. If a file of the same name exists, it's contents are replaced. See L{HexInput.mixed_list_file} for a description of the file format. @type filename: str @param filename: Name of the file to write. @type values: list( int ) @par...
Below is the the instruction that describes the task: ### Input: Write a list of mixed values to a file. If a file of the same name exists, it's contents are replaced. See L{HexInput.mixed_list_file} for a description of the file format. @type filename: str @param filename: Name o...
def setup(self): """Initialize filter just before it will be used.""" super(CleanCSSFilter, self).setup() self.root = current_app.config.get('COLLECT_STATIC_ROOT')
Initialize filter just before it will be used.
Below is the the instruction that describes the task: ### Input: Initialize filter just before it will be used. ### Response: def setup(self): """Initialize filter just before it will be used.""" super(CleanCSSFilter, self).setup() self.root = current_app.config.get('COLLECT_STATIC_ROOT')
def get_default_home_dir(): """ Return default home directory of Ding0 Returns ------- :any:`str` Default home directory including its path """ ding0_dir = str(cfg_ding0.get('config', 'config_dir')) return os.path.join(os.path.expanduser('~'), d...
Return default home directory of Ding0 Returns ------- :any:`str` Default home directory including its path
Below is the the instruction that describes the task: ### Input: Return default home directory of Ding0 Returns ------- :any:`str` Default home directory including its path ### Response: def get_default_home_dir(): """ Return default home directory of Ding0 Returns ------- ...
def _checkCanIndex(self): ''' _checkCanIndex - Check if we CAN index (if all fields are indexable). Also checks the right-most field for "hashIndex" - if it needs to hash we will hash. ''' # NOTE: We can't just check the right-most field. For types like pickle that don't support indexing, they don't # ...
_checkCanIndex - Check if we CAN index (if all fields are indexable). Also checks the right-most field for "hashIndex" - if it needs to hash we will hash.
Below is the the instruction that describes the task: ### Input: _checkCanIndex - Check if we CAN index (if all fields are indexable). Also checks the right-most field for "hashIndex" - if it needs to hash we will hash. ### Response: def _checkCanIndex(self): ''' _checkCanIndex - Check if we CAN index (if...
def Beta(alpha, beta, low=0, high=1, tag=None): """ A Beta random variate Parameters ---------- alpha : scalar The first shape parameter beta : scalar The second shape parameter Optional -------- low : scalar Lower bound of the distribution support (...
A Beta random variate Parameters ---------- alpha : scalar The first shape parameter beta : scalar The second shape parameter Optional -------- low : scalar Lower bound of the distribution support (default=0) high : scalar Upper bound of the dist...
Below is the the instruction that describes the task: ### Input: A Beta random variate Parameters ---------- alpha : scalar The first shape parameter beta : scalar The second shape parameter Optional -------- low : scalar Lower bound of the distribution ...
def __balance(self, account_id, **kwargs): """Call documentation: `/account/balance <https://www.wepay.com/developer/reference/account-2011-01-15#balance>`_, plus extra keyword parameters: :keyword str access_token: will be used instead of instance's ``access_token``,...
Call documentation: `/account/balance <https://www.wepay.com/developer/reference/account-2011-01-15#balance>`_, plus extra keyword parameters: :keyword str access_token: will be used instead of instance's ``access_token``, with ``batch_mode=True`` will set `authorization` ...
Below is the the instruction that describes the task: ### Input: Call documentation: `/account/balance <https://www.wepay.com/developer/reference/account-2011-01-15#balance>`_, plus extra keyword parameters: :keyword str access_token: will be used instead of instance's ``...
def get_checklists( self ): """ Get the checklists for this board. Returns a list of Checklist objects. """ checklists = self.getChecklistsJson( self.base_uri ) checklists_list = [] for checklist_json in checklists: checklists_list.append( self.createChecklis...
Get the checklists for this board. Returns a list of Checklist objects.
Below is the the instruction that describes the task: ### Input: Get the checklists for this board. Returns a list of Checklist objects. ### Response: def get_checklists( self ): """ Get the checklists for this board. Returns a list of Checklist objects. """ checklists = self.getChe...
def sort_data(x_vals, y_vals): """Sort the data so that x is monotonically increasing and contains no duplicates. """ # Sort data idxs = np.argsort(x_vals) x_vals = x_vals[idxs] y_vals = y_vals[idxs] # De-duplicate data mask = np.r_[True, (np.diff(x_vals) > 0)] if not mask.all()...
Sort the data so that x is monotonically increasing and contains no duplicates.
Below is the the instruction that describes the task: ### Input: Sort the data so that x is monotonically increasing and contains no duplicates. ### Response: def sort_data(x_vals, y_vals): """Sort the data so that x is monotonically increasing and contains no duplicates. """ # Sort data id...
def resolve_object_property(obj, path: str): """Resolves the value of a property on an object. Is able to resolve nested properties. For example, a path can be specified: 'other.beer.name' Raises: AttributeError: In case the property could not be resolved. Returns: ...
Resolves the value of a property on an object. Is able to resolve nested properties. For example, a path can be specified: 'other.beer.name' Raises: AttributeError: In case the property could not be resolved. Returns: The value of the specified property.
Below is the the instruction that describes the task: ### Input: Resolves the value of a property on an object. Is able to resolve nested properties. For example, a path can be specified: 'other.beer.name' Raises: AttributeError: In case the property could not be resolved....
def computeEntropyAndEnthalpy(self, uncertainty_method=None, verbose=False, warning_cutoff=1.0e-10): """Decompose free energy differences into enthalpy and entropy differences. Compute the decomposition of the free energy difference between states 1 and N into reduced free energy differences, r...
Decompose free energy differences into enthalpy and entropy differences. Compute the decomposition of the free energy difference between states 1 and N into reduced free energy differences, reduced potential (enthalpy) differences, and reduced entropy (S/k) differences. Parameters ...
Below is the the instruction that describes the task: ### Input: Decompose free energy differences into enthalpy and entropy differences. Compute the decomposition of the free energy difference between states 1 and N into reduced free energy differences, reduced potential (enthalpy) differe...
def savefits(cube, fitsname, **kwargs): """Save a cube to a 3D-cube FITS file. Args: cube (xarray.DataArray): Cube to be saved. fitsname (str): Name of output FITS file. kwargs (optional): Other arguments common with astropy.io.fits.writeto(). """ ### pick up kwargs dropdeg ...
Save a cube to a 3D-cube FITS file. Args: cube (xarray.DataArray): Cube to be saved. fitsname (str): Name of output FITS file. kwargs (optional): Other arguments common with astropy.io.fits.writeto().
Below is the the instruction that describes the task: ### Input: Save a cube to a 3D-cube FITS file. Args: cube (xarray.DataArray): Cube to be saved. fitsname (str): Name of output FITS file. kwargs (optional): Other arguments common with astropy.io.fits.writeto(). ### Response: def sa...
def kibana_install(self): """ kibana install :return: """ with cd('/tmp'): if not exists('kibana.deb'): sudo('wget {0} -O kibana.deb'.format( bigdata_conf.kibana_download_url )) sudo('dpkg -i kibana.deb'...
kibana install :return:
Below is the the instruction that describes the task: ### Input: kibana install :return: ### Response: def kibana_install(self): """ kibana install :return: """ with cd('/tmp'): if not exists('kibana.deb'): sudo('wget {0} -O kibana.deb'.fo...
def feed_data(self, data: bytes) -> None: """ 代理 feed_data """ if self._parser is not None: self._parser.feed_data(data)
代理 feed_data
Below is the the instruction that describes the task: ### Input: 代理 feed_data ### Response: def feed_data(self, data: bytes) -> None: """ 代理 feed_data """ if self._parser is not None: self._parser.feed_data(data)
def make_pose(translation, rotation): """ Makes a homogenous pose matrix from a translation vector and a rotation matrix. Args: translation: a 3-dim iterable rotation: a 3x3 matrix Returns: pose: a 4x4 homogenous matrix """ pose = np.zeros((4, 4)) pose[:3, :3] = rot...
Makes a homogenous pose matrix from a translation vector and a rotation matrix. Args: translation: a 3-dim iterable rotation: a 3x3 matrix Returns: pose: a 4x4 homogenous matrix
Below is the the instruction that describes the task: ### Input: Makes a homogenous pose matrix from a translation vector and a rotation matrix. Args: translation: a 3-dim iterable rotation: a 3x3 matrix Returns: pose: a 4x4 homogenous matrix ### Response: def make_pose(translatio...
def _solve(self, A=None, b=None): r""" Sends the A and b matrices to the specified solver, and solves for *x* given the boundary conditions, and source terms based on the present value of *x*. This method does NOT iterate to solve for non-linear source terms or march time steps....
r""" Sends the A and b matrices to the specified solver, and solves for *x* given the boundary conditions, and source terms based on the present value of *x*. This method does NOT iterate to solve for non-linear source terms or march time steps. Parameters ---------- ...
Below is the the instruction that describes the task: ### Input: r""" Sends the A and b matrices to the specified solver, and solves for *x* given the boundary conditions, and source terms based on the present value of *x*. This method does NOT iterate to solve for non-linear source...
def _get_base_command(self): """Returns the base command plus command-line options. Handles everything up to and including the classpath. The positional training parameters are added by the _input_handler_decorator method. """ cd_command = ''.join(['cd ', str(self.Worki...
Returns the base command plus command-line options. Handles everything up to and including the classpath. The positional training parameters are added by the _input_handler_decorator method.
Below is the the instruction that describes the task: ### Input: Returns the base command plus command-line options. Handles everything up to and including the classpath. The positional training parameters are added by the _input_handler_decorator method. ### Response: def _get_base_comma...
def exhandler(function, parser): """If -examples was specified in 'args', the specified function is called and the application exits. :arg function: the function that prints the examples. :arg parser: the initialized instance of the parser that has the additional, script-specific parameters. ...
If -examples was specified in 'args', the specified function is called and the application exits. :arg function: the function that prints the examples. :arg parser: the initialized instance of the parser that has the additional, script-specific parameters.
Below is the the instruction that describes the task: ### Input: If -examples was specified in 'args', the specified function is called and the application exits. :arg function: the function that prints the examples. :arg parser: the initialized instance of the parser that has the additional, scr...
def check(self, return_code=0): """Run command with arguments. Wait for command to complete. If the exit code was as expected and there is no exception then return, otherwise raise EasyProcessError. :param return_code: int, expected return code :rtype: self """ ...
Run command with arguments. Wait for command to complete. If the exit code was as expected and there is no exception then return, otherwise raise EasyProcessError. :param return_code: int, expected return code :rtype: self
Below is the the instruction that describes the task: ### Input: Run command with arguments. Wait for command to complete. If the exit code was as expected and there is no exception then return, otherwise raise EasyProcessError. :param return_code: int, expected return code :rtype: ...
def weld_str_lower(array): """Convert values to lowercase. Parameters ---------- array : numpy.ndarray or WeldObject Input data. Returns ------- WeldObject Representation of this computation. """ obj_id, weld_obj = create_weld_object(array) weld_template = """...
Convert values to lowercase. Parameters ---------- array : numpy.ndarray or WeldObject Input data. Returns ------- WeldObject Representation of this computation.
Below is the the instruction that describes the task: ### Input: Convert values to lowercase. Parameters ---------- array : numpy.ndarray or WeldObject Input data. Returns ------- WeldObject Representation of this computation. ### Response: def weld_str_lower(array): "...
def groupby(xs, key_fn): """ Group elements of the list `xs` by keys generated from calling `key_fn`. Returns a dictionary which maps keys to sub-lists of `xs`. """ result = defaultdict(list) for x in xs: key = key_fn(x) result[key].append(x) return result
Group elements of the list `xs` by keys generated from calling `key_fn`. Returns a dictionary which maps keys to sub-lists of `xs`.
Below is the the instruction that describes the task: ### Input: Group elements of the list `xs` by keys generated from calling `key_fn`. Returns a dictionary which maps keys to sub-lists of `xs`. ### Response: def groupby(xs, key_fn): """ Group elements of the list `xs` by keys generated from calling...
def get_artist_by_mbid(self, mbid): """Looks up an artist by its MusicBrainz ID""" params = {"mbid": mbid} doc = _Request(self, "artist.getInfo", params).execute(True) return Artist(_extract(doc, "name"), self)
Looks up an artist by its MusicBrainz ID
Below is the the instruction that describes the task: ### Input: Looks up an artist by its MusicBrainz ID ### Response: def get_artist_by_mbid(self, mbid): """Looks up an artist by its MusicBrainz ID""" params = {"mbid": mbid} doc = _Request(self, "artist.getInfo", params).execute(True) ...
def _handle_upsert(self, parts, unwritten_lobs=()): """Handle reply messages from INSERT or UPDATE statements""" self.description = None self._received_last_resultset_part = True # set to 'True' so that cursor.fetch*() returns just empty list for part in parts: if part.kind...
Handle reply messages from INSERT or UPDATE statements
Below is the the instruction that describes the task: ### Input: Handle reply messages from INSERT or UPDATE statements ### Response: def _handle_upsert(self, parts, unwritten_lobs=()): """Handle reply messages from INSERT or UPDATE statements""" self.description = None self._received_last_...
def validate_metadata(self, handler): """ validate that kind=category does not change the categories """ if self.meta == 'category': new_metadata = self.metadata cur_metadata = handler.read_metadata(self.cname) if (new_metadata is not None and cur_metadata is not None...
validate that kind=category does not change the categories
Below is the the instruction that describes the task: ### Input: validate that kind=category does not change the categories ### Response: def validate_metadata(self, handler): """ validate that kind=category does not change the categories """ if self.meta == 'category': new_metadata = s...
def placeholder(type_): """Returns the EmptyVal instance for the given type""" typetuple = type_ if isinstance(type_, tuple) else (type_,) if any in typetuple: typetuple = any if typetuple not in EMPTY_VALS: EMPTY_VALS[typetuple] = EmptyVal(typetuple) return EMPTY_VALS[typetuple]
Returns the EmptyVal instance for the given type
Below is the the instruction that describes the task: ### Input: Returns the EmptyVal instance for the given type ### Response: def placeholder(type_): """Returns the EmptyVal instance for the given type""" typetuple = type_ if isinstance(type_, tuple) else (type_,) if any in typetuple: typetup...
def join(self, joiner, formatter=lambda s, t: t.format(s), template="{}"): """Join values and convert to string Example: >>> from ww import l >>> lst = l('012') >>> lst.join(',') u'0,1,2' >>> lst.join(',', template="{}#") ...
Join values and convert to string Example: >>> from ww import l >>> lst = l('012') >>> lst.join(',') u'0,1,2' >>> lst.join(',', template="{}#") u'0#,1#,2#' >>> string = lst.join(',',\ formatte...
Below is the the instruction that describes the task: ### Input: Join values and convert to string Example: >>> from ww import l >>> lst = l('012') >>> lst.join(',') u'0,1,2' >>> lst.join(',', template="{}#") u'0#,1#,2#' >...
def filter(self, model=None, context=None): """ Perform filtering on the model. Will change model in place. :param model: object or dict :param context: object, dict or None :return: None """ if model is None: return # properties self....
Perform filtering on the model. Will change model in place. :param model: object or dict :param context: object, dict or None :return: None
Below is the the instruction that describes the task: ### Input: Perform filtering on the model. Will change model in place. :param model: object or dict :param context: object, dict or None :return: None ### Response: def filter(self, model=None, context=None): """ Perform ...