code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def post(request): """Creates a tag object :param name: Name for tag :type name: str :returns: json """ res = Result() data = request.POST or json.loads(request.body)['body'] name = data.get('name', None) if not name: res.isError = True res.message = "No name given"...
Creates a tag object :param name: Name for tag :type name: str :returns: json
Below is the the instruction that describes the task: ### Input: Creates a tag object :param name: Name for tag :type name: str :returns: json ### Response: def post(request): """Creates a tag object :param name: Name for tag :type name: str :returns: json """ res = Result() ...
def serialize(self, queryset, **options): """ Serialize a queryset. """ self.options = options self.stream = options.get("stream", StringIO()) self.primary_key = options.get("primary_key", None) self.properties = options.get("properties") self.geometry_fi...
Serialize a queryset.
Below is the the instruction that describes the task: ### Input: Serialize a queryset. ### Response: def serialize(self, queryset, **options): """ Serialize a queryset. """ self.options = options self.stream = options.get("stream", StringIO()) self.primary_key = opt...
def make_plot( self, count, plot=None, show=False, plottype='probability', bar=dict(alpha=0.15, color='b', linewidth=1.0, edgecolor='b'), errorbar=dict(fmt='b.'), gaussian=dict(ls='--', c='r') ): """ Convert histogram counts in array ``count`` into a plot. Args: ...
Convert histogram counts in array ``count`` into a plot. Args: count (array): Array of histogram counts (see :meth:`PDFHistogram.count`). plot (plotter): :mod:`matplotlib` plotting window. If ``None`` uses the default window. Default is ``None``. ...
Below is the the instruction that describes the task: ### Input: Convert histogram counts in array ``count`` into a plot. Args: count (array): Array of histogram counts (see :meth:`PDFHistogram.count`). plot (plotter): :mod:`matplotlib` plotting window. If ``None`` ...
def create_all(graph): """ Create all database tables. """ head = get_current_head(graph) if head is None: Model.metadata.create_all(graph.postgres) stamp_head(graph)
Create all database tables.
Below is the the instruction that describes the task: ### Input: Create all database tables. ### Response: def create_all(graph): """ Create all database tables. """ head = get_current_head(graph) if head is None: Model.metadata.create_all(graph.postgres) stamp_head(graph)
def get_method_map(self, viewset, method_map): """ Given a viewset, and a mapping of http methods to actions, return a new mapping which only includes any mappings that are actually implemented by the viewset. """ bound_methods = {} for method, action in method_map.item...
Given a viewset, and a mapping of http methods to actions, return a new mapping which only includes any mappings that are actually implemented by the viewset.
Below is the the instruction that describes the task: ### Input: Given a viewset, and a mapping of http methods to actions, return a new mapping which only includes any mappings that are actually implemented by the viewset. ### Response: def get_method_map(self, viewset, method_map): """ Gi...
def logger_initial_config(service_name=None, log_level=None, logger_format=None, logger_date_format=None): '''Set initial logging configurations. :param service_name: Name of the service :type logger: String :param log_level...
Set initial logging configurations. :param service_name: Name of the service :type logger: String :param log_level: A string or integer corresponding to a Python logging level :type log_level: String :param logger_format: A string defining the format of the logs :type log_level: String :...
Below is the the instruction that describes the task: ### Input: Set initial logging configurations. :param service_name: Name of the service :type logger: String :param log_level: A string or integer corresponding to a Python logging level :type log_level: String :param logger_format: A stri...
def render_subject(self, context): """ Renders the message subject for the given context. The context data is automatically unescaped to avoid rendering HTML entities in ``text/plain`` content. :param context: The context to use when rendering the subject template. :typ...
Renders the message subject for the given context. The context data is automatically unescaped to avoid rendering HTML entities in ``text/plain`` content. :param context: The context to use when rendering the subject template. :type context: :class:`~django.template.Context` :r...
Below is the the instruction that describes the task: ### Input: Renders the message subject for the given context. The context data is automatically unescaped to avoid rendering HTML entities in ``text/plain`` content. :param context: The context to use when rendering the subject template...
def hazard_at_times(self, times, label=None): """ Return a Pandas series of the predicted hazard at specific times. Parameters ----------- times: iterable or float values to return the hazard at. label: string, optional Rename the series returned. Use...
Return a Pandas series of the predicted hazard at specific times. Parameters ----------- times: iterable or float values to return the hazard at. label: string, optional Rename the series returned. Useful for plotting. Returns -------- pd.Ser...
Below is the the instruction that describes the task: ### Input: Return a Pandas series of the predicted hazard at specific times. Parameters ----------- times: iterable or float values to return the hazard at. label: string, optional Rename the series returned. ...
def handle_delete_scan_command(self, scan_et): """ Handles <delete_scan> command. @return: Response string for <delete_scan> command. """ scan_id = scan_et.attrib.get('scan_id') if scan_id is None: return simple_response_str('delete_scan', 404, ...
Handles <delete_scan> command. @return: Response string for <delete_scan> command.
Below is the the instruction that describes the task: ### Input: Handles <delete_scan> command. @return: Response string for <delete_scan> command. ### Response: def handle_delete_scan_command(self, scan_et): """ Handles <delete_scan> command. @return: Response string for <delete_scan> co...
def _process_sasl_failure(self, stream, element): """Process incoming <sasl:failure/> element. [initiating entity only] """ _unused = stream if not self.authenticator: logger.debug("Unexpected SASL response") return False logger.debug("SASL authe...
Process incoming <sasl:failure/> element. [initiating entity only]
Below is the the instruction that describes the task: ### Input: Process incoming <sasl:failure/> element. [initiating entity only] ### Response: def _process_sasl_failure(self, stream, element): """Process incoming <sasl:failure/> element. [initiating entity only] """ _un...
def run(): """This client generates customer reports on all the samples in workbench.""" # Grab server args args = client_helper.grab_server_args() # Start up workbench connection workbench = zerorpc.Client(timeout=300, heartbeat=60) workbench.connect('tcp://'+args['server']+':'+args['port...
This client generates customer reports on all the samples in workbench.
Below is the the instruction that describes the task: ### Input: This client generates customer reports on all the samples in workbench. ### Response: def run(): """This client generates customer reports on all the samples in workbench.""" # Grab server args args = client_helper.grab_server_args()...
def jsonify(symbol): """ returns json format for symbol """ try: # all symbols have a toJson method, try it return json.dumps(symbol.toJson(), indent=' ') except AttributeError: pass return json.dumps(symbol, indent=' ')
returns json format for symbol
Below is the the instruction that describes the task: ### Input: returns json format for symbol ### Response: def jsonify(symbol): """ returns json format for symbol """ try: # all symbols have a toJson method, try it return json.dumps(symbol.toJson(), indent=' ') except AttributeError...
def parse_names_and_default(self): """parse for `parse_content` {title: [('-a, --all=STH', 'default'), ...]}""" result = {} for title, text in self.formal_content.items(): if not text: result[title] = [] continue logger....
parse for `parse_content` {title: [('-a, --all=STH', 'default'), ...]}
Below is the the instruction that describes the task: ### Input: parse for `parse_content` {title: [('-a, --all=STH', 'default'), ...]} ### Response: def parse_names_and_default(self): """parse for `parse_content` {title: [('-a, --all=STH', 'default'), ...]}""" result = {} ...
def read(self, cmd_args): """ Execute Vagrant read command. :param list cmd_args: Command argument list. """ args = [ "vagrant", "--machine-readable" ] args.extend(cmd_args) proc = subprocess.Popen(args, stdout=subprocess.PIPE) for line in proc.stdout.readlines(): if len(line) ==...
Execute Vagrant read command. :param list cmd_args: Command argument list.
Below is the the instruction that describes the task: ### Input: Execute Vagrant read command. :param list cmd_args: Command argument list. ### Response: def read(self, cmd_args): """ Execute Vagrant read command. :param list cmd_args: Command argument list. """ args = [ "vagran...
def remove_watcher(self, issue, watcher): """Remove a user from an issue's watch list. :param issue: ID or key of the issue affected :param watcher: username of the user to remove from the watchers list :rtype: Response """ url = self._get_url('issue/' + str(issue) + '/w...
Remove a user from an issue's watch list. :param issue: ID or key of the issue affected :param watcher: username of the user to remove from the watchers list :rtype: Response
Below is the the instruction that describes the task: ### Input: Remove a user from an issue's watch list. :param issue: ID or key of the issue affected :param watcher: username of the user to remove from the watchers list :rtype: Response ### Response: def remove_watcher(self, issue, watc...
def info(self, remote_path): """Gets information about resource on WebDAV. More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_PROPFIND :param remote_path: the path to remote resource. :return: a dictionary of information attributes and them values with fol...
Gets information about resource on WebDAV. More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_PROPFIND :param remote_path: the path to remote resource. :return: a dictionary of information attributes and them values with following keys: `created`:...
Below is the the instruction that describes the task: ### Input: Gets information about resource on WebDAV. More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_PROPFIND :param remote_path: the path to remote resource. :return: a dictionary of information attrib...
def add_unique_element(self, location, element): """ Create an entry located at ``location``. Args: location: String or :class:`LocationDescriptor` to describe a "separator location" (i.e. dir1/dir2/dir3 for instance). element: Element to store. ...
Create an entry located at ``location``. Args: location: String or :class:`LocationDescriptor` to describe a "separator location" (i.e. dir1/dir2/dir3 for instance). element: Element to store. Returns: The created node with the elemen...
Below is the the instruction that describes the task: ### Input: Create an entry located at ``location``. Args: location: String or :class:`LocationDescriptor` to describe a "separator location" (i.e. dir1/dir2/dir3 for instance). element: Element to store. ...
def maybe_stream(s): """Ensure that the given argument is a stream.""" if isinstance(s, Stream): return s if s is None: stream = InMemStream() stream.close() # we don't intend to write anything return stream if isinstance(s, unicode): s = s.encode('utf-8') ...
Ensure that the given argument is a stream.
Below is the the instruction that describes the task: ### Input: Ensure that the given argument is a stream. ### Response: def maybe_stream(s): """Ensure that the given argument is a stream.""" if isinstance(s, Stream): return s if s is None: stream = InMemStream() stream.close...
def with_index(self, new_index): """ Returns a TimeSeriesRDD rebased on top of a new index. Any timestamps that exist in the new index but not in the existing index will be filled in with NaNs. Parameters ---------- new_index : DateTimeIndex """ ...
Returns a TimeSeriesRDD rebased on top of a new index. Any timestamps that exist in the new index but not in the existing index will be filled in with NaNs. Parameters ---------- new_index : DateTimeIndex
Below is the the instruction that describes the task: ### Input: Returns a TimeSeriesRDD rebased on top of a new index. Any timestamps that exist in the new index but not in the existing index will be filled in with NaNs. Parameters ---------- new_index : DateTimeIndex ### ...
def get_env(env_file='.env'): """ Set default environment variables from .env file """ try: with open(env_file) as f: for line in f.readlines(): try: key, val = line.split('=', maxsplit=1) os.environ.setdefault(key.strip(), val....
Set default environment variables from .env file
Below is the the instruction that describes the task: ### Input: Set default environment variables from .env file ### Response: def get_env(env_file='.env'): """ Set default environment variables from .env file """ try: with open(env_file) as f: for line in f.readlines(): ...
def validate(cert, ca_name, crl_file): ''' .. versionadded:: Neon Validate a certificate against a given CA/CRL. cert path to the certifiate PEM file or string ca_name name of the CA crl_file full path to the CRL file ''' store = OpenSSL.crypto.X509Store() ...
.. versionadded:: Neon Validate a certificate against a given CA/CRL. cert path to the certifiate PEM file or string ca_name name of the CA crl_file full path to the CRL file
Below is the the instruction that describes the task: ### Input: .. versionadded:: Neon Validate a certificate against a given CA/CRL. cert path to the certifiate PEM file or string ca_name name of the CA crl_file full path to the CRL file ### Response: def validate(cert...
def AgregarUbicacionTambo(self, latitud, longitud, domicilio, cod_localidad, cod_provincia, codigo_postal, nombre_partido_depto, **kwargs): "Agrego los datos del productor a la liq." ubic_tambo = {'latitud': latitud, 'lon...
Agrego los datos del productor a la liq.
Below is the the instruction that describes the task: ### Input: Agrego los datos del productor a la liq. ### Response: def AgregarUbicacionTambo(self, latitud, longitud, domicilio, cod_localidad, cod_provincia, codigo_postal, nombre_partido_depto, **kwar...
def operator_oropt(self, graph, solution, op_diff_round_digits, anim=None): # TODO: check docstring """Applies Or-Opt intra-route operator to solution Takes chains of nodes (length=3..1 consecutive nodes) from a given route and calculates savings when inserted into another posit...
Applies Or-Opt intra-route operator to solution Takes chains of nodes (length=3..1 consecutive nodes) from a given route and calculates savings when inserted into another position on the same route (all possible positions). Performes best move (max. saving) and starts over again...
Below is the the instruction that describes the task: ### Input: Applies Or-Opt intra-route operator to solution Takes chains of nodes (length=3..1 consecutive nodes) from a given route and calculates savings when inserted into another position on the same route (all possible positi...
def get_attribute_from_indices(self, indices: list, attribute_name: str): """Get attribute values for the requested indices. :param indices: Indices of vertices for which the attribute values are requested. :param attribute_name: The name of the attribute. :return: A list of attribute v...
Get attribute values for the requested indices. :param indices: Indices of vertices for which the attribute values are requested. :param attribute_name: The name of the attribute. :return: A list of attribute values for the requested indices.
Below is the the instruction that describes the task: ### Input: Get attribute values for the requested indices. :param indices: Indices of vertices for which the attribute values are requested. :param attribute_name: The name of the attribute. :return: A list of attribute values for the re...
def QA_fetch_risk(message={}, params={"_id": 0, 'assets': 0, 'timeindex': 0, 'totaltimeindex': 0, 'benchmark_assets': 0, 'month_profit': 0}, db=DATABASE): """get the risk message Arguments: query_mes {[type]} -- [description] Keyword Arguments: collection {[type]} -- [description] (default...
get the risk message Arguments: query_mes {[type]} -- [description] Keyword Arguments: collection {[type]} -- [description] (default: {DATABASE}) Returns: [type] -- [description]
Below is the the instruction that describes the task: ### Input: get the risk message Arguments: query_mes {[type]} -- [description] Keyword Arguments: collection {[type]} -- [description] (default: {DATABASE}) Returns: [type] -- [description] ### Response: def QA_fetch_risk(...
def from_histogram(cls, histogram, bin_edges, axis_names=None): """Make a HistdD from numpy histogram + bin edges :param histogram: Initial histogram :param bin_edges: x bin edges of histogram, y bin edges, ... :return: Histnd instance """ bin_edges = np.array(bin_edges) ...
Make a HistdD from numpy histogram + bin edges :param histogram: Initial histogram :param bin_edges: x bin edges of histogram, y bin edges, ... :return: Histnd instance
Below is the the instruction that describes the task: ### Input: Make a HistdD from numpy histogram + bin edges :param histogram: Initial histogram :param bin_edges: x bin edges of histogram, y bin edges, ... :return: Histnd instance ### Response: def from_histogram(cls, histogram, bin_edge...
def asset_create_combo(self, name, combo, tag='', description=''): '''asset_create_combo name, combination, tag, description Creates a new combination asset list. Operands can be either asset list IDs or be a nested combination asset list. UN-DOCUMENTED CALL: This function is not consi...
asset_create_combo name, combination, tag, description Creates a new combination asset list. Operands can be either asset list IDs or be a nested combination asset list. UN-DOCUMENTED CALL: This function is not considered stable. AND = intersection OR = union operand =...
Below is the the instruction that describes the task: ### Input: asset_create_combo name, combination, tag, description Creates a new combination asset list. Operands can be either asset list IDs or be a nested combination asset list. UN-DOCUMENTED CALL: This function is not considered sta...
def fix_variable(self, v, value): """Fix the value of a variable and remove it from the constraint. Args: v (variable): Variable in the constraint to be set to a constant value. val (int): Value assigned to the variable. Values must match the :cl...
Fix the value of a variable and remove it from the constraint. Args: v (variable): Variable in the constraint to be set to a constant value. val (int): Value assigned to the variable. Values must match the :class:`.Vartype` of the constra...
Below is the the instruction that describes the task: ### Input: Fix the value of a variable and remove it from the constraint. Args: v (variable): Variable in the constraint to be set to a constant value. val (int): Value assigned to the variable. V...
def _merge_prims(prims, *, debug=False, stagenames=None, stages=None): """Helper method to greedily combine Frames (of Primitives) or Primitives based on the rules defined in the Primitive's class. Used by a CommandQueue during compilation and optimization of Primitives. Args: prims: A list or...
Helper method to greedily combine Frames (of Primitives) or Primitives based on the rules defined in the Primitive's class. Used by a CommandQueue during compilation and optimization of Primitives. Args: prims: A list or FrameSequence of Primitives or Frames (respectively) to try to merge together...
Below is the the instruction that describes the task: ### Input: Helper method to greedily combine Frames (of Primitives) or Primitives based on the rules defined in the Primitive's class. Used by a CommandQueue during compilation and optimization of Primitives. Args: prims: A list or FrameSeq...
def _get_corr_stddevs(C, tau_ss, stddev_types, num_sites, phi_ss, NL=None, tau_value=None): """ Return standard deviations adjusted for single station sigma as the total standard deviation - as proposed to be used in the Swiss Hazard Model [2014]. """ stddevs = [] temp_...
Return standard deviations adjusted for single station sigma as the total standard deviation - as proposed to be used in the Swiss Hazard Model [2014].
Below is the the instruction that describes the task: ### Input: Return standard deviations adjusted for single station sigma as the total standard deviation - as proposed to be used in the Swiss Hazard Model [2014]. ### Response: def _get_corr_stddevs(C, tau_ss, stddev_types, num_sites, phi_ss, NL=None, ...
def _vagrant_ssh_config(vm_): ''' get the information for ssh communication from the new VM :param vm_: the VM's info as we have it now :return: dictionary of ssh stuff ''' machine = vm_['machine'] log.info('requesting vagrant ssh-config for VM %s', machine or '(default)') cmd = 'vagran...
get the information for ssh communication from the new VM :param vm_: the VM's info as we have it now :return: dictionary of ssh stuff
Below is the the instruction that describes the task: ### Input: get the information for ssh communication from the new VM :param vm_: the VM's info as we have it now :return: dictionary of ssh stuff ### Response: def _vagrant_ssh_config(vm_): ''' get the information for ssh communication from the...
def get_version(): """Reads the version (MAJOR.MINOR) from this module.""" release = get_release() split_version = release.split(".") if len(split_version) == 3: return ".".join(split_version[:2]) return release
Reads the version (MAJOR.MINOR) from this module.
Below is the the instruction that describes the task: ### Input: Reads the version (MAJOR.MINOR) from this module. ### Response: def get_version(): """Reads the version (MAJOR.MINOR) from this module.""" release = get_release() split_version = release.split(".") if len(split_version) == 3: ...
def warn(self, msg, whitespace_strp=True): """ For things that have gone seriously wrong but don't merit a program halt. Outputs to stderr, so JsonOutput does not need to override. @param msg: warning to output. @param whitespace_strp: whether to strip whitespace. ...
For things that have gone seriously wrong but don't merit a program halt. Outputs to stderr, so JsonOutput does not need to override. @param msg: warning to output. @param whitespace_strp: whether to strip whitespace.
Below is the the instruction that describes the task: ### Input: For things that have gone seriously wrong but don't merit a program halt. Outputs to stderr, so JsonOutput does not need to override. @param msg: warning to output. @param whitespace_strp: whether to strip whitespace. #...
def ts_to_df(metadata): """ Create a data frame from one TimeSeries object :param dict metadata: Time Series dictionary :return dict: One data frame per table, organized in a dictionary by name """ logger_dataframes.info("enter ts_to_df") dfs = {} # Plot the variable + values vs year, a...
Create a data frame from one TimeSeries object :param dict metadata: Time Series dictionary :return dict: One data frame per table, organized in a dictionary by name
Below is the the instruction that describes the task: ### Input: Create a data frame from one TimeSeries object :param dict metadata: Time Series dictionary :return dict: One data frame per table, organized in a dictionary by name ### Response: def ts_to_df(metadata): """ Create a data frame from o...
def set_defaults(self, config_file): """Set defaults. """ self.defaults = Defaults(config_file) self.python = Python() self.setuptools = Setuptools() self.docutils = Docutils() self.styles = self.defaults.styles self.browser = self.defaults.browser ...
Set defaults.
Below is the the instruction that describes the task: ### Input: Set defaults. ### Response: def set_defaults(self, config_file): """Set defaults. """ self.defaults = Defaults(config_file) self.python = Python() self.setuptools = Setuptools() self.docutils = Docutils...
def null_advance(self, blocksize): """Advance and insert zeros Parameters ---------- blocksize: int The number of seconds to attempt to read from the channel """ self.raw_buffer.roll(-int(blocksize * self.raw_sample_rate)) self.read_pos += blocksize ...
Advance and insert zeros Parameters ---------- blocksize: int The number of seconds to attempt to read from the channel
Below is the the instruction that describes the task: ### Input: Advance and insert zeros Parameters ---------- blocksize: int The number of seconds to attempt to read from the channel ### Response: def null_advance(self, blocksize): """Advance and insert zeros ...
def get(self): """ Constructs a ExecutionContextContext :returns: twilio.rest.studio.v1.flow.execution.execution_context.ExecutionContextContext :rtype: twilio.rest.studio.v1.flow.execution.execution_context.ExecutionContextContext """ return ExecutionContextContext( ...
Constructs a ExecutionContextContext :returns: twilio.rest.studio.v1.flow.execution.execution_context.ExecutionContextContext :rtype: twilio.rest.studio.v1.flow.execution.execution_context.ExecutionContextContext
Below is the the instruction that describes the task: ### Input: Constructs a ExecutionContextContext :returns: twilio.rest.studio.v1.flow.execution.execution_context.ExecutionContextContext :rtype: twilio.rest.studio.v1.flow.execution.execution_context.ExecutionContextContext ### Response: def ge...
def _convert_before_2_0_0_b3(self, dynamips_id): """ Before 2.0.0 beta3 the node didn't have a folder by node when we start we move the file, we can't do it in the topology conversion due to case of remote servers """ dynamips_dir = self.project.module_working_directory(s...
Before 2.0.0 beta3 the node didn't have a folder by node when we start we move the file, we can't do it in the topology conversion due to case of remote servers
Below is the the instruction that describes the task: ### Input: Before 2.0.0 beta3 the node didn't have a folder by node when we start we move the file, we can't do it in the topology conversion due to case of remote servers ### Response: def _convert_before_2_0_0_b3(self, dynamips_id): ""...
def censor_background(sample_frame, ntc_samples=['NTC'], margin=log2(10)): """Selects rows from the sample data frame that fall `margin` or greater cycles earlier than the NTC for that target. NTC wells are recognized by string matching against the Sample column. :param DataFrame sample_frame: A sample...
Selects rows from the sample data frame that fall `margin` or greater cycles earlier than the NTC for that target. NTC wells are recognized by string matching against the Sample column. :param DataFrame sample_frame: A sample data frame. :param iterable ntc_samples: A sequence of strings giving the sam...
Below is the the instruction that describes the task: ### Input: Selects rows from the sample data frame that fall `margin` or greater cycles earlier than the NTC for that target. NTC wells are recognized by string matching against the Sample column. :param DataFrame sample_frame: A sample data frame. ...
def clustering_coef_bu(G): ''' The clustering coefficient is the fraction of triangles around a node (equiv. the fraction of nodes neighbors that are neighbors of each other). Parameters ---------- A : NxN np.ndarray binary undirected connection matrix Returns ------- C : N...
The clustering coefficient is the fraction of triangles around a node (equiv. the fraction of nodes neighbors that are neighbors of each other). Parameters ---------- A : NxN np.ndarray binary undirected connection matrix Returns ------- C : Nx1 np.ndarray clustering coeffi...
Below is the the instruction that describes the task: ### Input: The clustering coefficient is the fraction of triangles around a node (equiv. the fraction of nodes neighbors that are neighbors of each other). Parameters ---------- A : NxN np.ndarray binary undirected connection matrix ...
def get_ht_capability(cap): """http://git.kernel.org/cgit/linux/kernel/git/jberg/iw.git/tree/util.c?id=v3.17#n541. Positional arguments: cap -- c_uint16 Returns: List. """ answers = list() if cap & 1: answers.append('RX LDPC') if cap & 2: answers.append('HT20/HT40')...
http://git.kernel.org/cgit/linux/kernel/git/jberg/iw.git/tree/util.c?id=v3.17#n541. Positional arguments: cap -- c_uint16 Returns: List.
Below is the the instruction that describes the task: ### Input: http://git.kernel.org/cgit/linux/kernel/git/jberg/iw.git/tree/util.c?id=v3.17#n541. Positional arguments: cap -- c_uint16 Returns: List. ### Response: def get_ht_capability(cap): """http://git.kernel.org/cgit/linux/kernel/git/jb...
def is_valid(self, name=None, debug=False): """ Check to see if the current xml path is to be processed. """ valid_tags = self.action_tree invalid = False for item in self.current_tree: try: if item in valid_tags or self.ALL_TAGS in valid_tags:...
Check to see if the current xml path is to be processed.
Below is the the instruction that describes the task: ### Input: Check to see if the current xml path is to be processed. ### Response: def is_valid(self, name=None, debug=False): """ Check to see if the current xml path is to be processed. """ valid_tags = self.action_tree ...
def software_fibonacci(n): """ a normal old python function to return the Nth fibonacci number. """ a, b = 0, 1 for i in range(n): a, b = b, a + b return a
a normal old python function to return the Nth fibonacci number.
Below is the the instruction that describes the task: ### Input: a normal old python function to return the Nth fibonacci number. ### Response: def software_fibonacci(n): """ a normal old python function to return the Nth fibonacci number. """ a, b = 0, 1 for i in range(n): a, b = b, a + b ...
def set_context(self, filename): """ Provide filename context to airflow task handler. :param filename: filename in which the dag is located """ local_loc = self._init_file(filename) self.handler = logging.FileHandler(local_loc) self.handler.setFormatter(self.form...
Provide filename context to airflow task handler. :param filename: filename in which the dag is located
Below is the the instruction that describes the task: ### Input: Provide filename context to airflow task handler. :param filename: filename in which the dag is located ### Response: def set_context(self, filename): """ Provide filename context to airflow task handler. :param filena...
def is_subdict(self, a,b): ''' Return True if a is a subdict of b ''' return all((k in b and b[k]==v) for k,v in a.iteritems())
Return True if a is a subdict of b
Below is the the instruction that describes the task: ### Input: Return True if a is a subdict of b ### Response: def is_subdict(self, a,b): ''' Return True if a is a subdict of b ''' return all((k in b and b[k]==v) for k,v in a.iteritems())
def insert(self, bs, pos=None): """Insert bs at bit position pos. bs -- The bitstring to insert. pos -- The bit position to insert at. Raises ValueError if pos < 0 or pos > self.len. """ bs = Bits(bs) if not bs.len: return self if bs is self...
Insert bs at bit position pos. bs -- The bitstring to insert. pos -- The bit position to insert at. Raises ValueError if pos < 0 or pos > self.len.
Below is the the instruction that describes the task: ### Input: Insert bs at bit position pos. bs -- The bitstring to insert. pos -- The bit position to insert at. Raises ValueError if pos < 0 or pos > self.len. ### Response: def insert(self, bs, pos=None): """Insert bs at bit po...
def get_collection(self, session, query, api_key): """ Fetch a collection of resources of a specified type. :param session: SQLAlchemy session :param query: Dict of query args :param api_type: The type of the model """ model = self._fetch_model(api_key) i...
Fetch a collection of resources of a specified type. :param session: SQLAlchemy session :param query: Dict of query args :param api_type: The type of the model
Below is the the instruction that describes the task: ### Input: Fetch a collection of resources of a specified type. :param session: SQLAlchemy session :param query: Dict of query args :param api_type: The type of the model ### Response: def get_collection(self, session, query, api_key): ...
def add_child(self, child): """ Adds self as parent to child, and then adds child. """ child.parent = self self.children.append(child) return child
Adds self as parent to child, and then adds child.
Below is the the instruction that describes the task: ### Input: Adds self as parent to child, and then adds child. ### Response: def add_child(self, child): """ Adds self as parent to child, and then adds child. """ child.parent = self self.children.append(child) re...
def pluck(self, key): """ Convenience version of a common use case of `map`: fetching a property. """ return self._wrap([x.get(key) for x in self.obj])
Convenience version of a common use case of `map`: fetching a property.
Below is the the instruction that describes the task: ### Input: Convenience version of a common use case of `map`: fetching a property. ### Response: def pluck(self, key): """ Convenience version of a common use case of `map`: fetching a property. """ return self._w...
def drawBackground( self, painter, rect ): """ Draws the backgrounds for the different chart types. :param painter | <QPainter> rect | <QRect> """ if ( self._dirty ): self.rebuild() if ( self.showGrid() )...
Draws the backgrounds for the different chart types. :param painter | <QPainter> rect | <QRect>
Below is the the instruction that describes the task: ### Input: Draws the backgrounds for the different chart types. :param painter | <QPainter> rect | <QRect> ### Response: def drawBackground( self, painter, rect ): """ Draws the backgrounds for t...
def _or_query(self, term_list, field, field_type): """ Joins each item of term_list decorated by _term_query with an OR. """ term_list = [self._term_query(term, field, field_type) for term in term_list] return xapian.Query(xapian.Query.OP_OR, term_list)
Joins each item of term_list decorated by _term_query with an OR.
Below is the the instruction that describes the task: ### Input: Joins each item of term_list decorated by _term_query with an OR. ### Response: def _or_query(self, term_list, field, field_type): """ Joins each item of term_list decorated by _term_query with an OR. """ term_list = [...
def has_insert(self, shape): """Returns True if any of the inserts have the given shape.""" for insert in self.inserts: if insert.shape == shape: return True return False
Returns True if any of the inserts have the given shape.
Below is the the instruction that describes the task: ### Input: Returns True if any of the inserts have the given shape. ### Response: def has_insert(self, shape): """Returns True if any of the inserts have the given shape.""" for insert in self.inserts: if insert.shape == shape: ...
def _gen_ticket(prefix=None, lg=settings.CAS_TICKET_LEN): """ Generate a ticket with prefix ``prefix`` and length ``lg`` :param unicode prefix: An optional prefix (probably ST, PT, PGT or PGTIOU) :param int lg: The length of the generated ticket (with the prefix) :return: A randomll...
Generate a ticket with prefix ``prefix`` and length ``lg`` :param unicode prefix: An optional prefix (probably ST, PT, PGT or PGTIOU) :param int lg: The length of the generated ticket (with the prefix) :return: A randomlly generated ticket of length ``lg`` :rtype: unicode
Below is the the instruction that describes the task: ### Input: Generate a ticket with prefix ``prefix`` and length ``lg`` :param unicode prefix: An optional prefix (probably ST, PT, PGT or PGTIOU) :param int lg: The length of the generated ticket (with the prefix) :return: A randomlly gen...
def makerandCIJ_dir(n, k, seed=None): ''' This function generates a directed random network Parameters ---------- N : int number of vertices K : int number of edges seed : hashable, optional If None (default), use the np.random's global random state to generate rando...
This function generates a directed random network Parameters ---------- N : int number of vertices K : int number of edges seed : hashable, optional If None (default), use the np.random's global random state to generate random numbers. Otherwise, use a new np.random....
Below is the the instruction that describes the task: ### Input: This function generates a directed random network Parameters ---------- N : int number of vertices K : int number of edges seed : hashable, optional If None (default), use the np.random's global random stat...
def remove_product_version(self, id, product_version_id, **kwargs): """ Removes a product version from the specified config set This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoke...
Removes a product version from the specified config 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): >>> ...
Below is the the instruction that describes the task: ### Input: Removes a product version from the specified config 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 th...
def subtract_metabolites(self, metabolites, combine=True, reversibly=True): """Subtract metabolites from a reaction. That means add the metabolites with -1*coefficient. If the final coefficient for a metabolite is 0 then the metabolite is removed from the reaction. Notes ...
Subtract metabolites from a reaction. That means add the metabolites with -1*coefficient. If the final coefficient for a metabolite is 0 then the metabolite is removed from the reaction. Notes ----- * A final coefficient < 0 implies a reactant. * The change is r...
Below is the the instruction that describes the task: ### Input: Subtract metabolites from a reaction. That means add the metabolites with -1*coefficient. If the final coefficient for a metabolite is 0 then the metabolite is removed from the reaction. Notes ----- * ...
def create_str(help_string=NO_HELP, default=NO_DEFAULT): # type: (str, Union[str, NO_DEFAULT_TYPE]) -> str """ Create a string parameter :param help_string: :param default: :return: """ # noinspection PyTypeChecker return ParamFunctions( ...
Create a string parameter :param help_string: :param default: :return:
Below is the the instruction that describes the task: ### Input: Create a string parameter :param help_string: :param default: :return: ### Response: def create_str(help_string=NO_HELP, default=NO_DEFAULT): # type: (str, Union[str, NO_DEFAULT_TYPE]) -> str """ Create...
def call_only_once(func): """ Decorate a method or property of a class, so that this method can only be called once for every instance. Calling it more than once will result in exception. """ @functools.wraps(func) def wrapper(*args, **kwargs): self = args[0] # cannot use has...
Decorate a method or property of a class, so that this method can only be called once for every instance. Calling it more than once will result in exception.
Below is the the instruction that describes the task: ### Input: Decorate a method or property of a class, so that this method can only be called once for every instance. Calling it more than once will result in exception. ### Response: def call_only_once(func): """ Decorate a method or property of...
def kernels_initialize(self, folder): """ create a new kernel in a specified folder from template, including json metadata that grabs values from the configuration. Parameters ========== folder: the path of the folder """ if not os.path.isdir(fold...
create a new kernel in a specified folder from template, including json metadata that grabs values from the configuration. Parameters ========== folder: the path of the folder
Below is the the instruction that describes the task: ### Input: create a new kernel in a specified folder from template, including json metadata that grabs values from the configuration. Parameters ========== folder: the path of the folder ### Response: def kernels...
def close(self): """The close operation loads the session if it is valid and then closes it and releases the session seat. All the session data are deleted and become invalid after the request is processed. The session ID can no longer be used in subsequent requests.""" if self._...
The close operation loads the session if it is valid and then closes it and releases the session seat. All the session data are deleted and become invalid after the request is processed. The session ID can no longer be used in subsequent requests.
Below is the the instruction that describes the task: ### Input: The close operation loads the session if it is valid and then closes it and releases the session seat. All the session data are deleted and become invalid after the request is processed. The session ID can no longer be used in ...
def is_purrlog(path): """Checks if path refers to a valid purrlog. Path must exist, and must contain either at least one directory called entry-YYYYMMDD-HHMMSS, or the file "dirconfig" """ if not os.path.isdir(path): return False if list(filter(os.path.isdir, glob.glo...
Checks if path refers to a valid purrlog. Path must exist, and must contain either at least one directory called entry-YYYYMMDD-HHMMSS, or the file "dirconfig"
Below is the the instruction that describes the task: ### Input: Checks if path refers to a valid purrlog. Path must exist, and must contain either at least one directory called entry-YYYYMMDD-HHMMSS, or the file "dirconfig" ### Response: def is_purrlog(path): """Checks if path refers to a valid pu...
def retrain(self): """Train for a session, pulling in any new data from the filesystem""" folder = TrainData.from_folder(self.args.folder) train_data, test_data = folder.load(True, not self.args.no_validation) train_data = TrainData.merge(train_data, self.sampled_data) test_data...
Train for a session, pulling in any new data from the filesystem
Below is the the instruction that describes the task: ### Input: Train for a session, pulling in any new data from the filesystem ### Response: def retrain(self): """Train for a session, pulling in any new data from the filesystem""" folder = TrainData.from_folder(self.args.folder) train_da...
def describe_field(k, v, timestamp_parser=default_timestamp_parser): """Given a key representing a column name and value representing the value stored in the column, return a representation of the BigQuery schema element describing that field. Raise errors if invalid value types are provided. Param...
Given a key representing a column name and value representing the value stored in the column, return a representation of the BigQuery schema element describing that field. Raise errors if invalid value types are provided. Parameters ---------- k : Union[str, unicode] Key representing th...
Below is the the instruction that describes the task: ### Input: Given a key representing a column name and value representing the value stored in the column, return a representation of the BigQuery schema element describing that field. Raise errors if invalid value types are provided. Parameters ...
def is_prime( n ): """Return True if x is prime, False otherwise. We use the Miller-Rabin test, as given in Menezes et al. p. 138. This test is not exact: there are composite values n for which it returns True. In testing the odd numbers from 10000001 to 19999999, about 66 composites got past the first te...
Return True if x is prime, False otherwise. We use the Miller-Rabin test, as given in Menezes et al. p. 138. This test is not exact: there are composite values n for which it returns True. In testing the odd numbers from 10000001 to 19999999, about 66 composites got past the first test, 5 got past the sec...
Below is the the instruction that describes the task: ### Input: Return True if x is prime, False otherwise. We use the Miller-Rabin test, as given in Menezes et al. p. 138. This test is not exact: there are composite values n for which it returns True. In testing the odd numbers from 10000001 to 19999999...
def view_all_work_queues(): """Page for viewing the index of all active work queues.""" count_list = list( db.session.query( work_queue.WorkQueue.queue_name, work_queue.WorkQueue.status, func.count(work_queue.WorkQueue.task_id)) .group_by(work_queue.WorkQueue....
Page for viewing the index of all active work queues.
Below is the the instruction that describes the task: ### Input: Page for viewing the index of all active work queues. ### Response: def view_all_work_queues(): """Page for viewing the index of all active work queues.""" count_list = list( db.session.query( work_queue.WorkQueue.queue_na...
def _set_rho_grids(self): """ Set the grids and weights for rho used in numerical integration of AR(1) parameters. """ rho_grids = np.arange(self.rho_bins) * 2 / self.rho_bins - 1 \ + 1 / self.rho_bins rho_weights = np.ones(self.rho_bins) / self.rho_bins r...
Set the grids and weights for rho used in numerical integration of AR(1) parameters.
Below is the the instruction that describes the task: ### Input: Set the grids and weights for rho used in numerical integration of AR(1) parameters. ### Response: def _set_rho_grids(self): """ Set the grids and weights for rho used in numerical integration of AR(1) parameters. ...
def _maybe_download_corpora(tmp_dir): """Download corpora for multinli. Args: tmp_dir: a string Returns: a string """ mnli_filename = "MNLI.zip" mnli_finalpath = os.path.join(tmp_dir, "MNLI") if not tf.gfile.Exists(mnli_finalpath): zip_filepath = generator_utils.maybe_download( tmp_di...
Download corpora for multinli. Args: tmp_dir: a string Returns: a string
Below is the the instruction that describes the task: ### Input: Download corpora for multinli. Args: tmp_dir: a string Returns: a string ### Response: def _maybe_download_corpora(tmp_dir): """Download corpora for multinli. Args: tmp_dir: a string Returns: a string """ mnli_filename...
def get_grade_entry_form_for_update(self, grade_entry_id): """Gets the grade entry form for updating an existing entry. A new grade entry form should be requested for each update transaction. arg: grade_entry_id (osid.id.Id): the ``Id`` of the ``GradeEntry`` ...
Gets the grade entry form for updating an existing entry. A new grade entry form should be requested for each update transaction. arg: grade_entry_id (osid.id.Id): the ``Id`` of the ``GradeEntry`` return: (osid.grading.GradeEntryForm) - the grade entry form r...
Below is the the instruction that describes the task: ### Input: Gets the grade entry form for updating an existing entry. A new grade entry form should be requested for each update transaction. arg: grade_entry_id (osid.id.Id): the ``Id`` of the ``GradeEntry`` r...
def perc(arr, p=95, **kwargs): """Create symmetric percentiles, with ``p`` coverage.""" offset = (100 - p) / 2 return np.percentile(arr, (offset, 100 - offset), **kwargs)
Create symmetric percentiles, with ``p`` coverage.
Below is the the instruction that describes the task: ### Input: Create symmetric percentiles, with ``p`` coverage. ### Response: def perc(arr, p=95, **kwargs): """Create symmetric percentiles, with ``p`` coverage.""" offset = (100 - p) / 2 return np.percentile(arr, (offset, 100 - offset), **kwargs)
def close(self): """close(self)""" if self.isClosed: raise ValueError("operation illegal for closed doc") if hasattr(self, '_outline') and self._outline: self._dropOutline(self._outline) self._outline = None self._reset_page_refs() self.metada...
close(self)
Below is the the instruction that describes the task: ### Input: close(self) ### Response: def close(self): """close(self)""" if self.isClosed: raise ValueError("operation illegal for closed doc") if hasattr(self, '_outline') and self._outline: self._dropOutline(sel...
def create_cache(directory, compress_level=6, value_type_is_binary=False, **kwargs): """ Create a html cache. Html string will be automatically compressed. :param directory: path for the cache directory. :param compress_level: 0 ~ 9, 9 is slowest and smallest. :param kwargs: other arguments. :r...
Create a html cache. Html string will be automatically compressed. :param directory: path for the cache directory. :param compress_level: 0 ~ 9, 9 is slowest and smallest. :param kwargs: other arguments. :return: a `diskcache.Cache()`
Below is the the instruction that describes the task: ### Input: Create a html cache. Html string will be automatically compressed. :param directory: path for the cache directory. :param compress_level: 0 ~ 9, 9 is slowest and smallest. :param kwargs: other arguments. :return: a `diskcache.Cache()`...
def plotnoise(noisepkl, mergepkl, plot_width=950, plot_height=400): """ Make two panel plot to summary noise analysis with estimated flux scale """ d = pickle.load(open(mergepkl)) ndist, imstd, flagfrac = plotnoisedist(noisepkl, plot_width=plot_width/2, plot_height=plot_height) fluxscale = calcfluxscal...
Make two panel plot to summary noise analysis with estimated flux scale
Below is the the instruction that describes the task: ### Input: Make two panel plot to summary noise analysis with estimated flux scale ### Response: def plotnoise(noisepkl, mergepkl, plot_width=950, plot_height=400): """ Make two panel plot to summary noise analysis with estimated flux scale """ d = pic...
def readTable(self, tableName): """ Read the table corresponding to the specified name, equivalent to the AMPL statement: .. code-block:: ampl read table tableName; Args: tableName: Name of the table to be read. """ lock_and_call( ...
Read the table corresponding to the specified name, equivalent to the AMPL statement: .. code-block:: ampl read table tableName; Args: tableName: Name of the table to be read.
Below is the the instruction that describes the task: ### Input: Read the table corresponding to the specified name, equivalent to the AMPL statement: .. code-block:: ampl read table tableName; Args: tableName: Name of the table to be read. ### Response: def readT...
def batching_scheme(batch_size, max_length, min_length_bucket, length_bucket_step, drop_long_sequences=False, shard_multiplier=1, length_multiplier=1, min_length=0): """A batchin...
A batching scheme based on model hyperparameters. Every batch contains a number of sequences divisible by `shard_multiplier`. Args: batch_size: int, total number of tokens in a batch. max_length: int, sequences longer than this will be skipped. Defaults to batch_size. min_length_bucket: int ...
Below is the the instruction that describes the task: ### Input: A batching scheme based on model hyperparameters. Every batch contains a number of sequences divisible by `shard_multiplier`. Args: batch_size: int, total number of tokens in a batch. max_length: int, sequences longer than this will be s...
def fixpath(path): """Uniformly format a path.""" return os.path.normpath(os.path.realpath(os.path.expanduser(path)))
Uniformly format a path.
Below is the the instruction that describes the task: ### Input: Uniformly format a path. ### Response: def fixpath(path): """Uniformly format a path.""" return os.path.normpath(os.path.realpath(os.path.expanduser(path)))
def _create_cpe_parts(self, system, components): """ Create the structure to store the input type of system associated with components of CPE Name (hardware, operating system and software). :param string system: type of system associated with CPE Name :param dict components: CPE...
Create the structure to store the input type of system associated with components of CPE Name (hardware, operating system and software). :param string system: type of system associated with CPE Name :param dict components: CPE Name components to store :returns: None :exception: ...
Below is the the instruction that describes the task: ### Input: Create the structure to store the input type of system associated with components of CPE Name (hardware, operating system and software). :param string system: type of system associated with CPE Name :param dict components: CPE...
def equal(self, value_a, value_b): #pylint: disable=no-self-use """Check if two valid Property values are equal .. note:: This method assumes that :code:`None` and :code:`properties.undefined` are never passed in as values """ ...
Check if two valid Property values are equal .. note:: This method assumes that :code:`None` and :code:`properties.undefined` are never passed in as values
Below is the the instruction that describes the task: ### Input: Check if two valid Property values are equal .. note:: This method assumes that :code:`None` and :code:`properties.undefined` are never passed in as values ### Response: def equal(self, value_a, value_b): ...
def add_entry(self, row): """This will parse the VCF entry and also store it within the VCFFile. It will also return the VCFEntry as well. """ var_call = VCFEntry(self.individuals) var_call.parse_entry( row ) self.entries[(var_call.chrom, var_call.pos)] = var_call ...
This will parse the VCF entry and also store it within the VCFFile. It will also return the VCFEntry as well.
Below is the the instruction that describes the task: ### Input: This will parse the VCF entry and also store it within the VCFFile. It will also return the VCFEntry as well. ### Response: def add_entry(self, row): """This will parse the VCF entry and also store it within the VCFFile. It will also ...
def queries(self, rcSuffix='', rcNeeded=False, padChar='-', queryInsertionChar='N', unknownQualityChar='!', allowDuplicateIds=False, addAlignment=False): """ Produce padded (with gaps) queries according to the CIGAR string and reference sequence length for each ma...
Produce padded (with gaps) queries according to the CIGAR string and reference sequence length for each matching query sequence. @param rcSuffix: A C{str} to add to the end of query names that are reverse complemented. This is added before the /1, /2, etc., that are added for du...
Below is the the instruction that describes the task: ### Input: Produce padded (with gaps) queries according to the CIGAR string and reference sequence length for each matching query sequence. @param rcSuffix: A C{str} to add to the end of query names that are reverse complemented. Thi...
def build_time(start_time): """ Calculate build time per package """ diff_time = round(time.time() - start_time, 2) if diff_time <= 59.99: sum_time = str(diff_time) + " Sec" elif diff_time > 59.99 and diff_time <= 3599.99: sum_time = round(diff_time / 60, 2) sum_time_list...
Calculate build time per package
Below is the the instruction that describes the task: ### Input: Calculate build time per package ### Response: def build_time(start_time): """ Calculate build time per package """ diff_time = round(time.time() - start_time, 2) if diff_time <= 59.99: sum_time = str(diff_time) + " Sec" ...
def any(pred: Callable, xs: Iterable): """ Check if at least one element of the iterable `xs` fullfills predicate `pred`. :param pred: predicate function. :param xs: iterable object. :returns: boolean """ b = find_first(pred, xs) return True if b is not None else Fals...
Check if at least one element of the iterable `xs` fullfills predicate `pred`. :param pred: predicate function. :param xs: iterable object. :returns: boolean
Below is the the instruction that describes the task: ### Input: Check if at least one element of the iterable `xs` fullfills predicate `pred`. :param pred: predicate function. :param xs: iterable object. :returns: boolean ### Response: def any(pred: Callable, xs: Iterable): """ ...
def Solver_CMFR_N(t_data, C_data, theta_guess, C_bar_guess): """Use non-linear least squares to fit the function Tracer_CMFR_N(t_seconds, t_bar, C_bar, N) to reactor data. :param t_data: Array of times with units :type t_data: float list :param C_data: Array of tracer concentration data with units ...
Use non-linear least squares to fit the function Tracer_CMFR_N(t_seconds, t_bar, C_bar, N) to reactor data. :param t_data: Array of times with units :type t_data: float list :param C_data: Array of tracer concentration data with units :type C_data: float list :param theta_guess: Estimate of tim...
Below is the the instruction that describes the task: ### Input: Use non-linear least squares to fit the function Tracer_CMFR_N(t_seconds, t_bar, C_bar, N) to reactor data. :param t_data: Array of times with units :type t_data: float list :param C_data: Array of tracer concentration data with units...
def plot_high_levels_data(self): """ Complicated function that draws the high level mean plot on canvas4, draws all specimen, sample, or site interpretations according to the UPPER_LEVEL_SHOW variable, draws the fisher mean or fisher mean by polarity of all interpretations displa...
Complicated function that draws the high level mean plot on canvas4, draws all specimen, sample, or site interpretations according to the UPPER_LEVEL_SHOW variable, draws the fisher mean or fisher mean by polarity of all interpretations displayed, draws sample orientation check if on, an...
Below is the the instruction that describes the task: ### Input: Complicated function that draws the high level mean plot on canvas4, draws all specimen, sample, or site interpretations according to the UPPER_LEVEL_SHOW variable, draws the fisher mean or fisher mean by polarity of all interp...
def _orientation_ok_to_bridge_contigs(self, start_hit, end_hit): '''Returns True iff the orientation of the hits means that the query contig of both hits can bridge the reference contigs of the hits''' assert start_hit.qry_name == end_hit.qry_name if start_hit.ref_name == end_hit.ref_name: ...
Returns True iff the orientation of the hits means that the query contig of both hits can bridge the reference contigs of the hits
Below is the the instruction that describes the task: ### Input: Returns True iff the orientation of the hits means that the query contig of both hits can bridge the reference contigs of the hits ### Response: def _orientation_ok_to_bridge_contigs(self, start_hit, end_hit): '''Returns True iff the orientat...
def find_previous_sibling(self, *args, **kwargs): """ Like :meth:`find`, but searches through :attr:`previous_siblings` """ op = operator.methodcaller('find_previous_sibling', *args, **kwargs) return self._wrap_node(op)
Like :meth:`find`, but searches through :attr:`previous_siblings`
Below is the the instruction that describes the task: ### Input: Like :meth:`find`, but searches through :attr:`previous_siblings` ### Response: def find_previous_sibling(self, *args, **kwargs): """ Like :meth:`find`, but searches through :attr:`previous_siblings` """ op = operator....
def table_mask(self): """ndarray, True where table margin <= min_base_size, same shape as slice.""" margin = compress_pruned( self._slice.margin( axis=None, weighted=False, include_transforms_for_dims=self._hs_dims, prune=self._...
ndarray, True where table margin <= min_base_size, same shape as slice.
Below is the the instruction that describes the task: ### Input: ndarray, True where table margin <= min_base_size, same shape as slice. ### Response: def table_mask(self): """ndarray, True where table margin <= min_base_size, same shape as slice.""" margin = compress_pruned( self._slic...
def _opposite_axis_margin(self): """ndarray representing margin along the axis opposite of self._axis In the process of calculating p-values for the column significance testing we need both the margin along the primary axis and the percentage margin along the opposite axis. """ ...
ndarray representing margin along the axis opposite of self._axis In the process of calculating p-values for the column significance testing we need both the margin along the primary axis and the percentage margin along the opposite axis.
Below is the the instruction that describes the task: ### Input: ndarray representing margin along the axis opposite of self._axis In the process of calculating p-values for the column significance testing we need both the margin along the primary axis and the percentage margin along the op...
def parse_nni_function(code): """Parse `nni.function_choice` expression. Return the AST node of annotated expression and a list of dumped function call expressions. code: annotation string """ name, call = parse_annotation_function(code, 'function_choice') funcs = [ast.dump(func, False) for func...
Parse `nni.function_choice` expression. Return the AST node of annotated expression and a list of dumped function call expressions. code: annotation string
Below is the the instruction that describes the task: ### Input: Parse `nni.function_choice` expression. Return the AST node of annotated expression and a list of dumped function call expressions. code: annotation string ### Response: def parse_nni_function(code): """Parse `nni.function_choice` express...
def set_volume(self, pct, channel=None): """ Sets the sound volume to the given percentage [0-100] by calling ``amixer -q set <channel> <pct>%``. If the channel is not specified, it tries to determine the default one by running ``amixer scontrols``. If that fails as well, it uses...
Sets the sound volume to the given percentage [0-100] by calling ``amixer -q set <channel> <pct>%``. If the channel is not specified, it tries to determine the default one by running ``amixer scontrols``. If that fails as well, it uses the ``Playback`` channel, as that is the only channe...
Below is the the instruction that describes the task: ### Input: Sets the sound volume to the given percentage [0-100] by calling ``amixer -q set <channel> <pct>%``. If the channel is not specified, it tries to determine the default one by running ``amixer scontrols``. If that fails as well,...
def connect(self): ''' Registers a new device + username with the bridge ''' # Don't try to register if we already have if self.validate_registration(): return True body = { 'devicetype': self.device_type, 'username': self.username, ...
Registers a new device + username with the bridge
Below is the the instruction that describes the task: ### Input: Registers a new device + username with the bridge ### Response: def connect(self): ''' Registers a new device + username with the bridge ''' # Don't try to register if we already have if self.validate_registrat...
def sparsify_rows(x, quantile=0.01): ''' Return a row-sparse matrix approximating the input `x`. Parameters ---------- x : np.ndarray [ndim <= 2] The input matrix to sparsify. quantile : float in [0, 1.0) Percentage of magnitude to discard in each row of `x` Returns --...
Return a row-sparse matrix approximating the input `x`. Parameters ---------- x : np.ndarray [ndim <= 2] The input matrix to sparsify. quantile : float in [0, 1.0) Percentage of magnitude to discard in each row of `x` Returns ------- x_sparse : `scipy.sparse.csr_matrix` [s...
Below is the the instruction that describes the task: ### Input: Return a row-sparse matrix approximating the input `x`. Parameters ---------- x : np.ndarray [ndim <= 2] The input matrix to sparsify. quantile : float in [0, 1.0) Percentage of magnitude to discard in each row of `x`...
def get_access_token_from_code( self, code, redirect_uri, app_id, app_secret ): """Get an access token from the "code" returned from an OAuth dialog. Returns a dict containing the user-specific access token and its expiration date (if applicable). """ args = { ...
Get an access token from the "code" returned from an OAuth dialog. Returns a dict containing the user-specific access token and its expiration date (if applicable).
Below is the the instruction that describes the task: ### Input: Get an access token from the "code" returned from an OAuth dialog. Returns a dict containing the user-specific access token and its expiration date (if applicable). ### Response: def get_access_token_from_code( self, code, re...
def entry_point(__func: Callable) -> Callable: """Execute function when module is run directly. Note: This allows fall through for importing modules that use it. Args: __func: Function to run """ if __func.__module__ == '__main__': import sys sys.exit(__func()) ...
Execute function when module is run directly. Note: This allows fall through for importing modules that use it. Args: __func: Function to run
Below is the the instruction that describes the task: ### Input: Execute function when module is run directly. Note: This allows fall through for importing modules that use it. Args: __func: Function to run ### Response: def entry_point(__func: Callable) -> Callable: """Execute functi...
def build_duration(self): """Return the difference between build and build_done states""" return int(self.state.build_done) - int(self.state.build)
Return the difference between build and build_done states
Below is the the instruction that describes the task: ### Input: Return the difference between build and build_done states ### Response: def build_duration(self): """Return the difference between build and build_done states""" return int(self.state.build_done) - int(self.state.build)
def set_default_format_options(self, format_options, read=False): """Set default format option""" if self.default_notebook_metadata_filter: format_options.setdefault('notebook_metadata_filter', self.default_notebook_metadata_filter) if self.default_cell_metadata_filter: f...
Set default format option
Below is the the instruction that describes the task: ### Input: Set default format option ### Response: def set_default_format_options(self, format_options, read=False): """Set default format option""" if self.default_notebook_metadata_filter: format_options.setdefault('notebook_metada...
def suggest(q='', results=15, buckets=None, limit=False, max_familiarity=None, min_familiarity=None, max_hotttnesss=None, min_hotttnesss=None): """Suggest artists based upon partial names. Args: Kwargs: q (str): The text to suggest artists from results (int): An integer nu...
Suggest artists based upon partial names. Args: Kwargs: q (str): The text to suggest artists from results (int): An integer number of results to return buckets (list): A list of strings specifying which buckets to retrieve limit (bool): A boolean indicating whether or not to...
Below is the the instruction that describes the task: ### Input: Suggest artists based upon partial names. Args: Kwargs: q (str): The text to suggest artists from results (int): An integer number of results to return buckets (list): A list of strings specifying which buckets to r...
def annotation_rows(prefix, annotations): """ Helper function to extract N: and C: rows from annotations and pad their values """ ncol = len(annotations['Column Name']) return {name.replace(prefix, '', 1) : values + [''] * (ncol - len(values)) for name, values in annotations.items() if n...
Helper function to extract N: and C: rows from annotations and pad their values
Below is the the instruction that describes the task: ### Input: Helper function to extract N: and C: rows from annotations and pad their values ### Response: def annotation_rows(prefix, annotations): """ Helper function to extract N: and C: rows from annotations and pad their values """ ncol = len...
def reply_ok(self): """Return True if this is a reply and its first argument is 'ok'.""" return (self.mtype == self.REPLY and self.arguments and self.arguments[0] == self.OK)
Return True if this is a reply and its first argument is 'ok'.
Below is the the instruction that describes the task: ### Input: Return True if this is a reply and its first argument is 'ok'. ### Response: def reply_ok(self): """Return True if this is a reply and its first argument is 'ok'.""" return (self.mtype == self.REPLY and self.arguments and ...
def mark(self): '''Mark the line and column information of the result of this parser.''' def pos(text, index): return ParseError.loc_info(text, index) @Parser def mark_parser(text, index): res = self(text, index) if res.status: return ...
Mark the line and column information of the result of this parser.
Below is the the instruction that describes the task: ### Input: Mark the line and column information of the result of this parser. ### Response: def mark(self): '''Mark the line and column information of the result of this parser.''' def pos(text, index): return ParseError.loc_info(tex...
def sample(self, withReplacement=None, fraction=None, seed=None): """Returns a sampled subset of this :class:`DataFrame`. :param withReplacement: Sample with replacement or not (default False). :param fraction: Fraction of rows to generate, range [0.0, 1.0]. :param seed: Seed for sampli...
Returns a sampled subset of this :class:`DataFrame`. :param withReplacement: Sample with replacement or not (default False). :param fraction: Fraction of rows to generate, range [0.0, 1.0]. :param seed: Seed for sampling (default a random seed). .. note:: This is not guaranteed to prov...
Below is the the instruction that describes the task: ### Input: Returns a sampled subset of this :class:`DataFrame`. :param withReplacement: Sample with replacement or not (default False). :param fraction: Fraction of rows to generate, range [0.0, 1.0]. :param seed: Seed for sampling (defa...