code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def write(self, output_buffer, kmip_version=enums.KMIPVersion.KMIP_1_0): """ Write the data encoding the DeriveKey request payload to a stream. Args: output_buffer (stream): A data stream in which to encode object data, supporting a write method; usually a BytearrayS...
Write the data encoding the DeriveKey request payload to a stream. Args: output_buffer (stream): A data stream in which to encode object data, supporting a write method; usually a BytearrayStream object. kmip_version (KMIPVersion): An enumeration defining...
Below is the the instruction that describes the task: ### Input: Write the data encoding the DeriveKey request payload to a stream. Args: output_buffer (stream): A data stream in which to encode object data, supporting a write method; usually a BytearrayStream ob...
def id_(reset=False): ''' .. versionadded:: 2016.3.0 Return monit unique id. reset : False Reset current id and generate a new id when it's True. CLI Example: .. code-block:: bash salt '*' monit.id [reset=True] ''' if reset: id_pattern = re.compile(r'Monit id...
.. versionadded:: 2016.3.0 Return monit unique id. reset : False Reset current id and generate a new id when it's True. CLI Example: .. code-block:: bash salt '*' monit.id [reset=True]
Below is the the instruction that describes the task: ### Input: .. versionadded:: 2016.3.0 Return monit unique id. reset : False Reset current id and generate a new id when it's True. CLI Example: .. code-block:: bash salt '*' monit.id [reset=True] ### Response: def id_(reset=...
def db020(self, value=None): """ Corresponds to IDD Field `db020` mean coincident wet-bulb temperature to Dry-bulb temperature corresponding to 2.0% annual cumulative frequency of occurrence (warm conditions) Args: value (float): value for IDD Field `db020` ...
Corresponds to IDD Field `db020` mean coincident wet-bulb temperature to Dry-bulb temperature corresponding to 2.0% annual cumulative frequency of occurrence (warm conditions) Args: value (float): value for IDD Field `db020` Unit: C if `value` is None...
Below is the the instruction that describes the task: ### Input: Corresponds to IDD Field `db020` mean coincident wet-bulb temperature to Dry-bulb temperature corresponding to 2.0% annual cumulative frequency of occurrence (warm conditions) Args: value (float): value for IDD Fie...
def check_instance( mzn, *dzn_files, data=None, include=None, stdlib_dir=None, globals_dir=None, allow_multiple_assignments=False ): """Perform instance checking on a model + data. This function calls the command ``minizinc --instance-check-only`` to check for consistency of the given model + data....
Perform instance checking on a model + data. This function calls the command ``minizinc --instance-check-only`` to check for consistency of the given model + data. Parameters ---------- mzn : str The minizinc model. This can be either the path to the ``.mzn`` file or the content of...
Below is the the instruction that describes the task: ### Input: Perform instance checking on a model + data. This function calls the command ``minizinc --instance-check-only`` to check for consistency of the given model + data. Parameters ---------- mzn : str The minizinc model. This ...
def get_voltage(self, channel, unit='V'): '''Reading voltage ''' adc_ch = self._ch_map[channel]['ADCV']['adc_ch'] address = self._ch_map[channel]['ADCV']['address'] raw = self._get_adc_value(address=address)[adc_ch] dac_offset = self._ch_cal[channel]['ADCV']['offset'] ...
Reading voltage
Below is the the instruction that describes the task: ### Input: Reading voltage ### Response: def get_voltage(self, channel, unit='V'): '''Reading voltage ''' adc_ch = self._ch_map[channel]['ADCV']['adc_ch'] address = self._ch_map[channel]['ADCV']['address'] raw = self._get...
def visit(self, func): """Run ``func`` on each object's path. Note: If ``func`` returns ``None`` (or doesn't return), iteration continues. However, if ``func`` returns anything else, it ceases and returns that value. Examples -------- >>> import zarr...
Run ``func`` on each object's path. Note: If ``func`` returns ``None`` (or doesn't return), iteration continues. However, if ``func`` returns anything else, it ceases and returns that value. Examples -------- >>> import zarr >>> g1 = zarr.group() ...
Below is the the instruction that describes the task: ### Input: Run ``func`` on each object's path. Note: If ``func`` returns ``None`` (or doesn't return), iteration continues. However, if ``func`` returns anything else, it ceases and returns that value. Examples ...
def _process_elem_text(elem, dic, subdic, text="@text", **options): """ :param elem: ET Element object which has elem.text :param dic: <container> (dict[-like]) object converted from elem :param subdic: Sub <container> object converted from elem :param options: Keyword options, see the descr...
:param elem: ET Element object which has elem.text :param dic: <container> (dict[-like]) object converted from elem :param subdic: Sub <container> object converted from elem :param options: Keyword options, see the description of :func:`elem_to_container` for more details. :return: None...
Below is the the instruction that describes the task: ### Input: :param elem: ET Element object which has elem.text :param dic: <container> (dict[-like]) object converted from elem :param subdic: Sub <container> object converted from elem :param options: Keyword options, see the description of :...
def number_cwt_peaks(x, n): """ This feature calculator searches for different peaks in x. To do so, x is smoothed by a ricker wavelet and for widths ranging from 1 to n. This feature calculator returns the number of peaks that occur at enough width scales and with sufficiently high Signal-to-Noise-Rati...
This feature calculator searches for different peaks in x. To do so, x is smoothed by a ricker wavelet and for widths ranging from 1 to n. This feature calculator returns the number of peaks that occur at enough width scales and with sufficiently high Signal-to-Noise-Ratio (SNR) :param x: the time series t...
Below is the the instruction that describes the task: ### Input: This feature calculator searches for different peaks in x. To do so, x is smoothed by a ricker wavelet and for widths ranging from 1 to n. This feature calculator returns the number of peaks that occur at enough width scales and with sufficien...
def QA_SU_save_stock_min(client=DATABASE, ui_log=None, ui_progress=None): """ 聚宽实现方式 save current day's stock_min data """ # 导入聚宽模块且进行登录 try: import jqdatasdk # 请自行将 JQUSERNAME 和 JQUSERPASSWD 修改为自己的账号密码 jqdatasdk.auth("JQUSERNAME", "JQUSERPASSWD") except: rais...
聚宽实现方式 save current day's stock_min data
Below is the the instruction that describes the task: ### Input: 聚宽实现方式 save current day's stock_min data ### Response: def QA_SU_save_stock_min(client=DATABASE, ui_log=None, ui_progress=None): """ 聚宽实现方式 save current day's stock_min data """ # 导入聚宽模块且进行登录 try: import jqdatasdk ...
def horizontal_layout(self, draw, slide): """ Augment slide with horizontal layout info """ padding = self.padding heading = slide['heading'] top = padding left = padding top += heading['height'] + padding rows = slide['rows'] for row in rows: ...
Augment slide with horizontal layout info
Below is the the instruction that describes the task: ### Input: Augment slide with horizontal layout info ### Response: def horizontal_layout(self, draw, slide): """ Augment slide with horizontal layout info """ padding = self.padding heading = slide['heading'] top = padding ...
def set_slug(apps, schema_editor): """ Create a slug for each Event already in the DB. """ Event = apps.get_model('spectator_events', 'Event') for e in Event.objects.all(): e.slug = generate_slug(e.pk) e.save(update_fields=['slug'])
Create a slug for each Event already in the DB.
Below is the the instruction that describes the task: ### Input: Create a slug for each Event already in the DB. ### Response: def set_slug(apps, schema_editor): """ Create a slug for each Event already in the DB. """ Event = apps.get_model('spectator_events', 'Event') for e in Event.objects.a...
def filesessionmaker(sessionmaker, file_manager, file_managers=None): u'''Wrapper of session maker adding link to a FileManager instance to session.:: file_manager = FileManager(cfg.TRANSIENT_ROOT, cfg.PERSISTENT_ROOT) filesessionmaker(sessionmaker(...), file_...
u'''Wrapper of session maker adding link to a FileManager instance to session.:: file_manager = FileManager(cfg.TRANSIENT_ROOT, cfg.PERSISTENT_ROOT) filesessionmaker(sessionmaker(...), file_manager)
Below is the the instruction that describes the task: ### Input: u'''Wrapper of session maker adding link to a FileManager instance to session.:: file_manager = FileManager(cfg.TRANSIENT_ROOT, cfg.PERSISTENT_ROOT) filesessionmaker(sessionmaker(...), file_manag...
def setup(self): """Setup does stuff only if there are no networks. This is so it only runs once at the start of the experiment. It first calls the same function in the super (see experiments.py in wallace). Then it adds a source to each network. """ if not self.networks...
Setup does stuff only if there are no networks. This is so it only runs once at the start of the experiment. It first calls the same function in the super (see experiments.py in wallace). Then it adds a source to each network.
Below is the the instruction that describes the task: ### Input: Setup does stuff only if there are no networks. This is so it only runs once at the start of the experiment. It first calls the same function in the super (see experiments.py in wallace). Then it adds a source to each network....
def aggregate(self, pipeline, **kwargs): """Perform an aggregation and make sure that result will be everytime CommandCursor. Will take care for pymongo version differencies :param pipeline: {list} of aggregation pipeline stages :return: {pymongo.command_cursor.CommandCursor} """...
Perform an aggregation and make sure that result will be everytime CommandCursor. Will take care for pymongo version differencies :param pipeline: {list} of aggregation pipeline stages :return: {pymongo.command_cursor.CommandCursor}
Below is the the instruction that describes the task: ### Input: Perform an aggregation and make sure that result will be everytime CommandCursor. Will take care for pymongo version differencies :param pipeline: {list} of aggregation pipeline stages :return: {pymongo.command_cursor.CommandCu...
def countByValue(self): """Apply countByValue to every RDD.abs :rtype: DStream .. warning:: Implemented as a local operation. Example: >>> import pysparkling >>> sc = pysparkling.Context() >>> ssc = pysparkling.streaming.StreamingContext(sc, 0.1) ...
Apply countByValue to every RDD.abs :rtype: DStream .. warning:: Implemented as a local operation. Example: >>> import pysparkling >>> sc = pysparkling.Context() >>> ssc = pysparkling.streaming.StreamingContext(sc, 0.1) >>> ( ... ssc ...
Below is the the instruction that describes the task: ### Input: Apply countByValue to every RDD.abs :rtype: DStream .. warning:: Implemented as a local operation. Example: >>> import pysparkling >>> sc = pysparkling.Context() >>> ssc = pysparkling.st...
def _get_address_family(table, instance): """ Function to derive address family from a junos table name. :params table: The name of the routing table :returns: address family """ address_family_mapping = {"inet": "ipv4", "inet6": "ipv6", "inetflow": "flow"} if in...
Function to derive address family from a junos table name. :params table: The name of the routing table :returns: address family
Below is the the instruction that describes the task: ### Input: Function to derive address family from a junos table name. :params table: The name of the routing table :returns: address family ### Response: def _get_address_family(table, instance): """ Function to derive address f...
def generate_additional_context(self, matching_datasets): """Return additional information about matching datasets. Includes upload counts, related hubs, related tags. """ dataset_ids = [upload.id for upload in matching_datasets] tags = Tag.objects.filter( dataset__i...
Return additional information about matching datasets. Includes upload counts, related hubs, related tags.
Below is the the instruction that describes the task: ### Input: Return additional information about matching datasets. Includes upload counts, related hubs, related tags. ### Response: def generate_additional_context(self, matching_datasets): """Return additional information about matching datase...
def plot_pnlmoney(self): """ 画出pnl盈亏额散点图 """ plt.scatter(x=self.pnl.sell_date.apply(str), y=self.pnl.pnl_money) plt.gcf().autofmt_xdate() return plt
画出pnl盈亏额散点图
Below is the the instruction that describes the task: ### Input: 画出pnl盈亏额散点图 ### Response: def plot_pnlmoney(self): """ 画出pnl盈亏额散点图 """ plt.scatter(x=self.pnl.sell_date.apply(str), y=self.pnl.pnl_money) plt.gcf().autofmt_xdate() return plt
def to_perseus(graphs): """ Create a network table and the network dictionary for export to Perseus. :param graphs: Collection of networkx graphs >>> from perseuspy import nx >>> G = nx.random_graphs.barabasi_albert_graph(10, 3) >>> network_table, networks = nx.to_perseus([G]) """ ...
Create a network table and the network dictionary for export to Perseus. :param graphs: Collection of networkx graphs >>> from perseuspy import nx >>> G = nx.random_graphs.barabasi_albert_graph(10, 3) >>> network_table, networks = nx.to_perseus([G])
Below is the the instruction that describes the task: ### Input: Create a network table and the network dictionary for export to Perseus. :param graphs: Collection of networkx graphs >>> from perseuspy import nx >>> G = nx.random_graphs.barabasi_albert_graph(10, 3) >>> network_table, networks ...
def calcDrawingProbs(self): """ Returns a vector that contains the probabily of an item being from each position. We say that every item in a order vector is drawn with weight phi^i where i is its position. """ wmg = self.wmg phi = self.phi # We say the weight o...
Returns a vector that contains the probabily of an item being from each position. We say that every item in a order vector is drawn with weight phi^i where i is its position.
Below is the the instruction that describes the task: ### Input: Returns a vector that contains the probabily of an item being from each position. We say that every item in a order vector is drawn with weight phi^i where i is its position. ### Response: def calcDrawingProbs(self): """ Retur...
def _from_p(self, mode): """Convert the image from P or PA to RGB or RGBA.""" self._check_modes(("P", "PA")) if not self.palette: raise RuntimeError("Can't convert palettized image, missing palette.") pal = np.array(self.palette) pal = da.from_array(pal, chunks=pal.s...
Convert the image from P or PA to RGB or RGBA.
Below is the the instruction that describes the task: ### Input: Convert the image from P or PA to RGB or RGBA. ### Response: def _from_p(self, mode): """Convert the image from P or PA to RGB or RGBA.""" self._check_modes(("P", "PA")) if not self.palette: raise RuntimeError("Ca...
def register_on_clipboard_mode_changed(self, callback): """Set the callback function to consume on clipboard mode changed events. Callback receives a IClipboardModeChangedEvent object. Returns the callback_id """ event_type = library.VBoxEventType.on_clipboard_mode_chan...
Set the callback function to consume on clipboard mode changed events. Callback receives a IClipboardModeChangedEvent object. Returns the callback_id
Below is the the instruction that describes the task: ### Input: Set the callback function to consume on clipboard mode changed events. Callback receives a IClipboardModeChangedEvent object. Returns the callback_id ### Response: def register_on_clipboard_mode_changed(self, callback): ...
def role_add(self, role=None, login=None, envs=[], query='/roles/'): """ `login` - Login or username of user to add to `role` `role` - Role to add user to Add user to role """ data = {'login': self.args.login} juicer.utils.Log.log_debug( "Add Role...
`login` - Login or username of user to add to `role` `role` - Role to add user to Add user to role
Below is the the instruction that describes the task: ### Input: `login` - Login or username of user to add to `role` `role` - Role to add user to Add user to role ### Response: def role_add(self, role=None, login=None, envs=[], query='/roles/'): """ `login` - Login or username of ...
def track_trace(self, name, properties=None, severity=None): """Sends a single trace statement. Args: name (str). the trace statement.\n properties (dict). the set of custom properties the client wants attached to this data item. (defaults to: None)\n severity (str)....
Sends a single trace statement. Args: name (str). the trace statement.\n properties (dict). the set of custom properties the client wants attached to this data item. (defaults to: None)\n severity (str). the severity level of this trace, one of DEBUG, INFO, WARNING, ERROR, C...
Below is the the instruction that describes the task: ### Input: Sends a single trace statement. Args: name (str). the trace statement.\n properties (dict). the set of custom properties the client wants attached to this data item. (defaults to: None)\n severity (str). th...
def append(self, other: 'List') -> 'List': """Append other list to this list.""" if self.null(): return other return (self.tail().append(other)).cons(self.head())
Append other list to this list.
Below is the the instruction that describes the task: ### Input: Append other list to this list. ### Response: def append(self, other: 'List') -> 'List': """Append other list to this list.""" if self.null(): return other return (self.tail().append(other)).cons(self.head())
def current_position(self): """Return a tuple of (start, end).""" token = self.tokenizer.peek(0) if token: return token.start, token.end return self.tokenizer.position, self.tokenizer.position + 1
Return a tuple of (start, end).
Below is the the instruction that describes the task: ### Input: Return a tuple of (start, end). ### Response: def current_position(self): """Return a tuple of (start, end).""" token = self.tokenizer.peek(0) if token: return token.start, token.end return self.tokenizer....
def join_domain(domain, username=None, password=None, account_ou=None, account_exists=False, restart=False): ''' Join a computer to an Active Directory domain. Requires a reboot. Args: domain (str): The dom...
Join a computer to an Active Directory domain. Requires a reboot. Args: domain (str): The domain to which the computer should be joined, e.g. ``example.com`` username (str): Username of an account which is authorized to join computers to the specifi...
Below is the the instruction that describes the task: ### Input: Join a computer to an Active Directory domain. Requires a reboot. Args: domain (str): The domain to which the computer should be joined, e.g. ``example.com`` username (str): Username of an acc...
def find_slave_widgets(self,tab): """return all the frontends that do not own the kernel attached to the given widget/tab. Only find frontends owned by the current application. Selection based on connection file of the kernel. This function does the conversion tabNumber/wid...
return all the frontends that do not own the kernel attached to the given widget/tab. Only find frontends owned by the current application. Selection based on connection file of the kernel. This function does the conversion tabNumber/widget if needed.
Below is the the instruction that describes the task: ### Input: return all the frontends that do not own the kernel attached to the given widget/tab. Only find frontends owned by the current application. Selection based on connection file of the kernel. This function does the ...
def _generate_examples(self, filepath): """Generate examples for the Shapes3d dataset. Args: filepath: path to the Shapes3d hdf5 file. Yields: Dictionaries with images and the different labels. """ # Simultaneously iterating through the different data sets in the hdf5 # file will b...
Generate examples for the Shapes3d dataset. Args: filepath: path to the Shapes3d hdf5 file. Yields: Dictionaries with images and the different labels.
Below is the the instruction that describes the task: ### Input: Generate examples for the Shapes3d dataset. Args: filepath: path to the Shapes3d hdf5 file. Yields: Dictionaries with images and the different labels. ### Response: def _generate_examples(self, filepath): """Generate example...
def _lval_add_towards_polarity(x, polarity): """Compute the appropriate Lval "kind" for the limit of value `x` towards `polarity`. Either 'toinf' or 'pastzero' depending on the sign of `x` and the infinity direction of polarity. """ if x < 0: if polarity < 0: return Lval('toinf'...
Compute the appropriate Lval "kind" for the limit of value `x` towards `polarity`. Either 'toinf' or 'pastzero' depending on the sign of `x` and the infinity direction of polarity.
Below is the the instruction that describes the task: ### Input: Compute the appropriate Lval "kind" for the limit of value `x` towards `polarity`. Either 'toinf' or 'pastzero' depending on the sign of `x` and the infinity direction of polarity. ### Response: def _lval_add_towards_polarity(x, polarity): ...
def pairs(a): """Return array of pairs of adjacent elements in a. >>> pairs([1, 2, 3, 4]) array([[1, 2], [2, 3], [3, 4]]) """ a = np.asarray(a) return as_strided(a, shape=(a.size - 1, 2), strides=a.strides * 2)
Return array of pairs of adjacent elements in a. >>> pairs([1, 2, 3, 4]) array([[1, 2], [2, 3], [3, 4]])
Below is the the instruction that describes the task: ### Input: Return array of pairs of adjacent elements in a. >>> pairs([1, 2, 3, 4]) array([[1, 2], [2, 3], [3, 4]]) ### Response: def pairs(a): """Return array of pairs of adjacent elements in a. >>> pairs([1, 2, 3, 4]) ...
def getgroupcustominformationurl(idgroup, customfield="", *args, **kwargs): """Request Group Custom Information URL. See mambugroup module and pydoc for further information. See Mambu official developer documentation for further details, and info on parameters that may be implemented here in the futur...
Request Group Custom Information URL. See mambugroup module and pydoc for further information. See Mambu official developer documentation for further details, and info on parameters that may be implemented here in the future.
Below is the the instruction that describes the task: ### Input: Request Group Custom Information URL. See mambugroup module and pydoc for further information. See Mambu official developer documentation for further details, and info on parameters that may be implemented here in the future. ### Respons...
def setup(self, settings): ''' Setup kafka ''' KafkaBaseMonitor.setup(self, settings) self.zoo_client = KazooClient(hosts=settings['ZOOKEEPER_HOSTS']) self.zoo_client.start() self.path = settings['ZOOKEEPER_ASSIGN_PATH'] + settings['ZOOKEEPER_ID'] if not...
Setup kafka
Below is the the instruction that describes the task: ### Input: Setup kafka ### Response: def setup(self, settings): ''' Setup kafka ''' KafkaBaseMonitor.setup(self, settings) self.zoo_client = KazooClient(hosts=settings['ZOOKEEPER_HOSTS']) self.zoo_client.start() ...
def render_field_errors(field): """ Render field errors as html. """ if field.errors: html = """<p class="help-block">Error: {errors}</p>""".format( errors='. '.join(field.errors) ) return HTMLString(html) return None
Render field errors as html.
Below is the the instruction that describes the task: ### Input: Render field errors as html. ### Response: def render_field_errors(field): """ Render field errors as html. """ if field.errors: html = """<p class="help-block">Error: {errors}</p>""".format( errors='. '.join(field...
def _additions_remove_use_cd(**kwargs): ''' Remove VirtualBox Guest Additions. It uses the CD, connected by VirtualBox. ''' with _additions_mounted() as mount_point: kernel = __grains__.get('kernel', '') if kernel == 'Linux': return _additions_remove_linux_use_cd(mount_...
Remove VirtualBox Guest Additions. It uses the CD, connected by VirtualBox.
Below is the the instruction that describes the task: ### Input: Remove VirtualBox Guest Additions. It uses the CD, connected by VirtualBox. ### Response: def _additions_remove_use_cd(**kwargs): ''' Remove VirtualBox Guest Additions. It uses the CD, connected by VirtualBox. ''' with _add...
def on_status_update(self, channel, callback): """ Callback to execute on status of update of channel """ if channel not in self._callbacks: self._callbacks[channel] = [] self._callbacks[channel].append(callback)
Callback to execute on status of update of channel
Below is the the instruction that describes the task: ### Input: Callback to execute on status of update of channel ### Response: def on_status_update(self, channel, callback): """ Callback to execute on status of update of channel """ if channel not in self._callbacks: ...
def set_input_value(self, selector, value): """Set the value of the input matched by given selector.""" script = 'document.querySelector("%s").setAttribute("value", "%s")' script = script % (selector, value) self.evaluate(script)
Set the value of the input matched by given selector.
Below is the the instruction that describes the task: ### Input: Set the value of the input matched by given selector. ### Response: def set_input_value(self, selector, value): """Set the value of the input matched by given selector.""" script = 'document.querySelector("%s").setAttribute("value", "...
async def wait_stream(aiterable): """Wait for an asynchronous iterable to finish and return the last item. The iterable is executed within a safe stream context. A StreamEmpty exception is raised if the sequence is empty. """ async with streamcontext(aiterable) as streamer: async for item i...
Wait for an asynchronous iterable to finish and return the last item. The iterable is executed within a safe stream context. A StreamEmpty exception is raised if the sequence is empty.
Below is the the instruction that describes the task: ### Input: Wait for an asynchronous iterable to finish and return the last item. The iterable is executed within a safe stream context. A StreamEmpty exception is raised if the sequence is empty. ### Response: async def wait_stream(aiterable): """W...
def graph_to_dimacs(g, f): """ Persists the supplied graph in valid dimacs format into the file. Parameters ---------- g : `~medpy.graphcut.graph.Graph` A graph object to persist. f : file A file-like object. """ # write comments f.write('c Created by medpy\n') ...
Persists the supplied graph in valid dimacs format into the file. Parameters ---------- g : `~medpy.graphcut.graph.Graph` A graph object to persist. f : file A file-like object.
Below is the the instruction that describes the task: ### Input: Persists the supplied graph in valid dimacs format into the file. Parameters ---------- g : `~medpy.graphcut.graph.Graph` A graph object to persist. f : file A file-like object. ### Response: def graph_to_dimacs(g...
def diet_expert(x, hidden_size, params): """A two-layer feed-forward network with relu activation on hidden layer. Uses diet variables. Recomputes hidden layer on backprop to save activation memory. Args: x: a Tensor with shape [batch, io_size] hidden_size: an integer params: a diet variable HPara...
A two-layer feed-forward network with relu activation on hidden layer. Uses diet variables. Recomputes hidden layer on backprop to save activation memory. Args: x: a Tensor with shape [batch, io_size] hidden_size: an integer params: a diet variable HParams object. Returns: a Tensor with shape...
Below is the the instruction that describes the task: ### Input: A two-layer feed-forward network with relu activation on hidden layer. Uses diet variables. Recomputes hidden layer on backprop to save activation memory. Args: x: a Tensor with shape [batch, io_size] hidden_size: an integer params...
def add(self, effect): """ Add an LV2 plugin encapsulated as a jack client :param Lv2Effect effect: Effect that will be loaded as LV2 plugin encapsulated """ effect.instance = self.instance_index self.instance_index += 1 self.connection.send(ProtocolParser.add(e...
Add an LV2 plugin encapsulated as a jack client :param Lv2Effect effect: Effect that will be loaded as LV2 plugin encapsulated
Below is the the instruction that describes the task: ### Input: Add an LV2 plugin encapsulated as a jack client :param Lv2Effect effect: Effect that will be loaded as LV2 plugin encapsulated ### Response: def add(self, effect): """ Add an LV2 plugin encapsulated as a jack client ...
def rpc_get_blockstack_ops_hash_at( self, block_id, **con_info ): """ Get the hash over the sequence of names and namespaces altered at the given block. Used by SNV clients. Returns {'status': True, 'ops_hash': ops_hash} on success Returns {'error': ...} on error """ ...
Get the hash over the sequence of names and namespaces altered at the given block. Used by SNV clients. Returns {'status': True, 'ops_hash': ops_hash} on success Returns {'error': ...} on error
Below is the the instruction that describes the task: ### Input: Get the hash over the sequence of names and namespaces altered at the given block. Used by SNV clients. Returns {'status': True, 'ops_hash': ops_hash} on success Returns {'error': ...} on error ### Response: def rpc_get_block...
def value(self): """ Get the value of the match, using formatter if defined. :return: :rtype: """ if self._value: return self._value if self.formatter: return self.formatter(self.raw) return self.raw
Get the value of the match, using formatter if defined. :return: :rtype:
Below is the the instruction that describes the task: ### Input: Get the value of the match, using formatter if defined. :return: :rtype: ### Response: def value(self): """ Get the value of the match, using formatter if defined. :return: :rtype: """ i...
def get_banks(self): """Pass through to provider BankLookupSession.get_banks""" # Implemented from kitosid template for - # osid.resource.BinLookupSession.get_bins_template catalogs = self._get_provider_session('bank_lookup_session').get_banks() cat_list = [] for cat in c...
Pass through to provider BankLookupSession.get_banks
Below is the the instruction that describes the task: ### Input: Pass through to provider BankLookupSession.get_banks ### Response: def get_banks(self): """Pass through to provider BankLookupSession.get_banks""" # Implemented from kitosid template for - # osid.resource.BinLookupSession.get_...
def make_assess_status_func(*args, **kwargs): """Creates an assess_status_func() suitable for handing to pause_unit() and resume_unit(). This uses the _determine_os_workload_status(...) function to determine what the workload_status should be for the unit. If the unit is not in maintenance or acti...
Creates an assess_status_func() suitable for handing to pause_unit() and resume_unit(). This uses the _determine_os_workload_status(...) function to determine what the workload_status should be for the unit. If the unit is not in maintenance or active states, then the message is returned to the ca...
Below is the the instruction that describes the task: ### Input: Creates an assess_status_func() suitable for handing to pause_unit() and resume_unit(). This uses the _determine_os_workload_status(...) function to determine what the workload_status should be for the unit. If the unit is not in mai...
def check_generic_request(self, item_session: ItemSession) -> Tuple[bool, str]: '''Check URL filters and scripting hook. Returns: tuple: (bool, str) ''' verdict, reason, test_info = self.consult_filters( item_session.request.url_info, item_session.url...
Check URL filters and scripting hook. Returns: tuple: (bool, str)
Below is the the instruction that describes the task: ### Input: Check URL filters and scripting hook. Returns: tuple: (bool, str) ### Response: def check_generic_request(self, item_session: ItemSession) -> Tuple[bool, str]: '''Check URL filters and scripting hook. Returns: ...
def geodetic2geocentric(theta, alt): """ Conversion from geodetic to geocentric coordinates by using the WGS84 spheroid. :param theta: colatitude (float, rad) :param alt: altitude (float, km) :return gccolat: geocentric colatitude (float, rad) d: gccolat minus theta (float, rad) ...
Conversion from geodetic to geocentric coordinates by using the WGS84 spheroid. :param theta: colatitude (float, rad) :param alt: altitude (float, km) :return gccolat: geocentric colatitude (float, rad) d: gccolat minus theta (float, rad) r: geocentric radius (float, km)
Below is the the instruction that describes the task: ### Input: Conversion from geodetic to geocentric coordinates by using the WGS84 spheroid. :param theta: colatitude (float, rad) :param alt: altitude (float, km) :return gccolat: geocentric colatitude (float, rad) d: gccolat minus theta (...
def Prep(self, size, additionalBytes): """ Prep prepares to write an element of `size` after `additional_bytes` have been written, e.g. if you write a string, you need to align such the int length field is aligned to SizeInt32, and the string data follows it directly. If ...
Prep prepares to write an element of `size` after `additional_bytes` have been written, e.g. if you write a string, you need to align such the int length field is aligned to SizeInt32, and the string data follows it directly. If all you need to do is align, `additionalBytes` will be 0.
Below is the the instruction that describes the task: ### Input: Prep prepares to write an element of `size` after `additional_bytes` have been written, e.g. if you write a string, you need to align such the int length field is aligned to SizeInt32, and the string data follows it directly. ...
def find_mod_objs(modname, onlylocals=False): """ Returns all the public attributes of a module referenced by name. .. note:: The returned list *not* include subpackages or modules of `modname`,nor does it include private attributes (those that beginwith '_' or are not in `__all__`). ...
Returns all the public attributes of a module referenced by name. .. note:: The returned list *not* include subpackages or modules of `modname`,nor does it include private attributes (those that beginwith '_' or are not in `__all__`). Parameters ---------- modname : str ...
Below is the the instruction that describes the task: ### Input: Returns all the public attributes of a module referenced by name. .. note:: The returned list *not* include subpackages or modules of `modname`,nor does it include private attributes (those that beginwith '_' or are not in...
def load_wc(cls, stream): """Return a `Wilson` instance initialized by a WCxf file-like object""" wc = wcxf.WC.load(stream) return cls.from_wc(wc)
Return a `Wilson` instance initialized by a WCxf file-like object
Below is the the instruction that describes the task: ### Input: Return a `Wilson` instance initialized by a WCxf file-like object ### Response: def load_wc(cls, stream): """Return a `Wilson` instance initialized by a WCxf file-like object""" wc = wcxf.WC.load(stream) return cls.from_wc(wc)
def add_rule(name, localport, protocol='tcp', action='allow', dir='in', remoteip='any'): ''' .. versionadded:: 2015.5.0 Add a new inbound or outbound rule to the firewall policy Args: name (str): The name of the rule. Must be unique and cannot be "all". Required. ...
.. versionadded:: 2015.5.0 Add a new inbound or outbound rule to the firewall policy Args: name (str): The name of the rule. Must be unique and cannot be "all". Required. localport (int): The port the rule applies to. Must be a number between 0 and 65535. Can be a ran...
Below is the the instruction that describes the task: ### Input: .. versionadded:: 2015.5.0 Add a new inbound or outbound rule to the firewall policy Args: name (str): The name of the rule. Must be unique and cannot be "all". Required. localport (int): The port the rule appli...
def _handle_chat_event(self, event: events.ChatMessageWasReceived) -> None: """ Not thread-safe. """ for subscriber in self._chat_subscribers: try: subscriber(event) except Exception: LOG.exception(self._prefix_log_message( ...
Not thread-safe.
Below is the the instruction that describes the task: ### Input: Not thread-safe. ### Response: def _handle_chat_event(self, event: events.ChatMessageWasReceived) -> None: """ Not thread-safe. """ for subscriber in self._chat_subscribers: try: subscriber...
def requires_role(self, roles): """ Require specific configured roles for access to a :mod:`flask` route. :param roles: Role or list of roles to test for access (only one role is required to pass). :type roles: str OR list(str) :raises: FlaskKeystoneForbidd...
Require specific configured roles for access to a :mod:`flask` route. :param roles: Role or list of roles to test for access (only one role is required to pass). :type roles: str OR list(str) :raises: FlaskKeystoneForbidden This method will gate a particular endpo...
Below is the the instruction that describes the task: ### Input: Require specific configured roles for access to a :mod:`flask` route. :param roles: Role or list of roles to test for access (only one role is required to pass). :type roles: str OR list(str) :raises: Fla...
async def _send_frame(self, message: bytes, opcode: int, compress: Optional[int]=None) -> None: """Send a frame over the websocket with message as its payload.""" if self._closing: ws_logger.warning('websocket connection is closing.') rsv = 0 # Onl...
Send a frame over the websocket with message as its payload.
Below is the the instruction that describes the task: ### Input: Send a frame over the websocket with message as its payload. ### Response: async def _send_frame(self, message: bytes, opcode: int, compress: Optional[int]=None) -> None: """Send a frame over the websocket with messa...
def override_colors(self, colors): """Override default color of elements. :param colors: New color value for given elements :type colors: dict """ if not isinstance(colors, dict): return for key in self._color[True]: if key in colors: ...
Override default color of elements. :param colors: New color value for given elements :type colors: dict
Below is the the instruction that describes the task: ### Input: Override default color of elements. :param colors: New color value for given elements :type colors: dict ### Response: def override_colors(self, colors): """Override default color of elements. :param colors: New colo...
def _text_position(size, text, font): """ Returns the left-top point where the text should be positioned. """ width, height = font.getsize(text) left = (size - width) / 2.0 top = (size - height) / 3.0 return left, top
Returns the left-top point where the text should be positioned.
Below is the the instruction that describes the task: ### Input: Returns the left-top point where the text should be positioned. ### Response: def _text_position(size, text, font): """ Returns the left-top point where the text should be positioned. """ width, height = font.getsi...
def delete_note(self, note_id): """ Method to permanently delete a note Arguments: - note_id (string): key of the note to trash Returns: A tuple `(note, status)` - note (dict): an empty dict or an error message - status (int): 0 on success and -...
Method to permanently delete a note Arguments: - note_id (string): key of the note to trash Returns: A tuple `(note, status)` - note (dict): an empty dict or an error message - status (int): 0 on success and -1 otherwise
Below is the the instruction that describes the task: ### Input: Method to permanently delete a note Arguments: - note_id (string): key of the note to trash Returns: A tuple `(note, status)` - note (dict): an empty dict or an error message - status ...
def registry_comparison(registry0, registry1): """Compares two dictionaries of registry keys returning their difference.""" comparison = {'created_keys': {}, 'deleted_keys': [], 'created_values': {}, 'deleted_values': {}, 'modified_values':...
Compares two dictionaries of registry keys returning their difference.
Below is the the instruction that describes the task: ### Input: Compares two dictionaries of registry keys returning their difference. ### Response: def registry_comparison(registry0, registry1): """Compares two dictionaries of registry keys returning their difference.""" comparison = {'created_keys': {},...
def hexdump(src, length=8, colorize=False): """ Produce a string hexdump of src, for debug output. Input: bytestring; output: text string """ if not src: return str(src) if type(src) is not bytes: raise yubico_exception.InputError('Hexdump \'src\' must be bytestring (got %s)' % type...
Produce a string hexdump of src, for debug output. Input: bytestring; output: text string
Below is the the instruction that describes the task: ### Input: Produce a string hexdump of src, for debug output. Input: bytestring; output: text string ### Response: def hexdump(src, length=8, colorize=False): """ Produce a string hexdump of src, for debug output. Input: bytestring; output: text s...
def purge_object(self, pid, log_message=None): """ Purge an object from Fedora. Calls :meth:`ApiFacade.purgeObject`. :param pid: pid of the object to be purged :param log_message: optional log message :rtype: boolean """ kwargs = {'pid': pid} if log_mess...
Purge an object from Fedora. Calls :meth:`ApiFacade.purgeObject`. :param pid: pid of the object to be purged :param log_message: optional log message :rtype: boolean
Below is the the instruction that describes the task: ### Input: Purge an object from Fedora. Calls :meth:`ApiFacade.purgeObject`. :param pid: pid of the object to be purged :param log_message: optional log message :rtype: boolean ### Response: def purge_object(self, pid, log_message=None...
def dist(self, point, exponent=2.0): """Return the distance of ``point`` to this set. Parameters ---------- point : `array-like` or float Point whose distance to calculate. Its length must be equal to the set's dimension. Can be a float in the 1d case. ex...
Return the distance of ``point`` to this set. Parameters ---------- point : `array-like` or float Point whose distance to calculate. Its length must be equal to the set's dimension. Can be a float in the 1d case. exponent : non-zero float or ``float('inf')``, opt...
Below is the the instruction that describes the task: ### Input: Return the distance of ``point`` to this set. Parameters ---------- point : `array-like` or float Point whose distance to calculate. Its length must be equal to the set's dimension. Can be a float in th...
def _open_terminal(): """Open pty master and return (master_fd, tty_name).""" for x in 'pqrstuvwxyzPQRST': for y in '0123456789abcdef': pty_name = '/dev/pty' + x + y try: fd = os.open(pty_name, os.O_RDWR) except OSError: continue ...
Open pty master and return (master_fd, tty_name).
Below is the the instruction that describes the task: ### Input: Open pty master and return (master_fd, tty_name). ### Response: def _open_terminal(): """Open pty master and return (master_fd, tty_name).""" for x in 'pqrstuvwxyzPQRST': for y in '0123456789abcdef': pty_name = '/dev/pty' ...
def get_num_nodes(properties=None, hadoop_conf_dir=None, offline=False): """ Get the number of task trackers in the Hadoop cluster. All arguments are passed to :func:`get_task_trackers`. """ return len(get_task_trackers(properties, hadoop_conf_dir, offline))
Get the number of task trackers in the Hadoop cluster. All arguments are passed to :func:`get_task_trackers`.
Below is the the instruction that describes the task: ### Input: Get the number of task trackers in the Hadoop cluster. All arguments are passed to :func:`get_task_trackers`. ### Response: def get_num_nodes(properties=None, hadoop_conf_dir=None, offline=False): """ Get the number of task trackers in t...
def _landsat_parse_scene_id(sceneid): """ Parse Landsat-8 scene id. Author @perrygeo - http://www.perrygeo.com """ pre_collection = r"(L[COTEM]8\d{6}\d{7}[A-Z]{3}\d{2})" collection_1 = r"(L[COTEM]08_L\d{1}[A-Z]{2}_\d{6}_\d{8}_\d{8}_\d{2}_(T1|T2|RT))" if not re.match("^{}|{}$".format(pre_co...
Parse Landsat-8 scene id. Author @perrygeo - http://www.perrygeo.com
Below is the the instruction that describes the task: ### Input: Parse Landsat-8 scene id. Author @perrygeo - http://www.perrygeo.com ### Response: def _landsat_parse_scene_id(sceneid): """ Parse Landsat-8 scene id. Author @perrygeo - http://www.perrygeo.com """ pre_collection = r"(L[COT...
def key2elements(key): """split key to elements""" # words = key.split('.') # if len(words) == 4: # return words # # there is a dot in object name # fieldword = words.pop(-1) # nameword = '.'.join(words[-2:]) # if nameword[-1] in ('"', "'"): # # The object name is in quotes ...
split key to elements
Below is the the instruction that describes the task: ### Input: split key to elements ### Response: def key2elements(key): """split key to elements""" # words = key.split('.') # if len(words) == 4: # return words # # there is a dot in object name # fieldword = words.pop(-1) # namew...
def with_context(cls, setup_phases, teardown_phases): """Create PhaseGroup creator function with setup and teardown phases. Args: setup_phases: list of phase_descriptor.PhaseDescriptors/PhaseGroups/ callables/iterables, phases to run during the setup for the PhaseGroup returned from t...
Create PhaseGroup creator function with setup and teardown phases. Args: setup_phases: list of phase_descriptor.PhaseDescriptors/PhaseGroups/ callables/iterables, phases to run during the setup for the PhaseGroup returned from the created function. teardown_phases: list of phase_des...
Below is the the instruction that describes the task: ### Input: Create PhaseGroup creator function with setup and teardown phases. Args: setup_phases: list of phase_descriptor.PhaseDescriptors/PhaseGroups/ callables/iterables, phases to run during the setup for the PhaseGroup returne...
def uncontract_general(basis, use_copy=True): """ Removes the general contractions from a basis set The input basis set is not modified. The returned basis may have functions with coefficients of zero and may have duplicate shells. If use_copy is True, the input basis set is not modified. ...
Removes the general contractions from a basis set The input basis set is not modified. The returned basis may have functions with coefficients of zero and may have duplicate shells. If use_copy is True, the input basis set is not modified.
Below is the the instruction that describes the task: ### Input: Removes the general contractions from a basis set The input basis set is not modified. The returned basis may have functions with coefficients of zero and may have duplicate shells. If use_copy is True, the input basis set is not mod...
def shape_rb_data(raw_rb): """Take the raw rb data and convert it into averages and std dev Args: raw_rb (numpy.array): m x n x l list where m is the number of seeds, n is the number of Clifford sequences and l is the number of qubits Return: numpy_array: 2 x n x l list where i...
Take the raw rb data and convert it into averages and std dev Args: raw_rb (numpy.array): m x n x l list where m is the number of seeds, n is the number of Clifford sequences and l is the number of qubits Return: numpy_array: 2 x n x l list where index 0 is the mean over seeds, 1 i...
Below is the the instruction that describes the task: ### Input: Take the raw rb data and convert it into averages and std dev Args: raw_rb (numpy.array): m x n x l list where m is the number of seeds, n is the number of Clifford sequences and l is the number of qubits Return: ...
def load(self, path): """ Load the catalog from file Parameters ---------- path: str The path to the file """ # Get the object DB = joblib.load(path) # Load the attributes self.catalog = DB.catalog se...
Load the catalog from file Parameters ---------- path: str The path to the file
Below is the the instruction that describes the task: ### Input: Load the catalog from file Parameters ---------- path: str The path to the file ### Response: def load(self, path): """ Load the catalog from file Parameters ------...
def create_token(self, *, holder_name, card_number, credit_card_cvv, expiration_date, token_type='credit_card', identity_document=None, billing_address=None, additional_details=None): """ When creating a Token, remember to use the public-key header instead of the private-key header,...
When creating a Token, remember to use the public-key header instead of the private-key header, and do not include the app-id header. Args: holder_name: Name of the credit card holder. card_number: Credit card number. credit_card_cvv: The CVV number on the card (3 or...
Below is the the instruction that describes the task: ### Input: When creating a Token, remember to use the public-key header instead of the private-key header, and do not include the app-id header. Args: holder_name: Name of the credit card holder. card_number: Credit card ...
def Beta(alpha: vertex_constructor_param_types, beta: vertex_constructor_param_types, label: Optional[str]=None) -> Vertex: """ One to one constructor for mapping some tensorShape of alpha and beta to a matching tensorShaped Beta. :param alpha: the alpha of the Beta with either the same tensorShape...
One to one constructor for mapping some tensorShape of alpha and beta to a matching tensorShaped Beta. :param alpha: the alpha of the Beta with either the same tensorShape as specified for this vertex or a scalar :param beta: the beta of the Beta with either the same tensorShape as specified for this v...
Below is the the instruction that describes the task: ### Input: One to one constructor for mapping some tensorShape of alpha and beta to a matching tensorShaped Beta. :param alpha: the alpha of the Beta with either the same tensorShape as specified for this vertex or a scalar :param beta: the beta...
def close_all_files(self): """Close all open files (so that we can open more).""" while len(self.open_file_infos) > 0: file_info = self.open_file_infos.pop(0) file_info.file_handle.close() file_info.file_handle = None self.closed_file_infos.append(file_inf...
Close all open files (so that we can open more).
Below is the the instruction that describes the task: ### Input: Close all open files (so that we can open more). ### Response: def close_all_files(self): """Close all open files (so that we can open more).""" while len(self.open_file_infos) > 0: file_info = self.open_file_infos.pop(0) ...
def leaveWhitespace( self ): """Extends ``leaveWhitespace`` defined in base class, and also invokes ``leaveWhitespace`` on all contained expressions.""" self.skipWhitespace = False self.exprs = [ e.copy() for e in self.exprs ] for e in self.exprs: e.leaveWhitespace...
Extends ``leaveWhitespace`` defined in base class, and also invokes ``leaveWhitespace`` on all contained expressions.
Below is the the instruction that describes the task: ### Input: Extends ``leaveWhitespace`` defined in base class, and also invokes ``leaveWhitespace`` on all contained expressions. ### Response: def leaveWhitespace( self ): """Extends ``leaveWhitespace`` defined in base class, and also invokes...
def kind(self): """Kind.""" if "kind" not in self.attrs.keys(): self.attrs["kind"] = "None" value = self.attrs["kind"] return value if not value == "None" else None
Kind.
Below is the the instruction that describes the task: ### Input: Kind. ### Response: def kind(self): """Kind.""" if "kind" not in self.attrs.keys(): self.attrs["kind"] = "None" value = self.attrs["kind"] return value if not value == "None" else None
def price_in_btc(self, minimum: float = 0, maximum: float = 2) -> str: """Generate random price in BTC. :param minimum: Minimum value of price. :param maximum: Maximum value of price. :return: Price in BTC. """ return '{} BTC'.format( self.random.uniform( ...
Generate random price in BTC. :param minimum: Minimum value of price. :param maximum: Maximum value of price. :return: Price in BTC.
Below is the the instruction that describes the task: ### Input: Generate random price in BTC. :param minimum: Minimum value of price. :param maximum: Maximum value of price. :return: Price in BTC. ### Response: def price_in_btc(self, minimum: float = 0, maximum: float = 2) -> str: ...
def _sorted_copy(self, comparison, reversed=False): """ Returns a sorted copy with the colors arranged according to the given comparison. """ sorted = self.copy() _list.sort(sorted, comparison) if reversed: _list.reverse(sorted) return sorted
Returns a sorted copy with the colors arranged according to the given comparison.
Below is the the instruction that describes the task: ### Input: Returns a sorted copy with the colors arranged according to the given comparison. ### Response: def _sorted_copy(self, comparison, reversed=False): """ Returns a sorted copy with the colors arranged according to the given comparison. ...
def include_theme_files(self, fragment): """ Gets theme configuration and renders theme css into fragment """ theme = self.get_theme() if not theme or 'package' not in theme: return theme_package, theme_files = theme.get('package', None), theme.get('locations...
Gets theme configuration and renders theme css into fragment
Below is the the instruction that describes the task: ### Input: Gets theme configuration and renders theme css into fragment ### Response: def include_theme_files(self, fragment): """ Gets theme configuration and renders theme css into fragment """ theme = self.get_theme() ...
def wait_for_task(task, instance_name, task_type, sleep_seconds=1, log_level='debug'): ''' Waits for a task to be completed. task The task to wait for. instance_name The name of the ESXi host, vCenter Server, or Virtual Machine that the task is being run on. task_type ...
Waits for a task to be completed. task The task to wait for. instance_name The name of the ESXi host, vCenter Server, or Virtual Machine that the task is being run on. task_type The type of task being performed. Useful information for debugging purposes. sleep_seconds...
Below is the the instruction that describes the task: ### Input: Waits for a task to be completed. task The task to wait for. instance_name The name of the ESXi host, vCenter Server, or Virtual Machine that the task is being run on. task_type The type of task being per...
def print_summary(self, w=0, objs=(), **print3opts): '''Print the summary statistics. *w=0* -- indentation for each line *objs=()* -- optional, list of objects *print3options* -- print options, as in Python 3.0 ''' self._printf('...
Print the summary statistics. *w=0* -- indentation for each line *objs=()* -- optional, list of objects *print3options* -- print options, as in Python 3.0
Below is the the instruction that describes the task: ### Input: Print the summary statistics. *w=0* -- indentation for each line *objs=()* -- optional, list of objects *print3options* -- print options, as in Python 3.0 ### Response: def print_summ...
def build_image(self, image_name: str, image_tag: str, repo_path: Path, requirements_option: RequirementsOptions, dependencies: Optional[List[str]]): """ Builds an image for specific requirements and dependencies, based on the settings. :param...
Builds an image for specific requirements and dependencies, based on the settings. :param image_name: How the image should be named :param image_tag: And what tag it should have. :param repo_path: Path to the cloned repository. :param requirements_option: How requirements are set in the...
Below is the the instruction that describes the task: ### Input: Builds an image for specific requirements and dependencies, based on the settings. :param image_name: How the image should be named :param image_tag: And what tag it should have. :param repo_path: Path to the cloned repository...
def writeConfig(self): """ Persists the value of the :attr:`AbstractJobStore.config` attribute to the job store, so that it can be retrieved later by other instances of this class. """ with self.writeSharedFileStream('config.pickle', isProtected=False) as fileHandle: ...
Persists the value of the :attr:`AbstractJobStore.config` attribute to the job store, so that it can be retrieved later by other instances of this class.
Below is the the instruction that describes the task: ### Input: Persists the value of the :attr:`AbstractJobStore.config` attribute to the job store, so that it can be retrieved later by other instances of this class. ### Response: def writeConfig(self): """ Persists the value of the :attr...
def send_email(template_name, context=None, *args, **kwargs): """ Send a templated email. To generate the message used for the email, the method first searches for an HTML template with the given name (eg: <template>.html), and renders it with the provided context. The process is repeated for t...
Send a templated email. To generate the message used for the email, the method first searches for an HTML template with the given name (eg: <template>.html), and renders it with the provided context. The process is repeated for the plain text message except a 'txt' extension is used. All other opti...
Below is the the instruction that describes the task: ### Input: Send a templated email. To generate the message used for the email, the method first searches for an HTML template with the given name (eg: <template>.html), and renders it with the provided context. The process is repeated for the pl...
def aggregate_daily_with_joins(image_coll, start_date, end_date, agg_type='mean'): """Aggregate images by day (using joins) The primary purpose of this function is to join separate Landsat images from the same path into a single daily image. Parameters ---------- ...
Aggregate images by day (using joins) The primary purpose of this function is to join separate Landsat images from the same path into a single daily image. Parameters ---------- image_coll : ee.ImageCollection Input image collection. start_date : date, number, string Start dat...
Below is the the instruction that describes the task: ### Input: Aggregate images by day (using joins) The primary purpose of this function is to join separate Landsat images from the same path into a single daily image. Parameters ---------- image_coll : ee.ImageCollection Input image...
def merge_dict(dict1, dict2): # type: (dict, dict) -> dict """Recursively merge dictionaries: dict2 on to dict1. This differs from dict.update() in that values that are dicts are recursively merged. Note that only dict value types are merged, not lists, etc. :param dict dict1: dictionary to merge t...
Recursively merge dictionaries: dict2 on to dict1. This differs from dict.update() in that values that are dicts are recursively merged. Note that only dict value types are merged, not lists, etc. :param dict dict1: dictionary to merge to :param dict dict2: dictionary to merge with :rtype: dict ...
Below is the the instruction that describes the task: ### Input: Recursively merge dictionaries: dict2 on to dict1. This differs from dict.update() in that values that are dicts are recursively merged. Note that only dict value types are merged, not lists, etc. :param dict dict1: dictionary to merge to...
def __threshold(self, ymx_i): """ Calculates the difference threshold for a given difference local maximum. Parameters ----------- ymx_i : float The normalized y value of a local maximum. """ return ymx_i - (self.S * np.diff(self.xsn).mean())
Calculates the difference threshold for a given difference local maximum. Parameters ----------- ymx_i : float The normalized y value of a local maximum.
Below is the the instruction that describes the task: ### Input: Calculates the difference threshold for a given difference local maximum. Parameters ----------- ymx_i : float The normalized y value of a local maximum. ### Response: def __threshold(self, ymx_i): ...
def find_runner(program): """Return a command that will run program. Args: program: The string name of the program to try to run. Returns: commandline list of strings to run the program (eg. with subprocess.call()) or None """ if os.path.isfile(program) and not os.access(program, os...
Return a command that will run program. Args: program: The string name of the program to try to run. Returns: commandline list of strings to run the program (eg. with subprocess.call()) or None
Below is the the instruction that describes the task: ### Input: Return a command that will run program. Args: program: The string name of the program to try to run. Returns: commandline list of strings to run the program (eg. with subprocess.call()) or None ### Response: def find_runner(p...
def add_path_argument(cls, group, argname, dest=None, help_=None): """ Subclasses may call this to expose a path argument. Args: group: arparse.ArgumentGroup, the extension argument group argname: str, the name of the argument, will be namespaced. dest: str, ...
Subclasses may call this to expose a path argument. Args: group: arparse.ArgumentGroup, the extension argument group argname: str, the name of the argument, will be namespaced. dest: str, similar to the `dest` argument of `argparse.ArgumentParser.add_argument...
Below is the the instruction that describes the task: ### Input: Subclasses may call this to expose a path argument. Args: group: arparse.ArgumentGroup, the extension argument group argname: str, the name of the argument, will be namespaced. dest: str, similar to the `de...
def encrypt_message(data_to_encrypt, enc_alg, encryption_cert): """Function encrypts data and returns the generated ASN.1 :param data_to_encrypt: A byte string of the data to be encrypted :param enc_alg: The algorithm to be used for encrypting the data :param encryption_cert: The certificate ...
Function encrypts data and returns the generated ASN.1 :param data_to_encrypt: A byte string of the data to be encrypted :param enc_alg: The algorithm to be used for encrypting the data :param encryption_cert: The certificate to be used for encrypting the data :return: A CMS ASN.1 byte strin...
Below is the the instruction that describes the task: ### Input: Function encrypts data and returns the generated ASN.1 :param data_to_encrypt: A byte string of the data to be encrypted :param enc_alg: The algorithm to be used for encrypting the data :param encryption_cert: The certificate to...
def _get_answer_spans(answer_list, answer_start_list): """Find all answer spans from the context, returning start_index and end_index :param list[str] answer_list: List of all answers :param list[int] answer_start_list: List of all answers' start indices Returns ------- ...
Find all answer spans from the context, returning start_index and end_index :param list[str] answer_list: List of all answers :param list[int] answer_start_list: List of all answers' start indices Returns ------- List[Tuple] list of Tuple(answer_start_index answer_e...
Below is the the instruction that describes the task: ### Input: Find all answer spans from the context, returning start_index and end_index :param list[str] answer_list: List of all answers :param list[int] answer_start_list: List of all answers' start indices Returns ------- ...
def setup_and_load_epoch(hparams, data_dir, which_epoch_data=None): """Load T2TGymEnv with data from one epoch. Args: hparams: hparams. data_dir: data directory. which_epoch_data: data from which epoch to load. Returns: env. """ t2t_env = rl_utils.setup_env( hparams, batch_size=hparams...
Load T2TGymEnv with data from one epoch. Args: hparams: hparams. data_dir: data directory. which_epoch_data: data from which epoch to load. Returns: env.
Below is the the instruction that describes the task: ### Input: Load T2TGymEnv with data from one epoch. Args: hparams: hparams. data_dir: data directory. which_epoch_data: data from which epoch to load. Returns: env. ### Response: def setup_and_load_epoch(hparams, data_dir, which_epoch_data...
def set_checks(self, checks, position=None): """Sets the checks at the position.""" if position is None: position = self.position self.checkdefs[position][0] = checks
Sets the checks at the position.
Below is the the instruction that describes the task: ### Input: Sets the checks at the position. ### Response: def set_checks(self, checks, position=None): """Sets the checks at the position.""" if position is None: position = self.position self.checkdefs[position][0] = checks
def show_type(cls, result): """ :param TryHaskell.Result result: Parse result of JSON data. :rtype: str|unicode """ if result.ok: return ' :: '.join([result.expr, result.type]) return result.value
:param TryHaskell.Result result: Parse result of JSON data. :rtype: str|unicode
Below is the the instruction that describes the task: ### Input: :param TryHaskell.Result result: Parse result of JSON data. :rtype: str|unicode ### Response: def show_type(cls, result): """ :param TryHaskell.Result result: Parse result of JSON data. :rtype: str|unicode """ ...
def reset_mode(self): """Send a Reset command to set the operation mode to 0.""" self.command(0x18, b"\x01", timeout=0.1) self.transport.write(Chipset.ACK) time.sleep(0.010)
Send a Reset command to set the operation mode to 0.
Below is the the instruction that describes the task: ### Input: Send a Reset command to set the operation mode to 0. ### Response: def reset_mode(self): """Send a Reset command to set the operation mode to 0.""" self.command(0x18, b"\x01", timeout=0.1) self.transport.write(Chipset.ACK) ...
def save_admin_log(build, **kwargs): """Saves an action to the admin log.""" message = kwargs.pop('message', None) release = kwargs.pop('release', None) run = kwargs.pop('run', None) if not len(kwargs) == 1: raise TypeError('Must specify a LOG_TYPE argument') log_enum = kwargs.keys()[0...
Saves an action to the admin log.
Below is the the instruction that describes the task: ### Input: Saves an action to the admin log. ### Response: def save_admin_log(build, **kwargs): """Saves an action to the admin log.""" message = kwargs.pop('message', None) release = kwargs.pop('release', None) run = kwargs.pop('run', None) ...
def _print_MatMul(self, expr): """ Matrix multiplication printer. The sympy one turns everything into a dot product without type-checking. """ from sympy import MatrixExpr links = [] for i, j in zip(expr.args[1:], expr.args[:-1]): if isinstance(i, Matr...
Matrix multiplication printer. The sympy one turns everything into a dot product without type-checking.
Below is the the instruction that describes the task: ### Input: Matrix multiplication printer. The sympy one turns everything into a dot product without type-checking. ### Response: def _print_MatMul(self, expr): """ Matrix multiplication printer. The sympy one turns everything into a ...
def extract_root_meta(cls, serializer, resource): """ Calls a `get_root_meta` function on a serializer, if it exists. """ many = False if hasattr(serializer, 'child'): many = True serializer = serializer.child data = {} if getattr(serializ...
Calls a `get_root_meta` function on a serializer, if it exists.
Below is the the instruction that describes the task: ### Input: Calls a `get_root_meta` function on a serializer, if it exists. ### Response: def extract_root_meta(cls, serializer, resource): """ Calls a `get_root_meta` function on a serializer, if it exists. """ many = False ...
def check_config(data): """Check if metadata is right TODO(crow): check more """ is_right = True if "title" not in data: logging.error("No 'title' in _config.yml") is_right = False return is_right
Check if metadata is right TODO(crow): check more
Below is the the instruction that describes the task: ### Input: Check if metadata is right TODO(crow): check more ### Response: def check_config(data): """Check if metadata is right TODO(crow): check more """ is_right = True if "title" not in data: logging.error("No 'title' in ...
def _get_date(day=None, month=None, year=None): """Returns a datetime object with optional params or today.""" now = datetime.date.today() if day is None: return now try: return datetime.date( day=int(day), month=int(month or now.month), year=int(yea...
Returns a datetime object with optional params or today.
Below is the the instruction that describes the task: ### Input: Returns a datetime object with optional params or today. ### Response: def _get_date(day=None, month=None, year=None): """Returns a datetime object with optional params or today.""" now = datetime.date.today() if day is None: ret...
def to_dict(self): """ Convert the object into a json serializable dictionary. Note: It uses the private method _save_to_input_dict of the parent. :return dict: json serializable dictionary containing the needed information to instantiate the object """ input_dict = su...
Convert the object into a json serializable dictionary. Note: It uses the private method _save_to_input_dict of the parent. :return dict: json serializable dictionary containing the needed information to instantiate the object
Below is the the instruction that describes the task: ### Input: Convert the object into a json serializable dictionary. Note: It uses the private method _save_to_input_dict of the parent. :return dict: json serializable dictionary containing the needed information to instantiate the object ### Re...
def set_tag(self, project, repository, tag_name, commit_revision, description=None): """ Creates a tag using the information provided in the {@link RestCreateTagRequest request} The authenticated user must have REPO_WRITE permission for the context repository to call this resource. :para...
Creates a tag using the information provided in the {@link RestCreateTagRequest request} The authenticated user must have REPO_WRITE permission for the context repository to call this resource. :param project: :param repository: :param tag_name: :param commit_revision: commit has...
Below is the the instruction that describes the task: ### Input: Creates a tag using the information provided in the {@link RestCreateTagRequest request} The authenticated user must have REPO_WRITE permission for the context repository to call this resource. :param project: :param repository...