code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def jaccardIndex(s1, s2, stranded=False): """ Compute the Jaccard index for two collections of genomic intervals :param s1: the first set of genomic intervals :param s2: the second set of genomic intervals :param stranded: if True, treat regions on different strands as not intersecting eac...
Compute the Jaccard index for two collections of genomic intervals :param s1: the first set of genomic intervals :param s2: the second set of genomic intervals :param stranded: if True, treat regions on different strands as not intersecting each other, even if they occupy the same ...
Below is the the instruction that describes the task: ### Input: Compute the Jaccard index for two collections of genomic intervals :param s1: the first set of genomic intervals :param s2: the second set of genomic intervals :param stranded: if True, treat regions on different strands as not ...
def transform_to_mods_multimono(marc_xml, uuid, url): """ Convert `marc_xml` to multimonograph MODS data format. Args: marc_xml (str): Filename or XML string. Don't use ``\\n`` in case of filename. uuid (str): UUID string giving the package ID. url (str): URL...
Convert `marc_xml` to multimonograph MODS data format. Args: marc_xml (str): Filename or XML string. Don't use ``\\n`` in case of filename. uuid (str): UUID string giving the package ID. url (str): URL of the publication (public or not). Returns: list: C...
Below is the the instruction that describes the task: ### Input: Convert `marc_xml` to multimonograph MODS data format. Args: marc_xml (str): Filename or XML string. Don't use ``\\n`` in case of filename. uuid (str): UUID string giving the package ID. url (str): ...
def load_calibration(self, calibration_file=None): """Load calibration data for IMU(s) connected to this SK8. This method attempts to load a set of calibration data from a .ini file produced by the sk8_calibration_gui application (TODO link!). By default, it will look for a file name ...
Load calibration data for IMU(s) connected to this SK8. This method attempts to load a set of calibration data from a .ini file produced by the sk8_calibration_gui application (TODO link!). By default, it will look for a file name "sk8calib.ini" in the current working directory. This ...
Below is the the instruction that describes the task: ### Input: Load calibration data for IMU(s) connected to this SK8. This method attempts to load a set of calibration data from a .ini file produced by the sk8_calibration_gui application (TODO link!). By default, it will look for a fil...
def add(self, rule): """Add a new classifier rule to the classifier set. Return a list containing zero or more rules that were deleted from the classifier by the algorithm in order to make room for the new rule. The rule argument should be a ClassifierRule instance. The behavior of this ...
Add a new classifier rule to the classifier set. Return a list containing zero or more rules that were deleted from the classifier by the algorithm in order to make room for the new rule. The rule argument should be a ClassifierRule instance. The behavior of this method depends on whethe...
Below is the the instruction that describes the task: ### Input: Add a new classifier rule to the classifier set. Return a list containing zero or more rules that were deleted from the classifier by the algorithm in order to make room for the new rule. The rule argument should be a Classifie...
def reset_server_env(self, server_name, configure): """ reset server env to server-name :param server_name: :param configure: :return: """ env.host_string = configure[server_name]['host'] env.user = configure[server_name]['user'] env.password = con...
reset server env to server-name :param server_name: :param configure: :return:
Below is the the instruction that describes the task: ### Input: reset server env to server-name :param server_name: :param configure: :return: ### Response: def reset_server_env(self, server_name, configure): """ reset server env to server-name :param server_name: ...
async def stop(self): """Stop the rpc queue from inside the event loop.""" if self._rpc_task is not None: self._rpc_task.cancel() try: await self._rpc_task except asyncio.CancelledError: pass self._rpc_task = None
Stop the rpc queue from inside the event loop.
Below is the the instruction that describes the task: ### Input: Stop the rpc queue from inside the event loop. ### Response: async def stop(self): """Stop the rpc queue from inside the event loop.""" if self._rpc_task is not None: self._rpc_task.cancel() try: awai...
def parse_xml_node(self, node): '''Parse an xml.dom Node object representing a condition into this object. ''' self.sequence = int(node.getAttributeNS(RTS_NS, 'sequence')) c = node.getElementsByTagNameNS(RTS_NS, 'TargetComponent') if c.length != 1: raise Inva...
Parse an xml.dom Node object representing a condition into this object.
Below is the the instruction that describes the task: ### Input: Parse an xml.dom Node object representing a condition into this object. ### Response: def parse_xml_node(self, node): '''Parse an xml.dom Node object representing a condition into this object. ''' self.sequenc...
def Power(base: vertex_constructor_param_types, exponent: vertex_constructor_param_types, label: Optional[str]=None) -> Vertex: """ Raises a vertex to the power of another :param base: the base vertex :param exponent: the exponent vertex """ return Double(context.jvm_view().PowerVertex, lab...
Raises a vertex to the power of another :param base: the base vertex :param exponent: the exponent vertex
Below is the the instruction that describes the task: ### Input: Raises a vertex to the power of another :param base: the base vertex :param exponent: the exponent vertex ### Response: def Power(base: vertex_constructor_param_types, exponent: vertex_constructor_param_types, label: Optional[str]=None) ...
def versionok_for_gui(): ''' Return True if running Python is suitable for GUI Event Integration and deeper IPython integration ''' # We require Python 2.6+ ... if sys.hexversion < 0x02060000: return False # Or Python 3.2+ if sys.hexversion >= 0x03000000 and sys.hexversion < 0x03020000: ...
Return True if running Python is suitable for GUI Event Integration and deeper IPython integration
Below is the the instruction that describes the task: ### Input: Return True if running Python is suitable for GUI Event Integration and deeper IPython integration ### Response: def versionok_for_gui(): ''' Return True if running Python is suitable for GUI Event Integration and deeper IPython integration ''' ...
def FortranScan(path_variable="FORTRANPATH"): """Return a prototype Scanner instance for scanning source files for Fortran USE & INCLUDE statements""" # The USE statement regex matches the following: # # USE module_name # USE :: module_name # USE, INTRINSIC :: module_name # USE, NON_INTRINSIC :: modu...
Return a prototype Scanner instance for scanning source files for Fortran USE & INCLUDE statements
Below is the the instruction that describes the task: ### Input: Return a prototype Scanner instance for scanning source files for Fortran USE & INCLUDE statements ### Response: def FortranScan(path_variable="FORTRANPATH"): """Return a prototype Scanner instance for scanning source files for Fortran US...
def _parse_settings_bond_1(opts, iface, bond_def): ''' Filters given options and outputs valid settings for bond1. If an option has a value that is not expected, this function will log what the Interface, Setting and what it was expecting. ''' bond = {'mode': '1'} for binding in ['miim...
Filters given options and outputs valid settings for bond1. If an option has a value that is not expected, this function will log what the Interface, Setting and what it was expecting.
Below is the the instruction that describes the task: ### Input: Filters given options and outputs valid settings for bond1. If an option has a value that is not expected, this function will log what the Interface, Setting and what it was expecting. ### Response: def _parse_settings_bond_1(opts, iface,...
def get_applicable_values(self): """Return selected values that will affect the search result""" return [v for v in self._values if v.is_active and not v.is_all_results]
Return selected values that will affect the search result
Below is the the instruction that describes the task: ### Input: Return selected values that will affect the search result ### Response: def get_applicable_values(self): """Return selected values that will affect the search result""" return [v for v in self._values if v.is_active and not v.is_all_r...
def transform_header(mtype_name): '''Add header to json output to wrap around distribution data. ''' head_dict = OrderedDict() head_dict["m-type"] = mtype_name head_dict["components"] = defaultdict(OrderedDict) return head_dict
Add header to json output to wrap around distribution data.
Below is the the instruction that describes the task: ### Input: Add header to json output to wrap around distribution data. ### Response: def transform_header(mtype_name): '''Add header to json output to wrap around distribution data. ''' head_dict = OrderedDict() head_dict["m-type"] = mtype_name...
def delete_specific(self, id, **kwargs): """ Removes a specific Build Configuration Set This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >...
Removes a specific Build Configuration Set This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(re...
Below is the the instruction that describes the task: ### Input: Removes a specific Build Configuration Set This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. ...
def decodeMotorInput(self, motorInputPattern): """ Decode motor command from bit vector. @param motorInputPattern (1D numpy.array) Encoded motor command. @return (1D numpy.array) Decoded motor command. """ key = self.motorEncoder.decode(motorInputPattern)[0].k...
Decode motor command from bit vector. @param motorInputPattern (1D numpy.array) Encoded motor command. @return (1D numpy.array) Decoded motor command.
Below is the the instruction that describes the task: ### Input: Decode motor command from bit vector. @param motorInputPattern (1D numpy.array) Encoded motor command. @return (1D numpy.array) Decoded motor command. ### Response: def decodeMotorInput(self, motorInputPatte...
def _setFlag(self, name, val, defVal): """set the objects property propName if the dictKey key exists in dict and it is not the same as default value defVal""" if not hasattr(self, "flags"): self.flags = {} if val != defVal: self.flags[name] = val
set the objects property propName if the dictKey key exists in dict and it is not the same as default value defVal
Below is the the instruction that describes the task: ### Input: set the objects property propName if the dictKey key exists in dict and it is not the same as default value defVal ### Response: def _setFlag(self, name, val, defVal): """set the objects property propName if the dictKey key exists in dict and...
def clear(self): """ Clear the content of `self.xmlnode` removing all <item/>, <status/>, etc. """ if not self.xmlnode.children: return n=self.xmlnode.children while n: ns=n.ns() if ns and ns.getContent()!=MUC_USER_NS: p...
Clear the content of `self.xmlnode` removing all <item/>, <status/>, etc.
Below is the the instruction that describes the task: ### Input: Clear the content of `self.xmlnode` removing all <item/>, <status/>, etc. ### Response: def clear(self): """ Clear the content of `self.xmlnode` removing all <item/>, <status/>, etc. """ if not self.xmlnode.children: ...
def infer_call_result(self, caller, context): """ The boundnode of the regular context with a function called on ``object.__new__`` will be of type ``object``, which is incorrect for the argument in general. If no context is given the ``object.__new__`` call argument will ...
The boundnode of the regular context with a function called on ``object.__new__`` will be of type ``object``, which is incorrect for the argument in general. If no context is given the ``object.__new__`` call argument will correctly inferred except when inside a call that requires ...
Below is the the instruction that describes the task: ### Input: The boundnode of the regular context with a function called on ``object.__new__`` will be of type ``object``, which is incorrect for the argument in general. If no context is given the ``object.__new__`` call argument will ...
def compounding(start, stop, compound, t=0.0): """Yield an infinite series of compounding values. Each time the generator is called, a value is produced by multiplying the previous value by the compound rate. EXAMPLE: >>> sizes = compounding(1., 10., 1.5) >>> assert next(sizes) == 1. ...
Yield an infinite series of compounding values. Each time the generator is called, a value is produced by multiplying the previous value by the compound rate. EXAMPLE: >>> sizes = compounding(1., 10., 1.5) >>> assert next(sizes) == 1. >>> assert next(sizes) == 1 * 1.5 >>> assert nex...
Below is the the instruction that describes the task: ### Input: Yield an infinite series of compounding values. Each time the generator is called, a value is produced by multiplying the previous value by the compound rate. EXAMPLE: >>> sizes = compounding(1., 10., 1.5) >>> assert next(size...
def show_print_dialog(self): """Open the print dialog""" if not self.impact_function: # Now try to read the keywords and show them in the dock try: active_layer = self.iface.activeLayer() keywords = self.keyword_io.read_keywords(active_layer) ...
Open the print dialog
Below is the the instruction that describes the task: ### Input: Open the print dialog ### Response: def show_print_dialog(self): """Open the print dialog""" if not self.impact_function: # Now try to read the keywords and show them in the dock try: active_lay...
def lookup_zone(conn, zone): """Look up a zone ID for a zone string. Args: conn: boto.route53.Route53Connection zone: string eg. foursquare.com Returns: zone ID eg. ZE2DYFZDWGSL4. Raises: ZoneNotFoundError if zone not found.""" all_zones = conn.get_all_hosted_zones() for resp in all_zones['ListHost...
Look up a zone ID for a zone string. Args: conn: boto.route53.Route53Connection zone: string eg. foursquare.com Returns: zone ID eg. ZE2DYFZDWGSL4. Raises: ZoneNotFoundError if zone not found.
Below is the the instruction that describes the task: ### Input: Look up a zone ID for a zone string. Args: conn: boto.route53.Route53Connection zone: string eg. foursquare.com Returns: zone ID eg. ZE2DYFZDWGSL4. Raises: ZoneNotFoundError if zone not found. ### Response: def lookup_zone(conn, zone):...
def p2sh_input_and_witness(outpoint, stack_script, redeem_script, sequence=None): ''' OutPoint, str, str, int -> (TxIn, InputWitness) Create a signed legacy TxIn from a p2pkh prevout Create an empty InputWitness for it Useful for transactions spending some witness and some...
OutPoint, str, str, int -> (TxIn, InputWitness) Create a signed legacy TxIn from a p2pkh prevout Create an empty InputWitness for it Useful for transactions spending some witness and some legacy prevouts
Below is the the instruction that describes the task: ### Input: OutPoint, str, str, int -> (TxIn, InputWitness) Create a signed legacy TxIn from a p2pkh prevout Create an empty InputWitness for it Useful for transactions spending some witness and some legacy prevouts ### Response: def p2sh_input_and_w...
def _send_packet_safe(self, cr, packet): """ Adds 1bit counter to CRTP header to guarantee that no ack (downlink) payload are lost and no uplink packet are duplicated. The caller should resend packet if not acked (ie. same as with a direct call to crazyradio.send_packet) ...
Adds 1bit counter to CRTP header to guarantee that no ack (downlink) payload are lost and no uplink packet are duplicated. The caller should resend packet if not acked (ie. same as with a direct call to crazyradio.send_packet)
Below is the the instruction that describes the task: ### Input: Adds 1bit counter to CRTP header to guarantee that no ack (downlink) payload are lost and no uplink packet are duplicated. The caller should resend packet if not acked (ie. same as with a direct call to crazyradio.send_packet) ...
def get_stages(self): ''' :return: dictionary of information regarding the stages in the fuzzing session .. note:: structure: { current: ['stage1', 'stage2', 'stage3'], 'stages': {'source1': ['dest1', 'dest2'], 'source2': ['dest1', 'dest3']}} ''' sequence = self.get...
:return: dictionary of information regarding the stages in the fuzzing session .. note:: structure: { current: ['stage1', 'stage2', 'stage3'], 'stages': {'source1': ['dest1', 'dest2'], 'source2': ['dest1', 'dest3']}}
Below is the the instruction that describes the task: ### Input: :return: dictionary of information regarding the stages in the fuzzing session .. note:: structure: { current: ['stage1', 'stage2', 'stage3'], 'stages': {'source1': ['dest1', 'dest2'], 'source2': ['dest1', 'dest3']}} ### Response...
def print_single(line, rev): """ print single reads to stderr """ if rev is True: seq = rc(['', line[9]])[1] qual = line[10][::-1] else: seq = line[9] qual = line[10] fq = ['@%s' % line[0], seq, '+%s' % line[0], qual] print('\n'.join(fq), file = sys.stderr)
print single reads to stderr
Below is the the instruction that describes the task: ### Input: print single reads to stderr ### Response: def print_single(line, rev): """ print single reads to stderr """ if rev is True: seq = rc(['', line[9]])[1] qual = line[10][::-1] else: seq = line[9] qual...
def gain_to_loss_ratio(self): """Gain-to-loss ratio, ratio of positive to negative returns. Formula: (n pos. / n neg.) * (avg. up-month return / avg. down-month return) [Source: CFA Institute] Returns ------- float """ gt = self > 0 lt =...
Gain-to-loss ratio, ratio of positive to negative returns. Formula: (n pos. / n neg.) * (avg. up-month return / avg. down-month return) [Source: CFA Institute] Returns ------- float
Below is the the instruction that describes the task: ### Input: Gain-to-loss ratio, ratio of positive to negative returns. Formula: (n pos. / n neg.) * (avg. up-month return / avg. down-month return) [Source: CFA Institute] Returns ------- float ### Response: def ...
def amp_pick_event(event, st, respdir, chans=['Z'], var_wintype=True, winlen=0.9, pre_pick=0.2, pre_filt=True, lowcut=1.0, highcut=20.0, corners=4, min_snr=1.0, plot=False, remove_old=False, ps_multiplier=0.34, velocity=False): """ Pick amplitudes for loc...
Pick amplitudes for local magnitude for a single event. Looks for maximum peak-to-trough amplitude for a channel in a stream, and picks this amplitude and period. There are a few things it does internally to stabilise the result: 1. Applies a given filter to the data - very necessary for small ...
Below is the the instruction that describes the task: ### Input: Pick amplitudes for local magnitude for a single event. Looks for maximum peak-to-trough amplitude for a channel in a stream, and picks this amplitude and period. There are a few things it does internally to stabilise the result: ...
def pdf_to_img(pdf_file, page_num, page_width, page_height): """ Converts pdf file into image :param pdf_file: path to the pdf file :param page_num: page number to convert (index starting at 1) :return: wand image object """ img = Image(filename="{}[{}]".format(pdf_file, page_num - 1)) i...
Converts pdf file into image :param pdf_file: path to the pdf file :param page_num: page number to convert (index starting at 1) :return: wand image object
Below is the the instruction that describes the task: ### Input: Converts pdf file into image :param pdf_file: path to the pdf file :param page_num: page number to convert (index starting at 1) :return: wand image object ### Response: def pdf_to_img(pdf_file, page_num, page_width, page_height): """...
def find(cls, text): """This method should return an iterable containing matches of this element.""" if isinstance(cls.pattern, string_types): cls.pattern = re.compile(cls.pattern) return cls.pattern.finditer(text)
This method should return an iterable containing matches of this element.
Below is the the instruction that describes the task: ### Input: This method should return an iterable containing matches of this element. ### Response: def find(cls, text): """This method should return an iterable containing matches of this element.""" if isinstance(cls.pattern, string_types): ...
def is_valid_github_uri(uri: URI, expected_path_terms: Tuple[str, ...]) -> bool: """ Return a bool indicating whether or not the URI fulfills the following specs Valid Github URIs *must*: - Have 'https' scheme - Have 'api.github.com' authority - Have a path that contains all "expected_path_terms...
Return a bool indicating whether or not the URI fulfills the following specs Valid Github URIs *must*: - Have 'https' scheme - Have 'api.github.com' authority - Have a path that contains all "expected_path_terms"
Below is the the instruction that describes the task: ### Input: Return a bool indicating whether or not the URI fulfills the following specs Valid Github URIs *must*: - Have 'https' scheme - Have 'api.github.com' authority - Have a path that contains all "expected_path_terms" ### Response: def is_...
def generate_account_shared_access_signature(self, resource_types, permission, expiry, start=None, ip=None, protocol=None): ''' Generates a shared access signature for the table service. Use the returned signature with the sas_token parameter of T...
Generates a shared access signature for the table service. Use the returned signature with the sas_token parameter of TableService. :param ResourceTypes resource_types: Specifies the resource types that are accessible with the account SAS. :param AccountPermissions permission: ...
Below is the the instruction that describes the task: ### Input: Generates a shared access signature for the table service. Use the returned signature with the sas_token parameter of TableService. :param ResourceTypes resource_types: Specifies the resource types that are accessible with...
def _backup(self): """ Backup the mined informations. """ if PyFunceble.CONFIGURATION["mining"]: # The mining is activated. # We backup our mined informations. Dict(PyFunceble.INTERN["mined"]).to_json(self.file)
Backup the mined informations.
Below is the the instruction that describes the task: ### Input: Backup the mined informations. ### Response: def _backup(self): """ Backup the mined informations. """ if PyFunceble.CONFIGURATION["mining"]: # The mining is activated. # We backup our mined i...
def commit_format(self): """ Formats the analysis into a simpler dictionary with the line, file and message values to be commented on a commit. Returns a list of dictionaries """ formatted_analyses = [] for analyze in self.analysis['messages']: for...
Formats the analysis into a simpler dictionary with the line, file and message values to be commented on a commit. Returns a list of dictionaries
Below is the the instruction that describes the task: ### Input: Formats the analysis into a simpler dictionary with the line, file and message values to be commented on a commit. Returns a list of dictionaries ### Response: def commit_format(self): """ Formats the analysis into...
def permute(self, ordering: np.ndarray, *, axis: int) -> None: """ Permute the view, by permuting its layers, attributes and graphs Args: ordering (np.ndarray): The desired ordering along the axis axis (int): 0, permute rows; 1, permute columns """ if axis not in (0, 1): raise ValueError("Axis mu...
Permute the view, by permuting its layers, attributes and graphs Args: ordering (np.ndarray): The desired ordering along the axis axis (int): 0, permute rows; 1, permute columns
Below is the the instruction that describes the task: ### Input: Permute the view, by permuting its layers, attributes and graphs Args: ordering (np.ndarray): The desired ordering along the axis axis (int): 0, permute rows; 1, permute columns ### Response: def permute(self, ordering: np.ndarray, *, axi...
def level(self): """Extract level number from compliance profile URI. Returns integer level number or raises IIIFInfoError """ m = re.match( self.compliance_prefix + r'(\d)' + self.compliance_suffix + r'$', self.compliance) ...
Extract level number from compliance profile URI. Returns integer level number or raises IIIFInfoError
Below is the the instruction that describes the task: ### Input: Extract level number from compliance profile URI. Returns integer level number or raises IIIFInfoError ### Response: def level(self): """Extract level number from compliance profile URI. Returns integer level number or raise...
def keepLastValue(requestContext, seriesList, limit=INF): """ Takes one metric or a wildcard seriesList, and optionally a limit to the number of 'None' values to skip over. Continues the line with the last received value when gaps ('None' values) appear in your data, rather than breaking your line. ...
Takes one metric or a wildcard seriesList, and optionally a limit to the number of 'None' values to skip over. Continues the line with the last received value when gaps ('None' values) appear in your data, rather than breaking your line. Example:: &target=keepLastValue(Server01.connections.han...
Below is the the instruction that describes the task: ### Input: Takes one metric or a wildcard seriesList, and optionally a limit to the number of 'None' values to skip over. Continues the line with the last received value when gaps ('None' values) appear in your data, rather than breaking your line. ...
def _consume_scope(self): """Returns a pair (scope, list of flags encountered in that scope). Note that the flag may be explicitly scoped, and therefore not actually belong to this scope. For example, in: ./pants --compile-java-partition-size-hint=100 compile <target> --compile-java-partition-si...
Returns a pair (scope, list of flags encountered in that scope). Note that the flag may be explicitly scoped, and therefore not actually belong to this scope. For example, in: ./pants --compile-java-partition-size-hint=100 compile <target> --compile-java-partition-size-hint should be treated as if i...
Below is the the instruction that describes the task: ### Input: Returns a pair (scope, list of flags encountered in that scope). Note that the flag may be explicitly scoped, and therefore not actually belong to this scope. For example, in: ./pants --compile-java-partition-size-hint=100 compile <targ...
def import_submodules(package, parent_package=None, exclude_submodules=None): """ Generator which imports all submodules of a module, recursively, including subpackages :param package: package name (e.g 'chisel.util'); may be relative if parent_package is provided :type package: str :param parent_p...
Generator which imports all submodules of a module, recursively, including subpackages :param package: package name (e.g 'chisel.util'); may be relative if parent_package is provided :type package: str :param parent_package: parent package name (e.g 'chisel') :type package: str :rtype: iterator of ...
Below is the the instruction that describes the task: ### Input: Generator which imports all submodules of a module, recursively, including subpackages :param package: package name (e.g 'chisel.util'); may be relative if parent_package is provided :type package: str :param parent_package: parent packag...
def _create_datadict(cls, internal_name): """Creates an object depending on `internal_name` Args: internal_name (str): IDD name Raises: ValueError: if `internal_name` cannot be matched to a data dictionary object """ if internal_name == "LOCATION": ...
Creates an object depending on `internal_name` Args: internal_name (str): IDD name Raises: ValueError: if `internal_name` cannot be matched to a data dictionary object
Below is the the instruction that describes the task: ### Input: Creates an object depending on `internal_name` Args: internal_name (str): IDD name Raises: ValueError: if `internal_name` cannot be matched to a data dictionary object ### Response: def _create_datadict(cls, ...
def fixed_padding(inputs, kernel_size, data_format): """Pads the input along the spatial dimensions independently of input size. Args: inputs: A tensor of size [batch, channels, height_in, width_in] or [batch, height_in, width_in, channels] depending on data_format. kernel_size: The kernel to be used...
Pads the input along the spatial dimensions independently of input size. Args: inputs: A tensor of size [batch, channels, height_in, width_in] or [batch, height_in, width_in, channels] depending on data_format. kernel_size: The kernel to be used in the conv2d or max_pool2d operation. S...
Below is the the instruction that describes the task: ### Input: Pads the input along the spatial dimensions independently of input size. Args: inputs: A tensor of size [batch, channels, height_in, width_in] or [batch, height_in, width_in, channels] depending on data_format. kernel_size: The kernel...
def get_term_freq(self, go_id): ''' Returns the frequency at which a particular GO term has been observed in the annotations. ''' num_ns = float(self.get_total_count(self.go2obj[go_id].namespace)) return float(self.get_count(go_id))/num_ns if num_ns != 0 else 0
Returns the frequency at which a particular GO term has been observed in the annotations.
Below is the the instruction that describes the task: ### Input: Returns the frequency at which a particular GO term has been observed in the annotations. ### Response: def get_term_freq(self, go_id): ''' Returns the frequency at which a particular GO term has been obser...
def _dict_to_bson(doc, check_keys, opts, top_level=True): """Encode a document to BSON.""" if _raw_document_class(doc): return doc.raw try: elements = [] if top_level and "_id" in doc: elements.append(_name_value_to_bson(b"_id\x00", doc["_id"], ...
Encode a document to BSON.
Below is the the instruction that describes the task: ### Input: Encode a document to BSON. ### Response: def _dict_to_bson(doc, check_keys, opts, top_level=True): """Encode a document to BSON.""" if _raw_document_class(doc): return doc.raw try: elements = [] if top_level and "_...
def from_file(cls, f): """Load the history of a ``NeuralNet`` from a json file. Parameters ---------- f : file-like object or str """ with open_file_like(f, 'r') as fp: return cls(json.load(fp))
Load the history of a ``NeuralNet`` from a json file. Parameters ---------- f : file-like object or str
Below is the the instruction that describes the task: ### Input: Load the history of a ``NeuralNet`` from a json file. Parameters ---------- f : file-like object or str ### Response: def from_file(cls, f): """Load the history of a ``NeuralNet`` from a json file. Parameters...
def connect_generators(self, debug=False): """ Connects generators (graph nodes) to grid (graph) for every MV and LV Grid District Args ---- debug: bool, defaults to False If True, information is printed during process. """ for mv_grid_district in self.mv_gr...
Connects generators (graph nodes) to grid (graph) for every MV and LV Grid District Args ---- debug: bool, defaults to False If True, information is printed during process.
Below is the the instruction that describes the task: ### Input: Connects generators (graph nodes) to grid (graph) for every MV and LV Grid District Args ---- debug: bool, defaults to False If True, information is printed during process. ### Response: def connect_generators(sel...
def get_parts(self, parts=None, reference_level=0): """Recursively returns a depth-first list of all known magic parts""" if parts is None: parts = list() new_reference_level = reference_level else: self._level_in_section = self._level + reference_level ...
Recursively returns a depth-first list of all known magic parts
Below is the the instruction that describes the task: ### Input: Recursively returns a depth-first list of all known magic parts ### Response: def get_parts(self, parts=None, reference_level=0): """Recursively returns a depth-first list of all known magic parts""" if parts is None: part...
def add_component_info(self, compinfo): """Add sub-component specific information to a particular data selection Parameters ---------- compinfo : `ModelComponentInfo` object Sub-component being added """ if self.components is None: self.component...
Add sub-component specific information to a particular data selection Parameters ---------- compinfo : `ModelComponentInfo` object Sub-component being added
Below is the the instruction that describes the task: ### Input: Add sub-component specific information to a particular data selection Parameters ---------- compinfo : `ModelComponentInfo` object Sub-component being added ### Response: def add_component_info(self, compinfo): ...
def get_el(el): """ Get value of given `el` tag element. Automatically choose proper method to set the `value` based on the type of the `el`. Args: el (obj): Element reference to the input you want to convert to typeahead. Returns: ...
Get value of given `el` tag element. Automatically choose proper method to set the `value` based on the type of the `el`. Args: el (obj): Element reference to the input you want to convert to typeahead. Returns: str: Value of the object.
Below is the the instruction that describes the task: ### Input: Get value of given `el` tag element. Automatically choose proper method to set the `value` based on the type of the `el`. Args: el (obj): Element reference to the input you want to convert to typea...
def search_url(self, searchterm): """Search for URLs :type searchterm: str :rtype: list """ return self.__search(type_attribute=self.__mispurltypes(), value=searchterm)
Search for URLs :type searchterm: str :rtype: list
Below is the the instruction that describes the task: ### Input: Search for URLs :type searchterm: str :rtype: list ### Response: def search_url(self, searchterm): """Search for URLs :type searchterm: str :rtype: list """ return self.__searc...
def _renew_by(name, window=None): ''' Date before a certificate should be renewed :param name: Common Name of the certificate (DNS name of certificate) :param window: days before expiry date to renew :return datetime object of first renewal date ''' expiry = _expires(name) if window is ...
Date before a certificate should be renewed :param name: Common Name of the certificate (DNS name of certificate) :param window: days before expiry date to renew :return datetime object of first renewal date
Below is the the instruction that describes the task: ### Input: Date before a certificate should be renewed :param name: Common Name of the certificate (DNS name of certificate) :param window: days before expiry date to renew :return datetime object of first renewal date ### Response: def _renew_by(n...
def enabled(name): ''' Enable the RDP service and make sure access to the RDP port is allowed in the firewall configuration ''' ret = {'name': name, 'result': True, 'changes': {}, 'comment': ''} stat = __salt__['rdp.status']() if not stat: if __opts...
Enable the RDP service and make sure access to the RDP port is allowed in the firewall configuration
Below is the the instruction that describes the task: ### Input: Enable the RDP service and make sure access to the RDP port is allowed in the firewall configuration ### Response: def enabled(name): ''' Enable the RDP service and make sure access to the RDP port is allowed in the firewall configura...
def nz(value, none_value, strict=True): ''' This function is named after an old VBA function. It returns a default value if the passed in value is None. If strict is False it will treat an empty string as None as well. example: x = None nz(x,"hello") --> "hello" ...
This function is named after an old VBA function. It returns a default value if the passed in value is None. If strict is False it will treat an empty string as None as well. example: x = None nz(x,"hello") --> "hello" nz(x,"") --> "" y = "" ...
Below is the the instruction that describes the task: ### Input: This function is named after an old VBA function. It returns a default value if the passed in value is None. If strict is False it will treat an empty string as None as well. example: x = None nz(x,"hello") ...
async def login(self, email: str, password: str) -> bool: """Login to the profile.""" login_resp = await self._request( 'post', API_URL_USER, json={ 'version': '1.0', 'method': 'Signin', 'param': { 'E...
Login to the profile.
Below is the the instruction that describes the task: ### Input: Login to the profile. ### Response: async def login(self, email: str, password: str) -> bool: """Login to the profile.""" login_resp = await self._request( 'post', API_URL_USER, json={ ...
def _apply_function_in_context(cls, f, args, context): """ Apply an MPFR function 'f' to the given arguments 'args', rounding to the given context. Returns a new Mpfr object with precision taken from the current context. """ rounding = context.rounding bf = mpfr.Mpfr_t.__new__(cls) mpfr.mp...
Apply an MPFR function 'f' to the given arguments 'args', rounding to the given context. Returns a new Mpfr object with precision taken from the current context.
Below is the the instruction that describes the task: ### Input: Apply an MPFR function 'f' to the given arguments 'args', rounding to the given context. Returns a new Mpfr object with precision taken from the current context. ### Response: def _apply_function_in_context(cls, f, args, context): """ Ap...
def create_convert_sbml_id_function( compartment_prefix='C_', reaction_prefix='R_', compound_prefix='M_', decode_id=entry_id_from_cobra_encoding): """Create function for converting SBML IDs. The returned function will strip prefixes, decode the ID using the provided function. These prefixes...
Create function for converting SBML IDs. The returned function will strip prefixes, decode the ID using the provided function. These prefixes are common on IDs in SBML models because the IDs live in a global namespace.
Below is the the instruction that describes the task: ### Input: Create function for converting SBML IDs. The returned function will strip prefixes, decode the ID using the provided function. These prefixes are common on IDs in SBML models because the IDs live in a global namespace. ### Response: def ...
def thr_img(img, thr=2., mode='+'): """ Use the given magic function name `func` to threshold with value `thr` the data of `img` and return a new nibabel.Nifti1Image. Parameters ---------- img: img-like thr: float or int The threshold value. mode: str Choices: '+' for posit...
Use the given magic function name `func` to threshold with value `thr` the data of `img` and return a new nibabel.Nifti1Image. Parameters ---------- img: img-like thr: float or int The threshold value. mode: str Choices: '+' for positive threshold, '+-' for pos...
Below is the the instruction that describes the task: ### Input: Use the given magic function name `func` to threshold with value `thr` the data of `img` and return a new nibabel.Nifti1Image. Parameters ---------- img: img-like thr: float or int The threshold value. mode: str ...
def Alt_Fn(self, n, dl = 0): """Alt + Fn1~12 组合键 """ self.Delay(dl) self.keyboard.press_key(self.keyboard.alt_key) self.keyboard.tap_key(self.keyboard.function_keys[n]) self.keyboard.release_key(self.keyboard.alt_key)
Alt + Fn1~12 组合键
Below is the the instruction that describes the task: ### Input: Alt + Fn1~12 组合键 ### Response: def Alt_Fn(self, n, dl = 0): """Alt + Fn1~12 组合键 """ self.Delay(dl) self.keyboard.press_key(self.keyboard.alt_key) self.keyboard.tap_key(self.keyboard.function_keys[n]) se...
def missingkeys_nonstandard(block, commdct, dtls, objectlist, afield='afiled %s'): """This is an object list where thre is no first field name to give a hint of what the first field name should be""" afield = 'afield %s' for key_txt in objectlist: key_i = dtls.index(key_txt.upper()) comm...
This is an object list where thre is no first field name to give a hint of what the first field name should be
Below is the the instruction that describes the task: ### Input: This is an object list where thre is no first field name to give a hint of what the first field name should be ### Response: def missingkeys_nonstandard(block, commdct, dtls, objectlist, afield='afiled %s'): """This is an object list where th...
def unread_count(current): """ Number of unread messages for current user .. code-block:: python # request: { 'view':'_zops_unread_count', } # response: { 'status': 'OK', 'co...
Number of unread messages for current user .. code-block:: python # request: { 'view':'_zops_unread_count', } # response: { 'status': 'OK', 'code': 200, 'notifications': ...
Below is the the instruction that describes the task: ### Input: Number of unread messages for current user .. code-block:: python # request: { 'view':'_zops_unread_count', } # response: { 'status':...
def urlretrieve(self, url, filename=None, method='GET', body=None, dir=None, **kwargs): """ Save result of a request to a file, similarly to :func:`urllib.urlretrieve`. If an error is encountered may raise any of the scrapelib `exceptions`_. A filename may be provided o...
Save result of a request to a file, similarly to :func:`urllib.urlretrieve`. If an error is encountered may raise any of the scrapelib `exceptions`_. A filename may be provided or :meth:`urlretrieve` will safely create a temporary file. If a directory is provided, a file will b...
Below is the the instruction that describes the task: ### Input: Save result of a request to a file, similarly to :func:`urllib.urlretrieve`. If an error is encountered may raise any of the scrapelib `exceptions`_. A filename may be provided or :meth:`urlretrieve` will safely creat...
def generalize_sql(sql): """ Removes most variables from an SQL query and replaces them with X or N for numbers. Based on Mediawiki's DatabaseBase::generalizeSQL :type sql str|None :rtype: str """ if sql is None: return None # multiple spaces sql = re.sub(r'\s{2,}', ' ', s...
Removes most variables from an SQL query and replaces them with X or N for numbers. Based on Mediawiki's DatabaseBase::generalizeSQL :type sql str|None :rtype: str
Below is the the instruction that describes the task: ### Input: Removes most variables from an SQL query and replaces them with X or N for numbers. Based on Mediawiki's DatabaseBase::generalizeSQL :type sql str|None :rtype: str ### Response: def generalize_sql(sql): """ Removes most variable...
def listify(*args): """ Convert args to a list, unless there's one arg and it's a function, then acts a decorator. """ if (len(args) == 1) and callable(args[0]): func = args[0] @wraps(func) def _inner(*args, **kwargs): return list(func(*args, **kwargs)) r...
Convert args to a list, unless there's one arg and it's a function, then acts a decorator.
Below is the the instruction that describes the task: ### Input: Convert args to a list, unless there's one arg and it's a function, then acts a decorator. ### Response: def listify(*args): """ Convert args to a list, unless there's one arg and it's a function, then acts a decorator. """ if...
def write_contents(self, table, reader): """Write the contents of `table` :Parameters: - `table`: an instance of a :py:class:`mysql2pgsql.lib.mysql_reader.MysqlReader.Table` object that represents the table to read/write. - `reader`: an instance of a :py:class:`mysql2pgsql.lib.mysql...
Write the contents of `table` :Parameters: - `table`: an instance of a :py:class:`mysql2pgsql.lib.mysql_reader.MysqlReader.Table` object that represents the table to read/write. - `reader`: an instance of a :py:class:`mysql2pgsql.lib.mysql_reader.MysqlReader` object that allows reading from...
Below is the the instruction that describes the task: ### Input: Write the contents of `table` :Parameters: - `table`: an instance of a :py:class:`mysql2pgsql.lib.mysql_reader.MysqlReader.Table` object that represents the table to read/write. - `reader`: an instance of a :py:class:`mysq...
def from_string(input_str) -> 'MissionTime': # noinspection SpellCheckingInspection """ Creates a MissionTime instance from a string Format: YYYYMMDDHHMMSS Args: input_str: string to parse Returns: MissionTime instance """ match = RE_INPUT_...
Creates a MissionTime instance from a string Format: YYYYMMDDHHMMSS Args: input_str: string to parse Returns: MissionTime instance
Below is the the instruction that describes the task: ### Input: Creates a MissionTime instance from a string Format: YYYYMMDDHHMMSS Args: input_str: string to parse Returns: MissionTime instance ### Response: def from_string(input_str) -> 'MissionTime': # noinspectio...
def load_name(*names, load_order=DEFAULT_LOAD_ORDER, extension='yaml', missing=Missing.silent): """ Read a `.Configuration` instance by name, trying to read from files in increasing significance. The default load order is `.system`, `.user`, `.application`, `.environment`. Multiple names are combin...
Read a `.Configuration` instance by name, trying to read from files in increasing significance. The default load order is `.system`, `.user`, `.application`, `.environment`. Multiple names are combined with multiple loaders using names as the 'inner loop / selector', loading ``/etc/name1.yaml`` and ``/...
Below is the the instruction that describes the task: ### Input: Read a `.Configuration` instance by name, trying to read from files in increasing significance. The default load order is `.system`, `.user`, `.application`, `.environment`. Multiple names are combined with multiple loaders using names as...
def status_log(func, message, *args, **kwargs): """Emits header message, executes a callable, and echoes the return strings.""" click.echo(message) log = func(*args, **kwargs) if log: out = [] for line in log.split('\n'): if not line.startswith('#'): out.ap...
Emits header message, executes a callable, and echoes the return strings.
Below is the the instruction that describes the task: ### Input: Emits header message, executes a callable, and echoes the return strings. ### Response: def status_log(func, message, *args, **kwargs): """Emits header message, executes a callable, and echoes the return strings.""" click.echo(message) l...
def __get_real_pid(self): """ Attempts to determine the true process ID by querying the /proc/<pid>/sched file. This works on systems with a proc filesystem. Otherwise default to os default. """ pid = None if os.path.exists("/proc/"): sched_file = "/...
Attempts to determine the true process ID by querying the /proc/<pid>/sched file. This works on systems with a proc filesystem. Otherwise default to os default.
Below is the the instruction that describes the task: ### Input: Attempts to determine the true process ID by querying the /proc/<pid>/sched file. This works on systems with a proc filesystem. Otherwise default to os default. ### Response: def __get_real_pid(self): """ Attempts to ...
def req(self, meth, url, http_data=''): """ sugar that wraps the 'requests' module with basic auth and some headers. """ self.logger.debug("Making request: %s %s\nBody:%s" % (meth, url, http_data)) req_method = getattr(requests, meth) return (req_method(url, ...
sugar that wraps the 'requests' module with basic auth and some headers.
Below is the the instruction that describes the task: ### Input: sugar that wraps the 'requests' module with basic auth and some headers. ### Response: def req(self, meth, url, http_data=''): """ sugar that wraps the 'requests' module with basic auth and some headers. """ self.logge...
def main(): """ NAME orientation_magic.py DESCRIPTION takes tab delimited field notebook information and converts to MagIC formatted tables SYNTAX orientation_magic.py [command line options] OPTIONS -f FILE: specify input file, default is: orient.txt -Fsa F...
NAME orientation_magic.py DESCRIPTION takes tab delimited field notebook information and converts to MagIC formatted tables SYNTAX orientation_magic.py [command line options] OPTIONS -f FILE: specify input file, default is: orient.txt -Fsa FILE: specify output file...
Below is the the instruction that describes the task: ### Input: NAME orientation_magic.py DESCRIPTION takes tab delimited field notebook information and converts to MagIC formatted tables SYNTAX orientation_magic.py [command line options] OPTIONS -f FILE: specify inpu...
def main(): '''Entry point''' if len(sys.argv) == 1: print("Usage: tyler [filename]") sys.exit(0) filename = sys.argv[1] if not os.path.isfile(filename): print("Specified file does not exists") sys.exit(8) my_tyler = Tyler(filename=filename) while True: ...
Entry point
Below is the the instruction that describes the task: ### Input: Entry point ### Response: def main(): '''Entry point''' if len(sys.argv) == 1: print("Usage: tyler [filename]") sys.exit(0) filename = sys.argv[1] if not os.path.isfile(filename): print("Specified file does no...
def save_instance(self, instance, using_transactions=True, dry_run=False): """ Takes care of saving the object to the database. Keep in mind that this is done by calling ``instance.save()``, so objects are not created in bulk! """ self.before_save_instance(instance, usin...
Takes care of saving the object to the database. Keep in mind that this is done by calling ``instance.save()``, so objects are not created in bulk!
Below is the the instruction that describes the task: ### Input: Takes care of saving the object to the database. Keep in mind that this is done by calling ``instance.save()``, so objects are not created in bulk! ### Response: def save_instance(self, instance, using_transactions=True, dry_run=Fals...
def _final_frame_length(header, final_frame_bytes): """Calculates the length of a final ciphertext frame, given a complete header and the number of bytes of ciphertext in the final frame. :param header: Complete message header object :type header: aws_encryption_sdk.structures.MessageHeader :param ...
Calculates the length of a final ciphertext frame, given a complete header and the number of bytes of ciphertext in the final frame. :param header: Complete message header object :type header: aws_encryption_sdk.structures.MessageHeader :param int final_frame_bytes: Bytes of ciphertext in the final fra...
Below is the the instruction that describes the task: ### Input: Calculates the length of a final ciphertext frame, given a complete header and the number of bytes of ciphertext in the final frame. :param header: Complete message header object :type header: aws_encryption_sdk.structures.MessageHeader ...
def adjust_datetime_to_timezone(value, from_tz, to_tz=None): """ Given a ``datetime`` object adjust it according to the from_tz timezone string into the to_tz timezone string. """ if to_tz is None: to_tz = settings.TIME_ZONE if value.tzinfo is None: if not hasattr(from_tz, "local...
Given a ``datetime`` object adjust it according to the from_tz timezone string into the to_tz timezone string.
Below is the the instruction that describes the task: ### Input: Given a ``datetime`` object adjust it according to the from_tz timezone string into the to_tz timezone string. ### Response: def adjust_datetime_to_timezone(value, from_tz, to_tz=None): """ Given a ``datetime`` object adjust it according ...
def get_all_keys(self, headers=None, callback=None, **params): """ A lower-level method for listing contents of a bucket. This closely models the actual S3 API and requires you to manually handle the paging of results. For a higher-level method that handles the details of paging...
A lower-level method for listing contents of a bucket. This closely models the actual S3 API and requires you to manually handle the paging of results. For a higher-level method that handles the details of paging for you, you can use the list method. :type max_keys: int ...
Below is the the instruction that describes the task: ### Input: A lower-level method for listing contents of a bucket. This closely models the actual S3 API and requires you to manually handle the paging of results. For a higher-level method that handles the details of paging for you, you ...
def register(): """ Plugin registration """ try: signals.article_generator_init.connect(feed_parser_initialization) signals.article_generator_context.connect(fetch_github_activity) except ImportError: logger.warning('`github_activity` failed to load dependency `feedparser...
Plugin registration
Below is the the instruction that describes the task: ### Input: Plugin registration ### Response: def register(): """ Plugin registration """ try: signals.article_generator_init.connect(feed_parser_initialization) signals.article_generator_context.connect(fetch_github_activity)...
def register_model_once(cls, ModelClass, **kwargs): """ Tweaked version of `AnyUrlField.register_model` that only registers the given model after checking that it is not already registered. """ if cls._static_registry.get_for_model(ModelClass) is None: logger.warn("Mo...
Tweaked version of `AnyUrlField.register_model` that only registers the given model after checking that it is not already registered.
Below is the the instruction that describes the task: ### Input: Tweaked version of `AnyUrlField.register_model` that only registers the given model after checking that it is not already registered. ### Response: def register_model_once(cls, ModelClass, **kwargs): """ Tweaked version of `An...
def _normalize(self, word): '''Normalization used in pre-processing. - All words are lower cased - Digits in the range 1800-2100 are represented as !YEAR; - Other digits are represented as !DIGITS :rtype: str ''' if '-' in word and word[0] != '-': re...
Normalization used in pre-processing. - All words are lower cased - Digits in the range 1800-2100 are represented as !YEAR; - Other digits are represented as !DIGITS :rtype: str
Below is the the instruction that describes the task: ### Input: Normalization used in pre-processing. - All words are lower cased - Digits in the range 1800-2100 are represented as !YEAR; - Other digits are represented as !DIGITS :rtype: str ### Response: def _normalize(self, wor...
def indent(buffer, from_row, to_row, count=1): """ Indent text of a :class:`.Buffer` object. """ current_row = buffer.document.cursor_position_row line_range = range(from_row, to_row) # Apply transformation. new_text = buffer.transform_lines(line_range, lambda l: ' ' * count + l) buf...
Indent text of a :class:`.Buffer` object.
Below is the the instruction that describes the task: ### Input: Indent text of a :class:`.Buffer` object. ### Response: def indent(buffer, from_row, to_row, count=1): """ Indent text of a :class:`.Buffer` object. """ current_row = buffer.document.cursor_position_row line_range = range(from_row...
def update(self, instance, oldValue, newValue): """Updates the aggregate based on a change in the child value.""" self.__set__(instance, self.__get__(instance, None) + newValue - (oldValue or 0))
Updates the aggregate based on a change in the child value.
Below is the the instruction that describes the task: ### Input: Updates the aggregate based on a change in the child value. ### Response: def update(self, instance, oldValue, newValue): """Updates the aggregate based on a change in the child value.""" self.__set__(instance, self.__get__(i...
def _integrateOrbit(vxvv,pot,t,method,dt): """ NAME: _integrateOrbit PURPOSE: integrate an orbit in a Phi(R) potential in the (R,phi)-plane INPUT: vxvv - array with the initial conditions stacked like [R,vR,vT,phi]; vR outward! pot - Potential instance t ...
NAME: _integrateOrbit PURPOSE: integrate an orbit in a Phi(R) potential in the (R,phi)-plane INPUT: vxvv - array with the initial conditions stacked like [R,vR,vT,phi]; vR outward! pot - Potential instance t - list of times at which to output (0 has to be in this...
Below is the the instruction that describes the task: ### Input: NAME: _integrateOrbit PURPOSE: integrate an orbit in a Phi(R) potential in the (R,phi)-plane INPUT: vxvv - array with the initial conditions stacked like [R,vR,vT,phi]; vR outward! pot - Potential inst...
def ae_latent_softmax(latents_pred, latents_discrete_hot, vocab_size, hparams): """Latent prediction and loss. Args: latents_pred: Tensor of shape [..., depth]. latents_discrete_hot: Tensor of shape [..., vocab_size]. vocab_size: an int representing the vocab size. hparams: HParams. Returns: ...
Latent prediction and loss. Args: latents_pred: Tensor of shape [..., depth]. latents_discrete_hot: Tensor of shape [..., vocab_size]. vocab_size: an int representing the vocab size. hparams: HParams. Returns: sample: Tensor of shape [...], a sample from a multinomial distribution. loss: T...
Below is the the instruction that describes the task: ### Input: Latent prediction and loss. Args: latents_pred: Tensor of shape [..., depth]. latents_discrete_hot: Tensor of shape [..., vocab_size]. vocab_size: an int representing the vocab size. hparams: HParams. Returns: sample: Tensor ...
def generate_file_shared_access_signature(self, share_name, directory_name=None, file_name=None, permission=None, expiry=None, ...
Generates a shared access signature for the file. Use the returned signature with the sas_token parameter of FileService. :param str share_name: Name of share. :param str directory_name: Name of directory. SAS tokens cannot be created for directories, so thi...
Below is the the instruction that describes the task: ### Input: Generates a shared access signature for the file. Use the returned signature with the sas_token parameter of FileService. :param str share_name: Name of share. :param str directory_name: Name of directo...
def f_expand(self, build_dict, fail_safe=True): """Similar to :func:`~pypet.trajectory.Trajectory.f_explore`, but can be used to enlarge already completed trajectories. Please ensure before usage, that all explored parameters are loaded! :param build_dict: Dictionary conta...
Similar to :func:`~pypet.trajectory.Trajectory.f_explore`, but can be used to enlarge already completed trajectories. Please ensure before usage, that all explored parameters are loaded! :param build_dict: Dictionary containing the expansion :param fail_safe: ...
Below is the the instruction that describes the task: ### Input: Similar to :func:`~pypet.trajectory.Trajectory.f_explore`, but can be used to enlarge already completed trajectories. Please ensure before usage, that all explored parameters are loaded! :param build_dict: Dictio...
def loglike(self, endog, mu, freq_weights=1, scale=1.): r""" The log-likelihood function in terms of the fitted mean response. Parameters ---------- endog : array-like Endogenous response variable mu : array-like Fitted mean response variable ...
r""" The log-likelihood function in terms of the fitted mean response. Parameters ---------- endog : array-like Endogenous response variable mu : array-like Fitted mean response variable freq_weights : array-like 1d array of frequency ...
Below is the the instruction that describes the task: ### Input: r""" The log-likelihood function in terms of the fitted mean response. Parameters ---------- endog : array-like Endogenous response variable mu : array-like Fitted mean response variable...
def _build_epsf_step(self, stars, epsf=None): """ A single iteration of improving an ePSF. Parameters ---------- stars : `EPSFStars` object The stars used to build the ePSF. epsf : `EPSFModel` object, optional The initial ePSF model. If not inpu...
A single iteration of improving an ePSF. Parameters ---------- stars : `EPSFStars` object The stars used to build the ePSF. epsf : `EPSFModel` object, optional The initial ePSF model. If not input, then the ePSF will be built from scratch. ...
Below is the the instruction that describes the task: ### Input: A single iteration of improving an ePSF. Parameters ---------- stars : `EPSFStars` object The stars used to build the ePSF. epsf : `EPSFModel` object, optional The initial ePSF model. If not i...
def repair_mongo(name, dbpath): """repair mongodb after usafe shutdown""" log_file = os.path.join(dbpath, 'mongod.log') cmd = [name, "--dbpath", dbpath, "--logpath", log_file, "--logappend", "--repair"] proc = subprocess.Popen( cmd, universal_newlines=True, stdout=subprocess.P...
repair mongodb after usafe shutdown
Below is the the instruction that describes the task: ### Input: repair mongodb after usafe shutdown ### Response: def repair_mongo(name, dbpath): """repair mongodb after usafe shutdown""" log_file = os.path.join(dbpath, 'mongod.log') cmd = [name, "--dbpath", dbpath, "--logpath", log_file, "--logappend...
def kata2hira(text, ignore=''): """Convert Full-width Katakana to Hiragana Parameters ---------- text : str Full-width Katakana string. ignore : str Characters to be ignored in converting. Return ------ str Hiragana string. Examples -------- >>> pri...
Convert Full-width Katakana to Hiragana Parameters ---------- text : str Full-width Katakana string. ignore : str Characters to be ignored in converting. Return ------ str Hiragana string. Examples -------- >>> print(jaconv.kata2hira('巴マミ')) 巴まみ ...
Below is the the instruction that describes the task: ### Input: Convert Full-width Katakana to Hiragana Parameters ---------- text : str Full-width Katakana string. ignore : str Characters to be ignored in converting. Return ------ str Hiragana string. Exa...
def get(self, sid): """ Constructs a TriggerContext :param sid: The unique string that identifies the resource :returns: twilio.rest.api.v2010.account.usage.trigger.TriggerContext :rtype: twilio.rest.api.v2010.account.usage.trigger.TriggerContext """ return Trig...
Constructs a TriggerContext :param sid: The unique string that identifies the resource :returns: twilio.rest.api.v2010.account.usage.trigger.TriggerContext :rtype: twilio.rest.api.v2010.account.usage.trigger.TriggerContext
Below is the the instruction that describes the task: ### Input: Constructs a TriggerContext :param sid: The unique string that identifies the resource :returns: twilio.rest.api.v2010.account.usage.trigger.TriggerContext :rtype: twilio.rest.api.v2010.account.usage.trigger.TriggerContext ##...
def fetch(self): """ Fetch a SyncListPermissionInstance :returns: Fetched SyncListPermissionInstance :rtype: twilio.rest.sync.v1.service.sync_list.sync_list_permission.SyncListPermissionInstance """ params = values.of({}) payload = self._version.fetch( ...
Fetch a SyncListPermissionInstance :returns: Fetched SyncListPermissionInstance :rtype: twilio.rest.sync.v1.service.sync_list.sync_list_permission.SyncListPermissionInstance
Below is the the instruction that describes the task: ### Input: Fetch a SyncListPermissionInstance :returns: Fetched SyncListPermissionInstance :rtype: twilio.rest.sync.v1.service.sync_list.sync_list_permission.SyncListPermissionInstance ### Response: def fetch(self): """ Fetch a ...
def parse_args(): """Parse arguments from the command line""" parser = argparse.ArgumentParser(description=TO_KIBANA5_DESC_MSG) parser.add_argument('-s', '--source', dest='src_path', \ required=True, help='source directory') parser.add_argument('-d', '--dest', dest='dest_path', \ requi...
Parse arguments from the command line
Below is the the instruction that describes the task: ### Input: Parse arguments from the command line ### Response: def parse_args(): """Parse arguments from the command line""" parser = argparse.ArgumentParser(description=TO_KIBANA5_DESC_MSG) parser.add_argument('-s', '--source', dest='src_path', \...
def perform_create(self, serializer): """Create a resource.""" process = serializer.validated_data.get('process') if not process.is_active: raise exceptions.ParseError( 'Process retired (id: {}, slug: {}/{}).'.format(process.id, process.slug, process.version) ...
Create a resource.
Below is the the instruction that describes the task: ### Input: Create a resource. ### Response: def perform_create(self, serializer): """Create a resource.""" process = serializer.validated_data.get('process') if not process.is_active: raise exceptions.ParseError( ...
def up_by_time(*filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR, count=1): """Sync most recent file by date, time attribues""" remote_files = command.map_files_raw(remote_dir=remote_dir) local_files = list_local_files(*filters, local_dir=local_dir) most_recent = sorted(local_files, key=lambda f: f...
Sync most recent file by date, time attribues
Below is the the instruction that describes the task: ### Input: Sync most recent file by date, time attribues ### Response: def up_by_time(*filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR, count=1): """Sync most recent file by date, time attribues""" remote_files = command.map_files_raw(remote_dir=r...
def _call(self, cmd, get_output): """Calls a command through the SSH connection. Remote stderr gets printed to this program's stderr. Output is captured and may be returned. """ server_err = self.server_logger() chan = self.get_client().get_transport().open_session() ...
Calls a command through the SSH connection. Remote stderr gets printed to this program's stderr. Output is captured and may be returned.
Below is the the instruction that describes the task: ### Input: Calls a command through the SSH connection. Remote stderr gets printed to this program's stderr. Output is captured and may be returned. ### Response: def _call(self, cmd, get_output): """Calls a command through the SSH conne...
def _from_jd_equinox(jd): '''Calculate the FR day using the equinox as day 1''' jd = trunc(jd) + 0.5 equinoxe = premier_da_la_annee(jd) an = gregorian.from_jd(equinoxe)[0] - YEAR_EPOCH mois = trunc((jd - equinoxe) / 30.) + 1 jour = int((jd - equinoxe) % 30) + 1 return (an, mois, jour)
Calculate the FR day using the equinox as day 1
Below is the the instruction that describes the task: ### Input: Calculate the FR day using the equinox as day 1 ### Response: def _from_jd_equinox(jd): '''Calculate the FR day using the equinox as day 1''' jd = trunc(jd) + 0.5 equinoxe = premier_da_la_annee(jd) an = gregorian.from_jd(equinoxe)[0]...
def BFS_Tree(G, start): """ Return an oriented tree constructed from bfs starting at 'start'. """ if start not in G.vertices: raise GraphInsertError("Vertex %s doesn't exist." % (start,)) pred = BFS(G, start) T = digraph.DiGraph() queue = Queue() queue.put(start) wh...
Return an oriented tree constructed from bfs starting at 'start'.
Below is the the instruction that describes the task: ### Input: Return an oriented tree constructed from bfs starting at 'start'. ### Response: def BFS_Tree(G, start): """ Return an oriented tree constructed from bfs starting at 'start'. """ if start not in G.vertices: raise GraphInse...
def iteritems(self): """ Sort and then iterate the dictionary """ sorted_data = sorted(self.data.iteritems(), self.cmp, self.key, self.reverse) for k,v in sorted_data: yield k,v
Sort and then iterate the dictionary
Below is the the instruction that describes the task: ### Input: Sort and then iterate the dictionary ### Response: def iteritems(self): """ Sort and then iterate the dictionary """ sorted_data = sorted(self.data.iteritems(), self.cmp, self.key, self.reverse) fo...
def Struct(fields): # pylint: disable=invalid-name """Construct a struct parameter type description protobuf. :type fields: list of :class:`type_pb2.StructType.Field` :param fields: the fields of the struct :rtype: :class:`type_pb2.Type` :returns: the appropriate struct-type protobuf """ ...
Construct a struct parameter type description protobuf. :type fields: list of :class:`type_pb2.StructType.Field` :param fields: the fields of the struct :rtype: :class:`type_pb2.Type` :returns: the appropriate struct-type protobuf
Below is the the instruction that describes the task: ### Input: Construct a struct parameter type description protobuf. :type fields: list of :class:`type_pb2.StructType.Field` :param fields: the fields of the struct :rtype: :class:`type_pb2.Type` :returns: the appropriate struct-type protobuf ##...
def get_data(self) -> bytes: """Return a compressed datablob representing this object. To restore the object, use :func:`fints.client.NeedRetryResponse.from_data`. """ data = { "_class_name": self.__class__.__name__, "version": 1, "segments_bi...
Return a compressed datablob representing this object. To restore the object, use :func:`fints.client.NeedRetryResponse.from_data`.
Below is the the instruction that describes the task: ### Input: Return a compressed datablob representing this object. To restore the object, use :func:`fints.client.NeedRetryResponse.from_data`. ### Response: def get_data(self) -> bytes: """Return a compressed datablob representing this ...
def get_submission(self, url=None, submission_id=None, comment_limit=0, comment_sort=None, params=None): """Return a Submission object for the given url or submission_id. :param comment_limit: The desired number of comments to fetch. If <= 0 fetch the default number f...
Return a Submission object for the given url or submission_id. :param comment_limit: The desired number of comments to fetch. If <= 0 fetch the default number for the session's user. If None, fetch the maximum possible. :param comment_sort: The sort order for retrieved comments....
Below is the the instruction that describes the task: ### Input: Return a Submission object for the given url or submission_id. :param comment_limit: The desired number of comments to fetch. If <= 0 fetch the default number for the session's user. If None, fetch the maximum possible...
def register(self, new_outputs, *args, **kwargs): """ Register outputs and metadata. * ``initial_value`` - used in dynamic calculations * ``size`` - number of elements per timestep * ``uncertainty`` - in percent of nominal value * ``variance`` - dictionary of covariances...
Register outputs and metadata. * ``initial_value`` - used in dynamic calculations * ``size`` - number of elements per timestep * ``uncertainty`` - in percent of nominal value * ``variance`` - dictionary of covariances, diagonal is square of uncertianties, no units * ``...
Below is the the instruction that describes the task: ### Input: Register outputs and metadata. * ``initial_value`` - used in dynamic calculations * ``size`` - number of elements per timestep * ``uncertainty`` - in percent of nominal value * ``variance`` - dictionary of covariances,...
def handle_symbol_search(self, call_id, payload): """Handler for symbol search results""" self.log.debug('handle_symbol_search: in %s', Pretty(payload)) syms = payload["syms"] qfList = [] for sym in syms: p = sym.get("pos") if p: item = se...
Handler for symbol search results
Below is the the instruction that describes the task: ### Input: Handler for symbol search results ### Response: def handle_symbol_search(self, call_id, payload): """Handler for symbol search results""" self.log.debug('handle_symbol_search: in %s', Pretty(payload)) syms = payload["syms"] ...