code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def removevalues(self, key, values): """ Removes all <values> from the values of <key>. If <key> has no remaining values after removevalues(), the key is popped. Example: omd = omdict([(1, 1), (1, 11), (1, 1), (1, 111)]) omd.removevalues(1, [1, 111]) omd.al...
Removes all <values> from the values of <key>. If <key> has no remaining values after removevalues(), the key is popped. Example: omd = omdict([(1, 1), (1, 11), (1, 1), (1, 111)]) omd.removevalues(1, [1, 111]) omd.allitems() == [(1, 11)] Returns: <self>.
Below is the the instruction that describes the task: ### Input: Removes all <values> from the values of <key>. If <key> has no remaining values after removevalues(), the key is popped. Example: omd = omdict([(1, 1), (1, 11), (1, 1), (1, 111)]) omd.removevalues(1, [1, 111]) ...
def MI_getInstance(self, env, instanceName, propertyList): # pylint: disable=invalid-name """Return a specific CIM instance Implements the WBEM operation GetInstance in terms of the get_instance method. A derived clas...
Return a specific CIM instance Implements the WBEM operation GetInstance in terms of the get_instance method. A derived class will not normally override this method.
Below is the the instruction that describes the task: ### Input: Return a specific CIM instance Implements the WBEM operation GetInstance in terms of the get_instance method. A derived class will not normally override this method. ### Response: def MI_getInstance(self, ...
def get_local_client( c_path=os.path.join(syspaths.CONFIG_DIR, 'master'), mopts=None, skip_perm_errors=False, io_loop=None, auto_reconnect=False): ''' .. versionadded:: 2014.7.0 Read in the config and return the correct LocalClient object based on the configured ...
.. versionadded:: 2014.7.0 Read in the config and return the correct LocalClient object based on the configured transport :param IOLoop io_loop: io_loop used for events. Pass in an io_loop if you want asynchronous operation for obtaining events. Eg use...
Below is the the instruction that describes the task: ### Input: .. versionadded:: 2014.7.0 Read in the config and return the correct LocalClient object based on the configured transport :param IOLoop io_loop: io_loop used for events. Pass in an io_loop if you want asynchron...
def makeSocket(self, timeout=1): """Override SocketHandler.makeSocket, to allow creating wrapped TLS sockets""" plain_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) if hasattr(plain_socket, 'settimeout'): plain_socket.settimeout(timeout) wrapped_socket =...
Override SocketHandler.makeSocket, to allow creating wrapped TLS sockets
Below is the the instruction that describes the task: ### Input: Override SocketHandler.makeSocket, to allow creating wrapped TLS sockets ### Response: def makeSocket(self, timeout=1): """Override SocketHandler.makeSocket, to allow creating wrapped TLS sockets""" plain_socket = sock...
def formatted_command(self): """ If we have ``bash``, then the command is ``/bin/bash -c <bash>``, whereas if the ``command`` is set, then we just return that. """ bash = self.bash if bash not in (None, "", NotSpecified) and callable(bash): bash = bash() ...
If we have ``bash``, then the command is ``/bin/bash -c <bash>``, whereas if the ``command`` is set, then we just return that.
Below is the the instruction that describes the task: ### Input: If we have ``bash``, then the command is ``/bin/bash -c <bash>``, whereas if the ``command`` is set, then we just return that. ### Response: def formatted_command(self): """ If we have ``bash``, then the command is ``/bin/bash...
def parseEvent(self, result, i): """Parse the current event and extract data.""" fmt = '%Y-%m-%dT%H:%M:%SZ' due = 0 delay = 0 real_time = 'n' number = result['stopEvents'][i]['transportation']['number'] planned = datetime.strptime(result['stopEvents'][i] ...
Parse the current event and extract data.
Below is the the instruction that describes the task: ### Input: Parse the current event and extract data. ### Response: def parseEvent(self, result, i): """Parse the current event and extract data.""" fmt = '%Y-%m-%dT%H:%M:%SZ' due = 0 delay = 0 real_time = 'n' numb...
def summarise_pdfs(pdfs): """ Collate the first page from each of the PDFs provided into a single PDF. :param pdfs: The contents of several PDF files. :type pdfs: list of str :returns: The contents of single PDF, which can be written directly to disk. """ # Ignore...
Collate the first page from each of the PDFs provided into a single PDF. :param pdfs: The contents of several PDF files. :type pdfs: list of str :returns: The contents of single PDF, which can be written directly to disk.
Below is the the instruction that describes the task: ### Input: Collate the first page from each of the PDFs provided into a single PDF. :param pdfs: The contents of several PDF files. :type pdfs: list of str :returns: The contents of single PDF, which can be written directly...
def _get_num_similar_objects(self, obj): """Get any statement lines which would be considered a duplicate of obj""" return StatementLine.objects.filter( date=obj.date, amount=obj.amount, description=obj.description ).count()
Get any statement lines which would be considered a duplicate of obj
Below is the the instruction that describes the task: ### Input: Get any statement lines which would be considered a duplicate of obj ### Response: def _get_num_similar_objects(self, obj): """Get any statement lines which would be considered a duplicate of obj""" return StatementLine.objects.filter...
def walk(self, node, name='', list=list, len=len, type=type): """Walk the tree starting at a given node. Maintain a stack of nodes. """ pre_handlers = self.pre_handlers.get post_handlers = self.post_handlers.get nodestack = self.nodestack emptystack = len(nodest...
Walk the tree starting at a given node. Maintain a stack of nodes.
Below is the the instruction that describes the task: ### Input: Walk the tree starting at a given node. Maintain a stack of nodes. ### Response: def walk(self, node, name='', list=list, len=len, type=type): """Walk the tree starting at a given node. Maintain a stack of nodes. ""...
def save(self): """This function is called by the parent dialog window when the user selects to save the settings.""" if self.path is None: # Delete requested, so remove the current path from sys.path, if present if self.config_manager.userCodeDir is not None: sys.path.remov...
This function is called by the parent dialog window when the user selects to save the settings.
Below is the the instruction that describes the task: ### Input: This function is called by the parent dialog window when the user selects to save the settings. ### Response: def save(self): """This function is called by the parent dialog window when the user selects to save the settings.""" if sel...
def layer(self, img, x=0, y=0, name=""): """Creates a new layer from file, Layer, PIL Image. If img is an image file or PIL Image object, Creates a new layer with the given image file. The image is positioned on the canvas at x, y. If img is a Layer, us...
Creates a new layer from file, Layer, PIL Image. If img is an image file or PIL Image object, Creates a new layer with the given image file. The image is positioned on the canvas at x, y. If img is a Layer, uses that layer's x and y position and name.
Below is the the instruction that describes the task: ### Input: Creates a new layer from file, Layer, PIL Image. If img is an image file or PIL Image object, Creates a new layer with the given image file. The image is positioned on the canvas at x, y. If img is a Layer...
def try_ntimes(_howmany, func, *argv, **kwarg): """Try a function n times. Try to execute func(*argv, **kwarg) ``_howmany`` times. If it successfully run one time, then return as normal. If it fails N times, then raise the exception in the last run. **中文文档** 反复尝试一个函数或方法``_howman...
Try a function n times. Try to execute func(*argv, **kwarg) ``_howmany`` times. If it successfully run one time, then return as normal. If it fails N times, then raise the exception in the last run. **中文文档** 反复尝试一个函数或方法``_howmany``次。 对func函数使用try, except, pass 若干次, 期间只要有一次成...
Below is the the instruction that describes the task: ### Input: Try a function n times. Try to execute func(*argv, **kwarg) ``_howmany`` times. If it successfully run one time, then return as normal. If it fails N times, then raise the exception in the last run. **中文文档** 反复尝试一个...
def filter_unique_peptides(peptides, score, ns): """ Filters unique peptides from multiple Percolator output XML files. Takes a dir with a set of XMLs, a score to filter on and a namespace. Outputs an ElementTree. """ scores = {'q': 'q_value', 'pep': 'pep', 'p': '...
Filters unique peptides from multiple Percolator output XML files. Takes a dir with a set of XMLs, a score to filter on and a namespace. Outputs an ElementTree.
Below is the the instruction that describes the task: ### Input: Filters unique peptides from multiple Percolator output XML files. Takes a dir with a set of XMLs, a score to filter on and a namespace. Outputs an ElementTree. ### Response: def filter_unique_peptides(peptides, score, ns): """ Fi...
def filter_on_attributes(ava, required=None, optional=None, acs=None, fail_on_unfulfilled_requirements=True): """ Filter :param ava: An attribute value assertion as a dictionary :param required: list of RequestedAttribute instances defined to be required :param optional...
Filter :param ava: An attribute value assertion as a dictionary :param required: list of RequestedAttribute instances defined to be required :param optional: list of RequestedAttribute instances defined to be optional :param fail_on_unfulfilled_requirements: If required attributes ...
Below is the the instruction that describes the task: ### Input: Filter :param ava: An attribute value assertion as a dictionary :param required: list of RequestedAttribute instances defined to be required :param optional: list of RequestedAttribute instances defined to be optional ...
def discussion_is_still_open(self, discussion_type, auto_close_after): """ Checks if a type of discussion is still open are a certain number of days. """ discussion_enabled = getattr(self, discussion_type) if (discussion_enabled and isinstance(auto_close_after, int) and ...
Checks if a type of discussion is still open are a certain number of days.
Below is the the instruction that describes the task: ### Input: Checks if a type of discussion is still open are a certain number of days. ### Response: def discussion_is_still_open(self, discussion_type, auto_close_after): """ Checks if a type of discussion is still open are a cer...
def deepish_copy(org): """Improved speed deep copy for dictionaries of simple python types. Thanks to Gregg Lind: http://writeonly.wordpress.com/2009/05/07/deepcopy-is-a-pig-for-simple-data/ """ out = dict().fromkeys(org) for k, v in org.items(): if isinstance(v, dict): out[...
Improved speed deep copy for dictionaries of simple python types. Thanks to Gregg Lind: http://writeonly.wordpress.com/2009/05/07/deepcopy-is-a-pig-for-simple-data/
Below is the the instruction that describes the task: ### Input: Improved speed deep copy for dictionaries of simple python types. Thanks to Gregg Lind: http://writeonly.wordpress.com/2009/05/07/deepcopy-is-a-pig-for-simple-data/ ### Response: def deepish_copy(org): """Improved speed deep copy for dic...
def close(self): """Closes the record file.""" if not self.is_open: return if self.writable: check_call(_LIB.MXRecordIOWriterFree(self.handle)) else: check_call(_LIB.MXRecordIOReaderFree(self.handle)) self.is_open = False self.pid = Non...
Closes the record file.
Below is the the instruction that describes the task: ### Input: Closes the record file. ### Response: def close(self): """Closes the record file.""" if not self.is_open: return if self.writable: check_call(_LIB.MXRecordIOWriterFree(self.handle)) else: ...
def is_valid_file(filename): """ Check if the specifed file exists and is not empty :param filename: full path to the file that needs to be checked :return: Status, Message """ if os.path.exists(filename): if not os.path.getsize(filename): logger.warning('%s : file is empty.', filename) ret...
Check if the specifed file exists and is not empty :param filename: full path to the file that needs to be checked :return: Status, Message
Below is the the instruction that describes the task: ### Input: Check if the specifed file exists and is not empty :param filename: full path to the file that needs to be checked :return: Status, Message ### Response: def is_valid_file(filename): """ Check if the specifed file exists and is not empty ...
def has_metaclass(parent): """ we have to check the cls_node without changing it. There are two possiblities: 1) clsdef => suite => simple_stmt => expr_stmt => Leaf('__meta') 2) clsdef => simple_stmt => expr_stmt => Leaf('__meta') """ for node in parent.children: if nod...
we have to check the cls_node without changing it. There are two possiblities: 1) clsdef => suite => simple_stmt => expr_stmt => Leaf('__meta') 2) clsdef => simple_stmt => expr_stmt => Leaf('__meta')
Below is the the instruction that describes the task: ### Input: we have to check the cls_node without changing it. There are two possiblities: 1) clsdef => suite => simple_stmt => expr_stmt => Leaf('__meta') 2) clsdef => simple_stmt => expr_stmt => Leaf('__meta') ### Response: def ha...
def do_write(self, msg): """Handling writing an individual record; we do a fresh open every time. This assumes emit() has already locked the file.""" self.stream = self.do_open() stream = self.stream stream.write(msg) if self.terminator: stream.write(self.term...
Handling writing an individual record; we do a fresh open every time. This assumes emit() has already locked the file.
Below is the the instruction that describes the task: ### Input: Handling writing an individual record; we do a fresh open every time. This assumes emit() has already locked the file. ### Response: def do_write(self, msg): """Handling writing an individual record; we do a fresh open every time. ...
def plot_txn_time_hist(transactions, bin_minutes=5, tz='America/New_York', ax=None, **kwargs): """ Plots a histogram of transaction times, binning the times into buckets of a given duration. Parameters ---------- transactions : pd.DataFrame Prices and amounts of e...
Plots a histogram of transaction times, binning the times into buckets of a given duration. Parameters ---------- transactions : pd.DataFrame Prices and amounts of executed trades. One row per trade. - See full explanation in tears.create_full_tear_sheet. bin_minutes : float, optio...
Below is the the instruction that describes the task: ### Input: Plots a histogram of transaction times, binning the times into buckets of a given duration. Parameters ---------- transactions : pd.DataFrame Prices and amounts of executed trades. One row per trade. - See full explan...
def to_xml(self, tag_name="buyer"): ''' Returns an XMLi representation of the object. @param tag_name:str Tag name @return: Element ''' for n, v in {"name": self.name, "address": self.address}.items(): if is_empty_or_none(v): raise ValueError("...
Returns an XMLi representation of the object. @param tag_name:str Tag name @return: Element
Below is the the instruction that describes the task: ### Input: Returns an XMLi representation of the object. @param tag_name:str Tag name @return: Element ### Response: def to_xml(self, tag_name="buyer"): ''' Returns an XMLi representation of the object. @param tag_name:st...
def infer(self, sequence, reset=True, sequenceNumber=None, burnIn=2, enableFeedback=True, apicalTiebreak=True, apicalModulationBasalThreshold=True, inertia=True): """ Infer on a single given sequence. Sequence format: sequence = [ set([16, 22, 32]), # Position 0 set([13...
Infer on a single given sequence. Sequence format: sequence = [ set([16, 22, 32]), # Position 0 set([13, 15, 33]) # Position 1 ] Parameters: ---------------------------- @param sequence (list) Sequence to infer, in the canonical format specified above @param re...
Below is the the instruction that describes the task: ### Input: Infer on a single given sequence. Sequence format: sequence = [ set([16, 22, 32]), # Position 0 set([13, 15, 33]) # Position 1 ] Parameters: ---------------------------- @param sequence (list) Sequen...
def fit_arrhenius(temps, diffusivities): """ Returns Ea, c, standard error of Ea from the Arrhenius fit: D = c * exp(-Ea/kT) Args: temps ([float]): A sequence of temperatures. units: K diffusivities ([float]): A sequence of diffusivities (e.g., from DiffusionAnalyzer.dif...
Returns Ea, c, standard error of Ea from the Arrhenius fit: D = c * exp(-Ea/kT) Args: temps ([float]): A sequence of temperatures. units: K diffusivities ([float]): A sequence of diffusivities (e.g., from DiffusionAnalyzer.diffusivity). units: cm^2/s
Below is the the instruction that describes the task: ### Input: Returns Ea, c, standard error of Ea from the Arrhenius fit: D = c * exp(-Ea/kT) Args: temps ([float]): A sequence of temperatures. units: K diffusivities ([float]): A sequence of diffusivities (e.g., from Diffu...
def readInstances(self, makeGlyphs=True, makeKerning=True, makeInfo=True): """ Read all instance elements. :: <instance familyname="SuperFamily" filename="OutputNameInstance1.ufo" location="location-token-aaa" stylename="Regular"> """ for instanceElement in self.root.finda...
Read all instance elements. :: <instance familyname="SuperFamily" filename="OutputNameInstance1.ufo" location="location-token-aaa" stylename="Regular">
Below is the the instruction that describes the task: ### Input: Read all instance elements. :: <instance familyname="SuperFamily" filename="OutputNameInstance1.ufo" location="location-token-aaa" stylename="Regular"> ### Response: def readInstances(self, makeGlyphs=True, makeKerning=True, mak...
def close_fast(self): """Turn the device off.""" close_command = StandardSend(self._address, COMMAND_LIGHT_OFF_FAST_0X14_0X00) self._send_method(close_command, self._closed_message_received)
Turn the device off.
Below is the the instruction that describes the task: ### Input: Turn the device off. ### Response: def close_fast(self): """Turn the device off.""" close_command = StandardSend(self._address, COMMAND_LIGHT_OFF_FAST_0X14_0X00) self._send_method(close_com...
def afni_copy(filename): ''' creates a ``+orig`` copy of the given dataset and returns the filename as a string ''' if nl.pkg_available('afni',True): afni_filename = "%s+orig" % nl.prefix(filename) if not os.path.exists(afni_filename + ".HEAD"): nl.calc(filename,'a',prefix=nl.prefix(...
creates a ``+orig`` copy of the given dataset and returns the filename as a string
Below is the the instruction that describes the task: ### Input: creates a ``+orig`` copy of the given dataset and returns the filename as a string ### Response: def afni_copy(filename): ''' creates a ``+orig`` copy of the given dataset and returns the filename as a string ''' if nl.pkg_available('afni',Tr...
def _multitaper_spectrum(self, clm, k, convention='power', unit='per_l', lmax=None, taper_wt=None): """ Return the multitaper spectrum estimate and standard error for an input SHCoeffs class instance. """ if lmax is None: lmax = clm.lmax ...
Return the multitaper spectrum estimate and standard error for an input SHCoeffs class instance.
Below is the the instruction that describes the task: ### Input: Return the multitaper spectrum estimate and standard error for an input SHCoeffs class instance. ### Response: def _multitaper_spectrum(self, clm, k, convention='power', unit='per_l', lmax=None, taper_wt=None): ...
def diabetes(display=False): """ Return the diabetes data in a nice package. """ d = sklearn.datasets.load_diabetes() df = pd.DataFrame(data=d.data, columns=d.feature_names) # pylint: disable=E1101 return df, d.target
Return the diabetes data in a nice package.
Below is the the instruction that describes the task: ### Input: Return the diabetes data in a nice package. ### Response: def diabetes(display=False): """ Return the diabetes data in a nice package. """ d = sklearn.datasets.load_diabetes() df = pd.DataFrame(data=d.data, columns=d.feature_names) # pyl...
def extract_input_lines(self, range_str, raw=False): """Return as a string a set of input history slices. Parameters ---------- range_str : string The set of slices is given as a string, like "~5/6-~4/2 4:8 9", since this function is for use by magic functions wh...
Return as a string a set of input history slices. Parameters ---------- range_str : string The set of slices is given as a string, like "~5/6-~4/2 4:8 9", since this function is for use by magic functions which get their arguments as strings. The number befor...
Below is the the instruction that describes the task: ### Input: Return as a string a set of input history slices. Parameters ---------- range_str : string The set of slices is given as a string, like "~5/6-~4/2 4:8 9", since this function is for use by magic functio...
def _get_child_admin_site(self, rel): """ Returns the separate AdminSite instance that django-polymorphic maintains for child models. This admin site needs to be passed to the widget so that it passes the check of whether the field is pointing to a model that's registered ...
Returns the separate AdminSite instance that django-polymorphic maintains for child models. This admin site needs to be passed to the widget so that it passes the check of whether the field is pointing to a model that's registered in the admin. The hackiness of this implementat...
Below is the the instruction that describes the task: ### Input: Returns the separate AdminSite instance that django-polymorphic maintains for child models. This admin site needs to be passed to the widget so that it passes the check of whether the field is pointing to a model that's regist...
def index( self, symbol='000001', market='sh', category='9', start='0', offset='100'): ''' 获取指数k线 K线种类: - 0 5分钟K线 - 1 15分钟K线 - 2 30分钟K线 - 3 1小时K线 - 4 日K线 - 5 周K线 - 6 月K线 - 7 1分钟 ...
获取指数k线 K线种类: - 0 5分钟K线 - 1 15分钟K线 - 2 30分钟K线 - 3 1小时K线 - 4 日K线 - 5 周K线 - 6 月K线 - 7 1分钟 - 8 1分钟K线 - 9 日K线 - 10 季K线 - 11 年K线 :param symbol: 股票代码 :param category: 数据类别 :param market: 证券市场 ...
Below is the the instruction that describes the task: ### Input: 获取指数k线 K线种类: - 0 5分钟K线 - 1 15分钟K线 - 2 30分钟K线 - 3 1小时K线 - 4 日K线 - 5 周K线 - 6 月K线 - 7 1分钟 - 8 1分钟K线 - 9 日K线 - 10 季K线 - 11 年K线 :param symbol:...
def task_submission_options(f): """ Options shared by both transfer and delete task submission """ def notify_opt_callback(ctx, param, value): """ Parse --notify - "" is the same as "off" - parse by lowercase, comma-split, strip spaces - "off,x" is invalid for an...
Options shared by both transfer and delete task submission
Below is the the instruction that describes the task: ### Input: Options shared by both transfer and delete task submission ### Response: def task_submission_options(f): """ Options shared by both transfer and delete task submission """ def notify_opt_callback(ctx, param, value): """ ...
def local_reduction_attention(x, block_length, multihead_params): """Reduce the length dimension using self attention. Args: x (tf.Tensor): float32 of shape [batch, length, depth] block_length (int): Block length for local attention (Compression factor) multihead_params (dict): parameters for multihead...
Reduce the length dimension using self attention. Args: x (tf.Tensor): float32 of shape [batch, length, depth] block_length (int): Block length for local attention (Compression factor) multihead_params (dict): parameters for multihead attention Returns: tf.Tensor: Compressed tensor of shape [batch...
Below is the the instruction that describes the task: ### Input: Reduce the length dimension using self attention. Args: x (tf.Tensor): float32 of shape [batch, length, depth] block_length (int): Block length for local attention (Compression factor) multihead_params (dict): parameters for multihead a...
def show_status(self): """Show status of unregistered migrations""" if not self.check_directory(): return migrations = self.get_unregistered_migrations() if migrations: logger.info('Unregistered migrations:') for migration in migrations: ...
Show status of unregistered migrations
Below is the the instruction that describes the task: ### Input: Show status of unregistered migrations ### Response: def show_status(self): """Show status of unregistered migrations""" if not self.check_directory(): return migrations = self.get_unregistered_migrations() ...
def set_led_brightness(self, brightness): """Set the LED brightness for the current group/button.""" set_cmd = self._create_set_property_msg("_led_brightness", 0x07, brightness) self._send_method(set_cmd, self._property_set)
Set the LED brightness for the current group/button.
Below is the the instruction that describes the task: ### Input: Set the LED brightness for the current group/button. ### Response: def set_led_brightness(self, brightness): """Set the LED brightness for the current group/button.""" set_cmd = self._create_set_property_msg("_led_brightness", 0x07, ...
def _prep_params(params): '''Remove empty (None) valued keywords and self from function parameters''' return {k: v for (k, v) in params.items() if v is not None and k != 'self'}
Remove empty (None) valued keywords and self from function parameters
Below is the the instruction that describes the task: ### Input: Remove empty (None) valued keywords and self from function parameters ### Response: def _prep_params(params): '''Remove empty (None) valued keywords and self from function parameters''' return {k: v for (k, v) in params.items() if v ...
def paintEvent(self, event): """ Runs the paint event for this item. """ painter = QtGui.QPainter() painter.begin(self) try: x = 0 y = 2 w = self.width() - 1 h = self.height() - 3 palette = self.palette() ...
Runs the paint event for this item.
Below is the the instruction that describes the task: ### Input: Runs the paint event for this item. ### Response: def paintEvent(self, event): """ Runs the paint event for this item. """ painter = QtGui.QPainter() painter.begin(self) try: x = 0 ...
async def clear(self): """Close all free connections in pool.""" with (await self._cond): while self._free: conn = self._free.popleft() await conn.close() self._cond.notify()
Close all free connections in pool.
Below is the the instruction that describes the task: ### Input: Close all free connections in pool. ### Response: async def clear(self): """Close all free connections in pool.""" with (await self._cond): while self._free: conn = self._free.popleft() awai...
def get_spider_stats(self, spider_name): """get-spider-stats <spider> - get stats of a running spider""" if spider_name is None: spider_name = self.spider_name else: self.spider_name = spider_name if self.spider_name is None: self.spider_name = self.li...
get-spider-stats <spider> - get stats of a running spider
Below is the the instruction that describes the task: ### Input: get-spider-stats <spider> - get stats of a running spider ### Response: def get_spider_stats(self, spider_name): """get-spider-stats <spider> - get stats of a running spider""" if spider_name is None: spider_name = self.sp...
def assert_no_text(self, *args, **kwargs): """ Asserts that the page or current node doesn't have the given text content, ignoring any HTML tags. Args: *args: Variable length argument list for :class:`TextQuery`. **kwargs: Arbitrary keyword arguments for :class:`...
Asserts that the page or current node doesn't have the given text content, ignoring any HTML tags. Args: *args: Variable length argument list for :class:`TextQuery`. **kwargs: Arbitrary keyword arguments for :class:`TextQuery`. Returns: True Raises:...
Below is the the instruction that describes the task: ### Input: Asserts that the page or current node doesn't have the given text content, ignoring any HTML tags. Args: *args: Variable length argument list for :class:`TextQuery`. **kwargs: Arbitrary keyword arguments for :c...
def default(return_X_y=True): """credit default dataset Parameters ---------- return_X_y : bool, if True, returns a model-ready tuple of data (X, y) otherwise, returns a Pandas DataFrame Returns ------- model-ready tuple of data (X, y) OR Pandas DataFrame N...
credit default dataset Parameters ---------- return_X_y : bool, if True, returns a model-ready tuple of data (X, y) otherwise, returns a Pandas DataFrame Returns ------- model-ready tuple of data (X, y) OR Pandas DataFrame Notes ----- X contains the cat...
Below is the the instruction that describes the task: ### Input: credit default dataset Parameters ---------- return_X_y : bool, if True, returns a model-ready tuple of data (X, y) otherwise, returns a Pandas DataFrame Returns ------- model-ready tuple of data (X, y) ...
def is_same_key(key_1, key_2): """Extract the key from two host entries and compare them. :param key_1: Host key :type key_1: str :param key_2: Host key :type key_2: str """ # The key format get will be like '|1|2rUumCavEXWVaVyB5uMl6m85pZo=|Cp' # 'EL6l7VTY37T/fg/ihhNb/GPgs= ssh-rsa AAAA...
Extract the key from two host entries and compare them. :param key_1: Host key :type key_1: str :param key_2: Host key :type key_2: str
Below is the the instruction that describes the task: ### Input: Extract the key from two host entries and compare them. :param key_1: Host key :type key_1: str :param key_2: Host key :type key_2: str ### Response: def is_same_key(key_1, key_2): """Extract the key from two host entries and com...
def resolve_alias(s: sym.Symbol, ns: Optional[Namespace] = None) -> sym.Symbol: """Resolve the aliased symbol in the current namespace.""" if s in _SPECIAL_FORMS: return s ns = Maybe(ns).or_else(get_current_ns) if s.ns is not None: aliased_ns = ns.get_alias(sym.symbol(s.ns)) if ...
Resolve the aliased symbol in the current namespace.
Below is the the instruction that describes the task: ### Input: Resolve the aliased symbol in the current namespace. ### Response: def resolve_alias(s: sym.Symbol, ns: Optional[Namespace] = None) -> sym.Symbol: """Resolve the aliased symbol in the current namespace.""" if s in _SPECIAL_FORMS: retu...
def _build_query_dict(self, formdata=None): """ Take submitted data from form and create a query dict to be used in a Q object (or filter) """ if self.is_valid() and formdata is None: formdata = self.cleaned_data key = "{field}__{operator}".format(**formdata) ...
Take submitted data from form and create a query dict to be used in a Q object (or filter)
Below is the the instruction that describes the task: ### Input: Take submitted data from form and create a query dict to be used in a Q object (or filter) ### Response: def _build_query_dict(self, formdata=None): """ Take submitted data from form and create a query dict to be used ...
def lookup_default(self, name): """Looks up the default for a parameter name. This by default looks into the :attr:`default_map` if available. """ if self.default_map is not None: rv = self.default_map.get(name) if callable(rv): rv = rv() ...
Looks up the default for a parameter name. This by default looks into the :attr:`default_map` if available.
Below is the the instruction that describes the task: ### Input: Looks up the default for a parameter name. This by default looks into the :attr:`default_map` if available. ### Response: def lookup_default(self, name): """Looks up the default for a parameter name. This by default looks in...
def _GetFileAndLine(): """Returns (filename, linenumber) for the stack frame.""" # Use sys._getframe(). This avoids creating a traceback object. # pylint: disable=protected-access f = _sys._getframe() # pylint: enable=protected-access our_file = f.f_code.co_filename f = f.f_back while f...
Returns (filename, linenumber) for the stack frame.
Below is the the instruction that describes the task: ### Input: Returns (filename, linenumber) for the stack frame. ### Response: def _GetFileAndLine(): """Returns (filename, linenumber) for the stack frame.""" # Use sys._getframe(). This avoids creating a traceback object. # pylint: disable=protecte...
def checked_run(cmd): """Prepare and run a subprocess cmd, checking for successful completion.""" completed_process = run(cmd) if completed_process.returncode > 0: print("Command failed! Hanging around in case someone needs a " "docker connection. (Ctrl-C to quit now)") time.s...
Prepare and run a subprocess cmd, checking for successful completion.
Below is the the instruction that describes the task: ### Input: Prepare and run a subprocess cmd, checking for successful completion. ### Response: def checked_run(cmd): """Prepare and run a subprocess cmd, checking for successful completion.""" completed_process = run(cmd) if completed_process.return...
def from_dict(input_dict): """ Instantiate an object of a derived class using the information in input_dict (built by the to_dict method of the derived class). More specifically, after reading the derived class from input_dict, it calls the method _build_from_input_dict of the de...
Instantiate an object of a derived class using the information in input_dict (built by the to_dict method of the derived class). More specifically, after reading the derived class from input_dict, it calls the method _build_from_input_dict of the derived class. Note: This method should n...
Below is the the instruction that describes the task: ### Input: Instantiate an object of a derived class using the information in input_dict (built by the to_dict method of the derived class). More specifically, after reading the derived class from input_dict, it calls the method _build_fro...
def cli(ctx, obj): """Show Alerta server and client versions.""" client = obj['client'] click.echo('alerta {}'.format(client.mgmt_status()['version'])) click.echo('alerta client {}'.format(client_version)) click.echo('requests {}'.format(requests_version)) click.echo('click {}'.format(click.__ve...
Show Alerta server and client versions.
Below is the the instruction that describes the task: ### Input: Show Alerta server and client versions. ### Response: def cli(ctx, obj): """Show Alerta server and client versions.""" client = obj['client'] click.echo('alerta {}'.format(client.mgmt_status()['version'])) click.echo('alerta client {}...
def status(directory: str) -> Tuple[RepositoryLocation, Branch, Commit]: """ Gets the status of the subrepo that has been cloned into the given directory. :param directory: the directory containing the subrepo :return: a tuple consisting of the URL the subrepo is tracking, the branch that has been check...
Gets the status of the subrepo that has been cloned into the given directory. :param directory: the directory containing the subrepo :return: a tuple consisting of the URL the subrepo is tracking, the branch that has been checked out and the commit reference
Below is the the instruction that describes the task: ### Input: Gets the status of the subrepo that has been cloned into the given directory. :param directory: the directory containing the subrepo :return: a tuple consisting of the URL the subrepo is tracking, the branch that has been checked out and the c...
def setDefaults(self, instance): """Only call during object initialization, this function sets fields to schema defaults. It's adapted from the original to support IAcquireFieldDefaults adapters. If IAcquireFieldDefaults adapter does not find a suitable field, or that field's value is Falseish, th...
Only call during object initialization, this function sets fields to schema defaults. It's adapted from the original to support IAcquireFieldDefaults adapters. If IAcquireFieldDefaults adapter does not find a suitable field, or that field's value is Falseish, this function will not continue with the n...
Below is the the instruction that describes the task: ### Input: Only call during object initialization, this function sets fields to schema defaults. It's adapted from the original to support IAcquireFieldDefaults adapters. If IAcquireFieldDefaults adapter does not find a suitable field, or that fiel...
def pipe2(flags=0): """ Wrapper around ``pipe2(2)`` :param flags: Optional flags to set. This should almost always include O_CLOEXEC so that the resulting code is not racy (see the discussion about O_CLOEXEC to understand why this flag is essential). It can also include O_NO...
Wrapper around ``pipe2(2)`` :param flags: Optional flags to set. This should almost always include O_CLOEXEC so that the resulting code is not racy (see the discussion about O_CLOEXEC to understand why this flag is essential). It can also include O_NONBLOCK or O_DIRECT, depending on...
Below is the the instruction that describes the task: ### Input: Wrapper around ``pipe2(2)`` :param flags: Optional flags to set. This should almost always include O_CLOEXEC so that the resulting code is not racy (see the discussion about O_CLOEXEC to understand why this flag is essenti...
def range(self): """A tuple containing the numeric range for this Slot. The Python equivalent of the CLIPS deftemplate-slot-range function. """ data = clips.data.DataObject(self._env) lib.EnvDeftemplateSlotRange( self._env, self._tpl, self._name, data.byref) ...
A tuple containing the numeric range for this Slot. The Python equivalent of the CLIPS deftemplate-slot-range function.
Below is the the instruction that describes the task: ### Input: A tuple containing the numeric range for this Slot. The Python equivalent of the CLIPS deftemplate-slot-range function. ### Response: def range(self): """A tuple containing the numeric range for this Slot. The Python equival...
def edge_by_id(self, edge): """ Returns the edge that connects the head_id and tail_id nodes """ try: head, tail, data = self.edges[edge] except KeyError: head, tail = None, None raise GraphError('Invalid edge %s' % edge) return (head...
Returns the edge that connects the head_id and tail_id nodes
Below is the the instruction that describes the task: ### Input: Returns the edge that connects the head_id and tail_id nodes ### Response: def edge_by_id(self, edge): """ Returns the edge that connects the head_id and tail_id nodes """ try: head, tail, data = self.edge...
def title(self, category): """ Return the total printed length of this category item. """ return sum( [self.getWidth(category, x) for x in self.fields])
Return the total printed length of this category item.
Below is the the instruction that describes the task: ### Input: Return the total printed length of this category item. ### Response: def title(self, category): """ Return the total printed length of this category item. """ return sum( [self.getWidth(category, x) for x in self.f...
def logProbability(self, distn): """Form of distribution must be an array of counts in order of self.keys.""" x = numpy.asarray(distn) n = x.sum() return (logFactorial(n) - numpy.sum([logFactorial(k) for k in x]) + numpy.sum(x * numpy.log(self.dist.pmf)))
Form of distribution must be an array of counts in order of self.keys.
Below is the the instruction that describes the task: ### Input: Form of distribution must be an array of counts in order of self.keys. ### Response: def logProbability(self, distn): """Form of distribution must be an array of counts in order of self.keys.""" x = numpy.asarray(distn) n = x.sum() re...
def cmd(self, *args, **kwargs): '''adb command, add -s serial by default. return the subprocess.Popen object.''' serial = self.device_serial() if serial: if " " in serial: # TODO how to include special chars on command line serial = "'%s'" % serial return...
adb command, add -s serial by default. return the subprocess.Popen object.
Below is the the instruction that describes the task: ### Input: adb command, add -s serial by default. return the subprocess.Popen object. ### Response: def cmd(self, *args, **kwargs): '''adb command, add -s serial by default. return the subprocess.Popen object.''' serial = self.device_serial() ...
def search_series(self, name=None, imdb_id=None, zap2it_id=None): """Search series""" # perform the request params = {'name': name, 'imdbId': imdb_id, 'zap2itId': zap2it_id} r = self.session.get(self.base_url + '/search/series', params=params) if r.status_code == 404: ...
Search series
Below is the the instruction that describes the task: ### Input: Search series ### Response: def search_series(self, name=None, imdb_id=None, zap2it_id=None): """Search series""" # perform the request params = {'name': name, 'imdbId': imdb_id, 'zap2itId': zap2it_id} r = self.session...
def _GetSubFileEntries(self): """Retrieves sub file entries. Yields: TARFileEntry: a sub file entry. """ tar_file = self._file_system.GetTARFile() if self._directory is None: self._directory = self._GetDirectory() if self._directory and tar_file: for path_spec in self._direc...
Retrieves sub file entries. Yields: TARFileEntry: a sub file entry.
Below is the the instruction that describes the task: ### Input: Retrieves sub file entries. Yields: TARFileEntry: a sub file entry. ### Response: def _GetSubFileEntries(self): """Retrieves sub file entries. Yields: TARFileEntry: a sub file entry. """ tar_file = self._file_system....
def description(self): """ A list of the metrics this query will ask for. """ if 'metrics' in self.raw: metrics = self.raw['metrics'] head = metrics[0:-1] or metrics[0:1] text = ", ".join(head) if len(metrics) > 1: tail = m...
A list of the metrics this query will ask for.
Below is the the instruction that describes the task: ### Input: A list of the metrics this query will ask for. ### Response: def description(self): """ A list of the metrics this query will ask for. """ if 'metrics' in self.raw: metrics = self.raw['metrics'] ...
def paths(self): """The list of search paths. It is built from registered finders, which has ``paths`` property. Can be useful for compilers to resolve internal dependencies. """ if not hasattr(self, '_paths'): paths = [] for finder in self.finders: ...
The list of search paths. It is built from registered finders, which has ``paths`` property. Can be useful for compilers to resolve internal dependencies.
Below is the the instruction that describes the task: ### Input: The list of search paths. It is built from registered finders, which has ``paths`` property. Can be useful for compilers to resolve internal dependencies. ### Response: def paths(self): """The list of search paths. It is built...
def _get_go2nthdridx(self, gos_all): """Get GO IDs header index for each user GO ID and corresponding parent GO IDs.""" go2nthdridx = {} # NtHdrIdx Namedtuple fields: # * format_txt: Used to determine the format when writing Excel cells # * hdr_idx: Value printed in an Excel ...
Get GO IDs header index for each user GO ID and corresponding parent GO IDs.
Below is the the instruction that describes the task: ### Input: Get GO IDs header index for each user GO ID and corresponding parent GO IDs. ### Response: def _get_go2nthdridx(self, gos_all): """Get GO IDs header index for each user GO ID and corresponding parent GO IDs.""" go2nthdridx = {} ...
def poll(self, timeout_ms=0, max_records=None): """Fetch data from assigned topics / partitions. Records are fetched and returned in batches by topic-partition. On each poll, consumer will try to use the last consumed offset as the starting offset and fetch sequentially. The last consum...
Fetch data from assigned topics / partitions. Records are fetched and returned in batches by topic-partition. On each poll, consumer will try to use the last consumed offset as the starting offset and fetch sequentially. The last consumed offset can be manually set through :meth:`~kafka...
Below is the the instruction that describes the task: ### Input: Fetch data from assigned topics / partitions. Records are fetched and returned in batches by topic-partition. On each poll, consumer will try to use the last consumed offset as the starting offset and fetch sequentially. The l...
def get_root_path(self, path): """See :py:meth:`~stash.repository.Repository.get_root_path`.""" # Look at the directories present in the current working directory. In # case a .svn directory is present, we know we are in the root directory # of a Subversion repository (for Subversion 1.7...
See :py:meth:`~stash.repository.Repository.get_root_path`.
Below is the the instruction that describes the task: ### Input: See :py:meth:`~stash.repository.Repository.get_root_path`. ### Response: def get_root_path(self, path): """See :py:meth:`~stash.repository.Repository.get_root_path`.""" # Look at the directories present in the current working director...
def get_schema(frame, name, keys=None, con=None, dtype=None): """ Get the SQL db table schema for the given frame. Parameters ---------- frame : DataFrame name : string name of SQL table keys : string or sequence, default: None columns to use a primary key con: an open S...
Get the SQL db table schema for the given frame. Parameters ---------- frame : DataFrame name : string name of SQL table keys : string or sequence, default: None columns to use a primary key con: an open SQL database connection object or a SQLAlchemy connectable Using SQ...
Below is the the instruction that describes the task: ### Input: Get the SQL db table schema for the given frame. Parameters ---------- frame : DataFrame name : string name of SQL table keys : string or sequence, default: None columns to use a primary key con: an open SQL da...
def term(name): ''' Send a TERM to service via daemontools CLI Example: .. code-block:: bash salt '*' daemontools.term <service name> ''' cmd = 'svc -t {0}'.format(_service_path(name)) return not __salt__['cmd.retcode'](cmd, python_shell=False)
Send a TERM to service via daemontools CLI Example: .. code-block:: bash salt '*' daemontools.term <service name>
Below is the the instruction that describes the task: ### Input: Send a TERM to service via daemontools CLI Example: .. code-block:: bash salt '*' daemontools.term <service name> ### Response: def term(name): ''' Send a TERM to service via daemontools CLI Example: .. code-block...
def check_exists(self): ''' Check if resource exists, update self.exists, returns Returns: None: sets self.exists ''' response = self.repo.api.http_request('HEAD', self.uri) self.status_code = response.status_code # resource exists if self.status_code == 200: self.exists = True # resource no ...
Check if resource exists, update self.exists, returns Returns: None: sets self.exists
Below is the the instruction that describes the task: ### Input: Check if resource exists, update self.exists, returns Returns: None: sets self.exists ### Response: def check_exists(self): ''' Check if resource exists, update self.exists, returns Returns: None: sets self.exists ''' response =...
def __get_keywords(self): """ Get all the keywords related of this page Returns: An array of strings """ txt = self.text for line in txt: for word in split_words(line): yield(word)
Get all the keywords related of this page Returns: An array of strings
Below is the the instruction that describes the task: ### Input: Get all the keywords related of this page Returns: An array of strings ### Response: def __get_keywords(self): """ Get all the keywords related of this page Returns: An array of strings ...
def paired_environment_phenotype_grid_circles(environment, phenotypes, **kwargs): """ Plots the given environment (EnvironmentFile object) and phenotypes (2d array of binary strings) onto the same image and saves the image based on the name of the environmen...
Plots the given environment (EnvironmentFile object) and phenotypes (2d array of binary strings) onto the same image and saves the image based on the name of the environment file. The environment file will be represented by coloring square cells, while the phenotypes are represented as concentric circle...
Below is the the instruction that describes the task: ### Input: Plots the given environment (EnvironmentFile object) and phenotypes (2d array of binary strings) onto the same image and saves the image based on the name of the environment file. The environment file will be represented by coloring square...
def save(self, destination, **kwargs): """Serialize and save a model. Example: end_model = EndModel(...) end_model.train_model(...) end_model.save("my_end_model.pkl") """ with open(destination, "wb") as f: torch.save(self, f, **kwargs)
Serialize and save a model. Example: end_model = EndModel(...) end_model.train_model(...) end_model.save("my_end_model.pkl")
Below is the the instruction that describes the task: ### Input: Serialize and save a model. Example: end_model = EndModel(...) end_model.train_model(...) end_model.save("my_end_model.pkl") ### Response: def save(self, destination, **kwargs): """Serialize and sa...
def apply(self, func, axis=0, broadcast=None, reduce=None, result_type=None): """ Analogous to DataFrame.apply, for SparseDataFrame Parameters ---------- func : function Function to apply to each column axis : {0, 1, 'index', 'columns'} ...
Analogous to DataFrame.apply, for SparseDataFrame Parameters ---------- func : function Function to apply to each column axis : {0, 1, 'index', 'columns'} broadcast : bool, default False For aggregation functions, return object of same size with values ...
Below is the the instruction that describes the task: ### Input: Analogous to DataFrame.apply, for SparseDataFrame Parameters ---------- func : function Function to apply to each column axis : {0, 1, 'index', 'columns'} broadcast : bool, default False ...
def stream(self, callback=None): """ Runtime copy of job messages. This required the 'stream` flag to be set to True otherwise it will not be able to copy any output, while it will block until the process exits. :note: This function will block until it reaches end of stream or the proce...
Runtime copy of job messages. This required the 'stream` flag to be set to True otherwise it will not be able to copy any output, while it will block until the process exits. :note: This function will block until it reaches end of stream or the process is no longer running. :param callback: ca...
Below is the the instruction that describes the task: ### Input: Runtime copy of job messages. This required the 'stream` flag to be set to True otherwise it will not be able to copy any output, while it will block until the process exits. :note: This function will block until it reaches end of str...
def _log_likelihood_transit_plus_line(theta, params, model, t, data_flux, err_flux, priorbounds): ''' Given a batman TransitModel and its proposed parameters (theta), update the batman params object with the proposed parameters and evaluate the gaussian likelihood. ...
Given a batman TransitModel and its proposed parameters (theta), update the batman params object with the proposed parameters and evaluate the gaussian likelihood. Note: the priorbounds are only needed to parse theta.
Below is the the instruction that describes the task: ### Input: Given a batman TransitModel and its proposed parameters (theta), update the batman params object with the proposed parameters and evaluate the gaussian likelihood. Note: the priorbounds are only needed to parse theta. ### Response: def _...
def new_sent(self, text, ID=None, **kwargs): ''' Create a new sentence and add it to this Document ''' if ID is None: ID = next(self.__idgen) return self.add_sent(Sentence(text, ID=ID, **kwargs))
Create a new sentence and add it to this Document
Below is the the instruction that describes the task: ### Input: Create a new sentence and add it to this Document ### Response: def new_sent(self, text, ID=None, **kwargs): ''' Create a new sentence and add it to this Document ''' if ID is None: ID = next(self.__idgen) return s...
def authenticate(self, request): """ Returns two-tuple of (user, token) if authentication succeeds, or None otherwise. """ try: oauth_request = oauth_provider.utils.get_oauth_request(request) except oauth.Error as err: raise exceptions.Authenticati...
Returns two-tuple of (user, token) if authentication succeeds, or None otherwise.
Below is the the instruction that describes the task: ### Input: Returns two-tuple of (user, token) if authentication succeeds, or None otherwise. ### Response: def authenticate(self, request): """ Returns two-tuple of (user, token) if authentication succeeds, or None otherwise. ...
def update_priority(self, tree_idx_list, priority_list): """ Update priorities of the elements in the tree """ for tree_idx, priority, segment_tree in zip(tree_idx_list, priority_list, self.segment_trees): segment_tree.update(tree_idx, priority)
Update priorities of the elements in the tree
Below is the the instruction that describes the task: ### Input: Update priorities of the elements in the tree ### Response: def update_priority(self, tree_idx_list, priority_list): """ Update priorities of the elements in the tree """ for tree_idx, priority, segment_tree in zip(tree_idx_list, prio...
def indices_removed(lst, idxs): '''Returns a copy of lst with each index in idxs removed.''' ret = [item for k,item in enumerate(lst) if k not in idxs] return type(lst)(ret)
Returns a copy of lst with each index in idxs removed.
Below is the the instruction that describes the task: ### Input: Returns a copy of lst with each index in idxs removed. ### Response: def indices_removed(lst, idxs): '''Returns a copy of lst with each index in idxs removed.''' ret = [item for k,item in enumerate(lst) if k not in idxs] return type(lst)(...
def _aggregate_one_result( self, sock_info, slave_ok, cmd, collation=None, session=None): """Internal helper to run an aggregate that returns a single result.""" result = self._command( sock_info, cmd, slave_ok, codec_options=self.__write_respo...
Internal helper to run an aggregate that returns a single result.
Below is the the instruction that describes the task: ### Input: Internal helper to run an aggregate that returns a single result. ### Response: def _aggregate_one_result( self, sock_info, slave_ok, cmd, collation=None, session=None): """Internal helper to run an aggregate that returns a single...
def download_rdf(self, force=False): """Ensures a fresh-enough RDF file is downloaded and extracted. Returns True on error.""" if self.downloading: return True if not force and (os.path.exists(RDF_PATH) and (time.time() - os.path.getmtime(RDF_PATH)) < RDF_MA...
Ensures a fresh-enough RDF file is downloaded and extracted. Returns True on error.
Below is the the instruction that describes the task: ### Input: Ensures a fresh-enough RDF file is downloaded and extracted. Returns True on error. ### Response: def download_rdf(self, force=False): """Ensures a fresh-enough RDF file is downloaded and extracted. Returns True on error."""...
def location_purge(location_id, delete=False, verbosity=0): """Print and conditionally delete files not referenced by meta data. :param location_id: Id of the :class:`~resolwe.flow.models.DataLocation` model that data objects reference to. :param delete: If ``True``, then delete unreference...
Print and conditionally delete files not referenced by meta data. :param location_id: Id of the :class:`~resolwe.flow.models.DataLocation` model that data objects reference to. :param delete: If ``True``, then delete unreferenced files.
Below is the the instruction that describes the task: ### Input: Print and conditionally delete files not referenced by meta data. :param location_id: Id of the :class:`~resolwe.flow.models.DataLocation` model that data objects reference to. :param delete: If ``True``, then delete unreferen...
def sum(self, field): """ Returns the sum of the field in the result set of the query by wrapping the query and performing a SUM aggregate of the specified field :param field: the field to pass to the SUM aggregate :type field: str :return: The sum of the specified field...
Returns the sum of the field in the result set of the query by wrapping the query and performing a SUM aggregate of the specified field :param field: the field to pass to the SUM aggregate :type field: str :return: The sum of the specified field :rtype: int
Below is the the instruction that describes the task: ### Input: Returns the sum of the field in the result set of the query by wrapping the query and performing a SUM aggregate of the specified field :param field: the field to pass to the SUM aggregate :type field: str :return: The...
def init_app(self, app): """Initialize a :class:`~flask.Flask` application for use with this extension. """ self._jobs = [] if not hasattr(app, 'extensions'): app.extensions = {} app.extensions['restpoints'] = self app.restpoints_instance = self ...
Initialize a :class:`~flask.Flask` application for use with this extension.
Below is the the instruction that describes the task: ### Input: Initialize a :class:`~flask.Flask` application for use with this extension. ### Response: def init_app(self, app): """Initialize a :class:`~flask.Flask` application for use with this extension. """ self._jobs =...
def show_listener(self, lbaas_listener, **_params): """Fetches information for a lbaas_listener.""" return self.get(self.lbaas_listener_path % (lbaas_listener), params=_params)
Fetches information for a lbaas_listener.
Below is the the instruction that describes the task: ### Input: Fetches information for a lbaas_listener. ### Response: def show_listener(self, lbaas_listener, **_params): """Fetches information for a lbaas_listener.""" return self.get(self.lbaas_listener_path % (lbaas_listener), ...
def main(xmpp_server, xmpp_port, peer_name, node_name, app_id, xmpp_jid=None, xmpp_password=None): """ Runs the framework :param xmpp_server: Address of the XMPP server :param xmpp_port: Port of the XMPP server :param peer_name: Name of the peer :param node_name: Name (also, UID) of th...
Runs the framework :param xmpp_server: Address of the XMPP server :param xmpp_port: Port of the XMPP server :param peer_name: Name of the peer :param node_name: Name (also, UID) of the node hosting the peer :param app_id: Application ID :param xmpp_jid: XMPP JID, None for Anonymous login :p...
Below is the the instruction that describes the task: ### Input: Runs the framework :param xmpp_server: Address of the XMPP server :param xmpp_port: Port of the XMPP server :param peer_name: Name of the peer :param node_name: Name (also, UID) of the node hosting the peer :param app_id: Applicat...
def filtered_list(cls, name=None, obj=None): """List datacenters matching name and compatible with obj""" options = {} if name: options['id'] = cls.usable_id(name) def obj_ok(dc, obj): if not obj or obj['datacenter_id'] == dc['id']: return...
List datacenters matching name and compatible with obj
Below is the the instruction that describes the task: ### Input: List datacenters matching name and compatible with obj ### Response: def filtered_list(cls, name=None, obj=None): """List datacenters matching name and compatible with obj""" options = {} if name: o...
def wait_for_element_visible(self, selector, by=By.CSS_SELECTOR, timeout=settings.LARGE_TIMEOUT): """ Waits for an element to appear in the HTML of a page. The element must be visible (it cannot be hidden). """ if page_utils.is_xpath_selector(selector): ...
Waits for an element to appear in the HTML of a page. The element must be visible (it cannot be hidden).
Below is the the instruction that describes the task: ### Input: Waits for an element to appear in the HTML of a page. The element must be visible (it cannot be hidden). ### Response: def wait_for_element_visible(self, selector, by=By.CSS_SELECTOR, timeout=settings.LARG...
def skill_update(self, skill_id, data, **kwargs): "https://developer.zendesk.com/rest_api/docs/chat/skills#update-skill-by-id" api_path = "/api/v2/skills/{skill_id}" api_path = api_path.format(skill_id=skill_id) return self.call(api_path, method="PUT", data=data, **kwargs)
https://developer.zendesk.com/rest_api/docs/chat/skills#update-skill-by-id
Below is the the instruction that describes the task: ### Input: https://developer.zendesk.com/rest_api/docs/chat/skills#update-skill-by-id ### Response: def skill_update(self, skill_id, data, **kwargs): "https://developer.zendesk.com/rest_api/docs/chat/skills#update-skill-by-id" api_path = "/api/v...
def transition(self, duration, brightness=None, temperature=None): """ Transition wrapper. Short-circuit transition if necessary. :param duration: Duration of transition. :param brightness: Transition to this brightness. :param temperature: Transition to this temperature. ...
Transition wrapper. Short-circuit transition if necessary. :param duration: Duration of transition. :param brightness: Transition to this brightness. :param temperature: Transition to this temperature.
Below is the the instruction that describes the task: ### Input: Transition wrapper. Short-circuit transition if necessary. :param duration: Duration of transition. :param brightness: Transition to this brightness. :param temperature: Transition to this temperature. ### Response: ...
def scatter_master_notifications(self): """Generate children notifications from a master notification Also update notification number Master notification are raised when a notification must be sent out. They are not launched by reactionners (only children are) but they are used to build...
Generate children notifications from a master notification Also update notification number Master notification are raised when a notification must be sent out. They are not launched by reactionners (only children are) but they are used to build the children notifications. From ...
Below is the the instruction that describes the task: ### Input: Generate children notifications from a master notification Also update notification number Master notification are raised when a notification must be sent out. They are not launched by reactionners (only children are) but they...
def disconnect(self): """ Disconnect from a TWS or IB gateway application. This will clear all session state. """ if not self.client.isConnected(): return stats = self.client.connectionStats() self._logger.info( f'Disconnecting from {self.c...
Disconnect from a TWS or IB gateway application. This will clear all session state.
Below is the the instruction that describes the task: ### Input: Disconnect from a TWS or IB gateway application. This will clear all session state. ### Response: def disconnect(self): """ Disconnect from a TWS or IB gateway application. This will clear all session state. ""...
def _create_one(self, ctx): """ Creates an instance to be saved when a model is created. """ assert isinstance(ctx, ResourceQueryContext) fields = dict_pick(ctx.data, self._model_columns) model = self.model_cls(**fields) return model
Creates an instance to be saved when a model is created.
Below is the the instruction that describes the task: ### Input: Creates an instance to be saved when a model is created. ### Response: def _create_one(self, ctx): """ Creates an instance to be saved when a model is created. """ assert isinstance(ctx, ResourceQueryContext) ...
def get_vaults(self): """Gets the vault list resulting from the search. return: (osid.authorization.VaultList) - the vault list raise: IllegalState - list has already been retrieved *compliance: mandatory -- This method must be implemented.* """ if self.retrieved: ...
Gets the vault list resulting from the search. return: (osid.authorization.VaultList) - the vault list raise: IllegalState - list has already been retrieved *compliance: mandatory -- This method must be implemented.*
Below is the the instruction that describes the task: ### Input: Gets the vault list resulting from the search. return: (osid.authorization.VaultList) - the vault list raise: IllegalState - list has already been retrieved *compliance: mandatory -- This method must be implemented.* ### Resp...
def construct_task_instance(self, session=None, lock_for_update=False): """ Construct a TaskInstance from the database based on the primary key :param session: DB session. :param lock_for_update: if True, indicates that the database should lock the TaskInstance (issuing a FO...
Construct a TaskInstance from the database based on the primary key :param session: DB session. :param lock_for_update: if True, indicates that the database should lock the TaskInstance (issuing a FOR UPDATE clause) until the session is committed.
Below is the the instruction that describes the task: ### Input: Construct a TaskInstance from the database based on the primary key :param session: DB session. :param lock_for_update: if True, indicates that the database should lock the TaskInstance (issuing a FOR UPDATE clause) until ...
def list_renderers(*args): ''' List the renderers loaded on the minion .. versionadded:: 2015.5.0 CLI Example: .. code-block:: bash salt '*' sys.list_renderers Render names can be specified as globs. .. code-block:: bash salt '*' sys.list_renderers 'yaml*' ''' ...
List the renderers loaded on the minion .. versionadded:: 2015.5.0 CLI Example: .. code-block:: bash salt '*' sys.list_renderers Render names can be specified as globs. .. code-block:: bash salt '*' sys.list_renderers 'yaml*'
Below is the the instruction that describes the task: ### Input: List the renderers loaded on the minion .. versionadded:: 2015.5.0 CLI Example: .. code-block:: bash salt '*' sys.list_renderers Render names can be specified as globs. .. code-block:: bash salt '*' sys.list_...
def _submit(self, pathfile, filedata, filename): ''' Submit either a file from disk, or a in-memory file to the solver service, and return the request ID associated with the new captcha task. ''' if pathfile and os.path.exists(pathfile): files = {'file': open(pathfile, 'rb')} elif filedata: assert fil...
Submit either a file from disk, or a in-memory file to the solver service, and return the request ID associated with the new captcha task.
Below is the the instruction that describes the task: ### Input: Submit either a file from disk, or a in-memory file to the solver service, and return the request ID associated with the new captcha task. ### Response: def _submit(self, pathfile, filedata, filename): ''' Submit either a file from disk, or a i...
def check_path_consistency(self, resource): '''Path arguments must be consistent for all methods.''' msg = ('Method "{}" path variables {}) do not conform with the ' 'resource subpath declaration ({}).') errors = [] # If subpath is not set, it will be detected by another c...
Path arguments must be consistent for all methods.
Below is the the instruction that describes the task: ### Input: Path arguments must be consistent for all methods. ### Response: def check_path_consistency(self, resource): '''Path arguments must be consistent for all methods.''' msg = ('Method "{}" path variables {}) do not conform with the ' ...
async def starttls( self, server_hostname: str = None, validate_certs: bool = None, client_cert: DefaultStrType = _default, client_key: DefaultStrType = _default, cert_bundle: DefaultStrType = _default, tls_context: DefaultSSLContextType = _default, timeou...
Puts the connection to the SMTP server into TLS mode. If there has been no previous EHLO or HELO command this session, this method tries ESMTP EHLO first. If the server supports TLS, this will encrypt the rest of the SMTP session. If you provide the keyfile and certfile parameters, ...
Below is the the instruction that describes the task: ### Input: Puts the connection to the SMTP server into TLS mode. If there has been no previous EHLO or HELO command this session, this method tries ESMTP EHLO first. If the server supports TLS, this will encrypt the rest of the SMTP ...
def start_at(self, start_at): """ Sets the start_at of this Shift. RFC 3339; shifted to location timezone + offset. Precision up to the minute is respected; seconds are truncated. :param start_at: The start_at of this Shift. :type: str """ if start_at is None: ...
Sets the start_at of this Shift. RFC 3339; shifted to location timezone + offset. Precision up to the minute is respected; seconds are truncated. :param start_at: The start_at of this Shift. :type: str
Below is the the instruction that describes the task: ### Input: Sets the start_at of this Shift. RFC 3339; shifted to location timezone + offset. Precision up to the minute is respected; seconds are truncated. :param start_at: The start_at of this Shift. :type: str ### Response: def start...
def _param_grad_helper(self,X,X2,target): """Return shape is NxMx(Ntheta)""" if X2 is None: X2 = X FX = np.column_stack([f(X) for f in self.F]) FX2 = np.column_stack([f(X2) for f in self.F]) DER = np.zeros((self.n,self.n,self.n)) for i in range(self.n): DER[i,...
Return shape is NxMx(Ntheta)
Below is the the instruction that describes the task: ### Input: Return shape is NxMx(Ntheta) ### Response: def _param_grad_helper(self,X,X2,target): """Return shape is NxMx(Ntheta)""" if X2 is None: X2 = X FX = np.column_stack([f(X) for f in self.F]) FX2 = np.column_stack([f(X2) fo...