code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def filter_pem(data): '''Processes the bytes for PEM certificates. Returns: ``set`` containing each certificate ''' assert isinstance(data, bytes), 'Expect bytes. Got {}.'.format(type(data)) certs = set() new_list = [] in_pem_block = False for line in re.split(br'[\r\n]+', data...
Processes the bytes for PEM certificates. Returns: ``set`` containing each certificate
Below is the the instruction that describes the task: ### Input: Processes the bytes for PEM certificates. Returns: ``set`` containing each certificate ### Response: def filter_pem(data): '''Processes the bytes for PEM certificates. Returns: ``set`` containing each certificate '''...
def vlink(s_expnum, s_ccd, s_version, s_ext, l_expnum, l_ccd, l_version, l_ext, s_prefix=None, l_prefix=None): """make a link between two version of a file. @param s_expnum: @param s_ccd: @param s_version: @param s_ext: @param l_expnum: @param l_ccd: @param l_version: @par...
make a link between two version of a file. @param s_expnum: @param s_ccd: @param s_version: @param s_ext: @param l_expnum: @param l_ccd: @param l_version: @param l_ext: @param s_prefix: @param l_prefix: @return:
Below is the the instruction that describes the task: ### Input: make a link between two version of a file. @param s_expnum: @param s_ccd: @param s_version: @param s_ext: @param l_expnum: @param l_ccd: @param l_version: @param l_ext: @param s_prefix: @param l_prefix: @re...
def handleStatus(self, version, status, message): """Save the status code for processing when we get to the end of the headers.""" self.status = status self.message = message
Save the status code for processing when we get to the end of the headers.
Below is the the instruction that describes the task: ### Input: Save the status code for processing when we get to the end of the headers. ### Response: def handleStatus(self, version, status, message): """Save the status code for processing when we get to the end of the headers.""" ...
def sg_aconv1d(tensor, opt): r"""Applies 1-D atrous (or dilated) convolution. Args: tensor: A 3-D `Tensor` (automatically passed by decorator). opt: causal: Boolean. If True, zeros are padded before the time axis such that each activation unit doesn't have receptive neurons be...
r"""Applies 1-D atrous (or dilated) convolution. Args: tensor: A 3-D `Tensor` (automatically passed by decorator). opt: causal: Boolean. If True, zeros are padded before the time axis such that each activation unit doesn't have receptive neurons beyond the equivalent time step. ...
Below is the the instruction that describes the task: ### Input: r"""Applies 1-D atrous (or dilated) convolution. Args: tensor: A 3-D `Tensor` (automatically passed by decorator). opt: causal: Boolean. If True, zeros are padded before the time axis such that each activation un...
def do_debug(self, args, arguments): """ :: Usage: debug on debug off Turns the debug log level on and off. """ filename = path_expand("~/.cloudmesh/cmd3.yaml") config = ConfigDict(filename=filename) if arguments['on']:...
:: Usage: debug on debug off Turns the debug log level on and off.
Below is the the instruction that describes the task: ### Input: :: Usage: debug on debug off Turns the debug log level on and off. ### Response: def do_debug(self, args, arguments): """ :: Usage: debug on debu...
def parse_token_kwargs(parser, token, allowed_kwargs=None, compile_args=True, compile_kwargs=True): """ Allow the template tag arguments to be like a normal Python function, with *args and **kwargs. :param parser: The "parser" object that ``@register.tag`` provides. :type parser: :class:`~django.templa...
Allow the template tag arguments to be like a normal Python function, with *args and **kwargs. :param parser: The "parser" object that ``@register.tag`` provides. :type parser: :class:`~django.template.Parser` :param token: The "token" object that ``@register.tag`` provides. :type token: :class:`~djang...
Below is the the instruction that describes the task: ### Input: Allow the template tag arguments to be like a normal Python function, with *args and **kwargs. :param parser: The "parser" object that ``@register.tag`` provides. :type parser: :class:`~django.template.Parser` :param token: The "token" ob...
def mode_assignment(arg): """ Translates arg to enforce proper assignment """ arg = arg.upper() stream_args = ('STREAM', 'CONSOLE', 'STDOUT') try: if arg in stream_args: return 'STREAM' else: return arg except Exception: return None
Translates arg to enforce proper assignment
Below is the the instruction that describes the task: ### Input: Translates arg to enforce proper assignment ### Response: def mode_assignment(arg): """ Translates arg to enforce proper assignment """ arg = arg.upper() stream_args = ('STREAM', 'CONSOLE', 'STDOUT') try: if arg in str...
def process_docstring(app, what, name, obj, options, lines): """Process the docstring for a given python object. Called when autodoc has read and processed a docstring. `lines` is a list of docstring lines that `_process_docstring` modifies in place to change what Sphinx outputs. The following set...
Process the docstring for a given python object. Called when autodoc has read and processed a docstring. `lines` is a list of docstring lines that `_process_docstring` modifies in place to change what Sphinx outputs. The following settings in conf.py control what styles of docstrings will be parse...
Below is the the instruction that describes the task: ### Input: Process the docstring for a given python object. Called when autodoc has read and processed a docstring. `lines` is a list of docstring lines that `_process_docstring` modifies in place to change what Sphinx outputs. The following se...
def add_val(self, val): """add value in form of dict""" if not isinstance(val, type({})): raise ValueError(type({})) self.read() self.config.update(val) self.save()
add value in form of dict
Below is the the instruction that describes the task: ### Input: add value in form of dict ### Response: def add_val(self, val): """add value in form of dict""" if not isinstance(val, type({})): raise ValueError(type({})) self.read() self.config.update(val) self....
def _read_source(self) -> None: """ Reads the source file. """ with open(self.full_path, "rt") as f: for linenum, line_with_nl in enumerate(f.readlines(), start=1): line_without_newline = ( line_with_nl[:-1] if line_with_nl.endswith(NL) ...
Reads the source file.
Below is the the instruction that describes the task: ### Input: Reads the source file. ### Response: def _read_source(self) -> None: """ Reads the source file. """ with open(self.full_path, "rt") as f: for linenum, line_with_nl in enumerate(f.readlines(), start=1): ...
def _get_udev_rules(self, channel_read, channel_write, channel_data): """construct udev rules info.""" sub_str = '%(read)s %%k %(read)s %(write)s %(data)s qeth' % { 'read': channel_read, 'read': channel_read, ...
construct udev rules info.
Below is the the instruction that describes the task: ### Input: construct udev rules info. ### Response: def _get_udev_rules(self, channel_read, channel_write, channel_data): """construct udev rules info.""" sub_str = '%(read)s %%k %(read)s %(write)s %(data)s qeth' % { ...
def randomChildElement(self, node): """choose a random child element of a node This is a utility method used by do_xref and do_choice. """ choices = [e for e in node.childNodes if e.nodeType == e.ELEMENT_NODE] chosen = random.choice(choices) ...
choose a random child element of a node This is a utility method used by do_xref and do_choice.
Below is the the instruction that describes the task: ### Input: choose a random child element of a node This is a utility method used by do_xref and do_choice. ### Response: def randomChildElement(self, node): """choose a random child element of a node This is a util...
def percentile(x, q, axis=None, interpolation=None, keep_dims=False, validate_args=False, preserve_gradients=True, name=None): """Compute the `q`-th percentile(s) of `x`. Given a vector `x`, the `q`-th percenti...
Compute the `q`-th percentile(s) of `x`. Given a vector `x`, the `q`-th percentile of `x` is the value `q / 100` of the way from the minimum to the maximum in a sorted copy of `x`. The values and distances of the two nearest neighbors as well as the `interpolation` parameter will determine the percentile if t...
Below is the the instruction that describes the task: ### Input: Compute the `q`-th percentile(s) of `x`. Given a vector `x`, the `q`-th percentile of `x` is the value `q / 100` of the way from the minimum to the maximum in a sorted copy of `x`. The values and distances of the two nearest neighbors as well ...
def get_next_question(self, question_id, answered=None, reverse=False, honor_sequential=True): """Inspects question map to return the next available question. if answered == False: only return next unanswered question if answered == True: only return next answered question if answered i...
Inspects question map to return the next available question. if answered == False: only return next unanswered question if answered == True: only return next answered question if answered in None: return next question whether answered or not if reverse == True: go backwards - effectivel...
Below is the the instruction that describes the task: ### Input: Inspects question map to return the next available question. if answered == False: only return next unanswered question if answered == True: only return next answered question if answered in None: return next question whether ...
def _feature_to_fields(f, jsonify=True): """ Convert feature to tuple, for faster sqlite3 import """ x = [] for k in constants._keys: v = getattr(f, k) if jsonify and (k in ('attributes', 'extra')): x.append(_jsonify(v)) else: x.append(v) return tu...
Convert feature to tuple, for faster sqlite3 import
Below is the the instruction that describes the task: ### Input: Convert feature to tuple, for faster sqlite3 import ### Response: def _feature_to_fields(f, jsonify=True): """ Convert feature to tuple, for faster sqlite3 import """ x = [] for k in constants._keys: v = getattr(f, k) ...
def fix_module(job): """ Fix for tasks without a module. Provides backwards compatibility with < 0.1.5 """ modules = settings.RQ_JOBS_MODULE if not type(modules) == tuple: modules = [modules] for module in modules: try: module_match = importlib.import_module(module) ...
Fix for tasks without a module. Provides backwards compatibility with < 0.1.5
Below is the the instruction that describes the task: ### Input: Fix for tasks without a module. Provides backwards compatibility with < 0.1.5 ### Response: def fix_module(job): """ Fix for tasks without a module. Provides backwards compatibility with < 0.1.5 """ modules = settings.RQ_JOBS_MODULE ...
def _call_one_middleware(self, middleware): ''' Evaluate arguments and execute the middleware function ''' args = {} for arg in middleware['args']: if hasattr(self, arg): # same as eval() but safer for arbitrary code execution args[arg] = reduce(getatt...
Evaluate arguments and execute the middleware function
Below is the the instruction that describes the task: ### Input: Evaluate arguments and execute the middleware function ### Response: def _call_one_middleware(self, middleware): ''' Evaluate arguments and execute the middleware function ''' args = {} for arg in middleware['args']: ...
def getTrustForJID(self, bare_jid): """ All-in-one trust information for all devices of a bare jid. The result is structured like this: { "active" : { device: int => trust_info } "inactive" : { device: int => trust_info } } where trust_info is ...
All-in-one trust information for all devices of a bare jid. The result is structured like this: { "active" : { device: int => trust_info } "inactive" : { device: int => trust_info } } where trust_info is the structure returned by getTrustForDevice.
Below is the the instruction that describes the task: ### Input: All-in-one trust information for all devices of a bare jid. The result is structured like this: { "active" : { device: int => trust_info } "inactive" : { device: int => trust_info } } where t...
def dfs(graph, func, head, reverse=None): """ DEPTH FIRST SEARCH IF func RETURNS FALSE, THEN PATH IS NO LONGER TAKEN IT'S EXPECTED func TAKES 3 ARGUMENTS node - THE CURRENT NODE IN THE path - PATH FROM head TO node graph - THE WHOLE GRAPH """ todo = deque() todo.append(head) ...
DEPTH FIRST SEARCH IF func RETURNS FALSE, THEN PATH IS NO LONGER TAKEN IT'S EXPECTED func TAKES 3 ARGUMENTS node - THE CURRENT NODE IN THE path - PATH FROM head TO node graph - THE WHOLE GRAPH
Below is the the instruction that describes the task: ### Input: DEPTH FIRST SEARCH IF func RETURNS FALSE, THEN PATH IS NO LONGER TAKEN IT'S EXPECTED func TAKES 3 ARGUMENTS node - THE CURRENT NODE IN THE path - PATH FROM head TO node graph - THE WHOLE GRAPH ### Response: def dfs(graph, func, ...
def PrintRanges(type, name, ranges): """Print the ranges as an array of type named name.""" print "static const %s %s[] = {" % (type, name,) for lo, hi in ranges: print "\t{ %d, %d }," % (lo, hi) print "};"
Print the ranges as an array of type named name.
Below is the the instruction that describes the task: ### Input: Print the ranges as an array of type named name. ### Response: def PrintRanges(type, name, ranges): """Print the ranges as an array of type named name.""" print "static const %s %s[] = {" % (type, name,) for lo, hi in ranges: print "\t{ %d,...
def nlmsg_type(self, value): """Message content setter.""" self.bytearray[self._get_slicers(1)] = bytearray(c_uint16(value or 0))
Message content setter.
Below is the the instruction that describes the task: ### Input: Message content setter. ### Response: def nlmsg_type(self, value): """Message content setter.""" self.bytearray[self._get_slicers(1)] = bytearray(c_uint16(value or 0))
def fuzz_elements(self, element): """ Fuzz all elements inside the object """ try: if type(element) == dict: tmp_element = {} for key in element: if len(self.config.parameters) > 0: if self.config.exc...
Fuzz all elements inside the object
Below is the the instruction that describes the task: ### Input: Fuzz all elements inside the object ### Response: def fuzz_elements(self, element): """ Fuzz all elements inside the object """ try: if type(element) == dict: tmp_element = {} ...
def project_data_dir(self, *args) -> str: """ Directory where to store data """ return os.path.normpath(os.path.join(self.project_dir, 'data', *args))
Directory where to store data
Below is the the instruction that describes the task: ### Input: Directory where to store data ### Response: def project_data_dir(self, *args) -> str: """ Directory where to store data """ return os.path.normpath(os.path.join(self.project_dir, 'data', *args))
def prepare(self): """When connecting start the next connection step and schedule next `prepare` call, when connected return `HandlerReady()` """ with self._lock: if self._socket: self._socket.listen(SOMAXCONN) self._socket.setblocking(False) ...
When connecting start the next connection step and schedule next `prepare` call, when connected return `HandlerReady()`
Below is the the instruction that describes the task: ### Input: When connecting start the next connection step and schedule next `prepare` call, when connected return `HandlerReady()` ### Response: def prepare(self): """When connecting start the next connection step and schedule next `prep...
def render_image1(self, rgbobj, dst_x, dst_y): """Render the image represented by (rgbobj) at dst_x, dst_y in the pixel space. NOTE: this version uses a Figure.FigImage to render the image. """ self.logger.debug("redraw surface") if self.figure is None: retur...
Render the image represented by (rgbobj) at dst_x, dst_y in the pixel space. NOTE: this version uses a Figure.FigImage to render the image.
Below is the the instruction that describes the task: ### Input: Render the image represented by (rgbobj) at dst_x, dst_y in the pixel space. NOTE: this version uses a Figure.FigImage to render the image. ### Response: def render_image1(self, rgbobj, dst_x, dst_y): """Render the image repr...
def add_pipers(self, pipers, *args, **kwargs): """ Adds a sequence of ``Pipers`` instances to the ``Dagger`` in the specified order. Takes optional arguments for ``Dagger.add_piper``. Arguments: - pipers(sequence of valid ``add_piper`` arguments) Sequence of ...
Adds a sequence of ``Pipers`` instances to the ``Dagger`` in the specified order. Takes optional arguments for ``Dagger.add_piper``. Arguments: - pipers(sequence of valid ``add_piper`` arguments) Sequence of ``Pipers`` or valid ``Dagger.add_piper`` arguments to ...
Below is the the instruction that describes the task: ### Input: Adds a sequence of ``Pipers`` instances to the ``Dagger`` in the specified order. Takes optional arguments for ``Dagger.add_piper``. Arguments: - pipers(sequence of valid ``add_piper`` arguments) Sequence o...
def force_vertical_padding_after( self, index: int, padding: Union[int, float]) -> None: """Change the padding after the given row.""" self.vertical_padding[index] = padding
Change the padding after the given row.
Below is the the instruction that describes the task: ### Input: Change the padding after the given row. ### Response: def force_vertical_padding_after( self, index: int, padding: Union[int, float]) -> None: """Change the padding after the given row.""" self.vertical_padding[index] = pa...
def members(group_id): """List user group members.""" page = request.args.get('page', 1, type=int) per_page = request.args.get('per_page', 5, type=int) q = request.args.get('q', '') s = request.args.get('s', '') group = Group.query.get_or_404(group_id) if group.can_see_members(current_user)...
List user group members.
Below is the the instruction that describes the task: ### Input: List user group members. ### Response: def members(group_id): """List user group members.""" page = request.args.get('page', 1, type=int) per_page = request.args.get('per_page', 5, type=int) q = request.args.get('q', '') s = reque...
def _get_key_values(self, name): """Return a dict containing key / values items for a given key, used for items like filters, page, etc. :param str name: name of the querystring parameter :return dict: a dict of key / values items """ results = {} for key, value in self...
Return a dict containing key / values items for a given key, used for items like filters, page, etc. :param str name: name of the querystring parameter :return dict: a dict of key / values items
Below is the the instruction that describes the task: ### Input: Return a dict containing key / values items for a given key, used for items like filters, page, etc. :param str name: name of the querystring parameter :return dict: a dict of key / values items ### Response: def _get_key_values(self...
def print_device_info(dev_name): """Prints information about the given device. Usage: print_device_info("Dev1") """ string_buffer = ctypes.create_string_buffer(1024) attributes = [pydaq.DAQmx_Dev_ProductType, pydaq.DAQmx_Dev_SerialNum, pydaq.DAQmx_Dev_AO_PhysicalChans, ...
Prints information about the given device. Usage: print_device_info("Dev1")
Below is the the instruction that describes the task: ### Input: Prints information about the given device. Usage: print_device_info("Dev1") ### Response: def print_device_info(dev_name): """Prints information about the given device. Usage: print_device_info("Dev1") """ string_buffer ...
def _compile_scalar(schema): """A scalar value. The schema can either be a value or a type. >>> _compile_scalar(int)([], 1) 1 >>> with raises(er.Invalid, 'expected float'): ... _compile_scalar(float)([], '1') Callables have >>> _compile_scalar(lambda v: float(v))([], '1') 1.0 ...
A scalar value. The schema can either be a value or a type. >>> _compile_scalar(int)([], 1) 1 >>> with raises(er.Invalid, 'expected float'): ... _compile_scalar(float)([], '1') Callables have >>> _compile_scalar(lambda v: float(v))([], '1') 1.0 As a convenience, ValueError's ar...
Below is the the instruction that describes the task: ### Input: A scalar value. The schema can either be a value or a type. >>> _compile_scalar(int)([], 1) 1 >>> with raises(er.Invalid, 'expected float'): ... _compile_scalar(float)([], '1') Callables have >>> _compile_scalar(lambda...
def write_data(self, variable_id, value, task): """ write values to the device """ variable = self._variables[variable_id] if task.property_name != '': # write the property to VariableProperty use that for later read vp = VariableProperty.objects.update_or...
write values to the device
Below is the the instruction that describes the task: ### Input: write values to the device ### Response: def write_data(self, variable_id, value, task): """ write values to the device """ variable = self._variables[variable_id] if task.property_name != '': # wri...
def is_all_field_none(self): """ :rtype: bool """ if self._id_ is not None: return False if self._created is not None: return False if self._updated is not None: return False if self._time_responded is not None: ...
:rtype: bool
Below is the the instruction that describes the task: ### Input: :rtype: bool ### Response: def is_all_field_none(self): """ :rtype: bool """ if self._id_ is not None: return False if self._created is not None: return False if self._updated...
async def call(self, method, **params): """ Call an Slack Web API method :param method: Slack Web API method to call :param params: {str: object} parameters to method :return: dict() """ url = self.SLACK_RPC_PREFIX + method data = FormData() data....
Call an Slack Web API method :param method: Slack Web API method to call :param params: {str: object} parameters to method :return: dict()
Below is the the instruction that describes the task: ### Input: Call an Slack Web API method :param method: Slack Web API method to call :param params: {str: object} parameters to method :return: dict() ### Response: async def call(self, method, **params): """ Call an Slac...
def binary_back_substitute(W: np.ndarray, s: np.ndarray) -> np.ndarray: """ Perform back substitution on a binary system of equations, i.e. it performs Gauss elimination over the field :math:`GF(2)`. It finds an :math:`\\mathbf{x}` such that :math:`\\mathbf{\\mathit{W}}\\mathbf{x}=\\mathbf{s}`, where al...
Perform back substitution on a binary system of equations, i.e. it performs Gauss elimination over the field :math:`GF(2)`. It finds an :math:`\\mathbf{x}` such that :math:`\\mathbf{\\mathit{W}}\\mathbf{x}=\\mathbf{s}`, where all arithmetic is taken bitwise and modulo 2. :param W: A square :math:`n\\ti...
Below is the the instruction that describes the task: ### Input: Perform back substitution on a binary system of equations, i.e. it performs Gauss elimination over the field :math:`GF(2)`. It finds an :math:`\\mathbf{x}` such that :math:`\\mathbf{\\mathit{W}}\\mathbf{x}=\\mathbf{s}`, where all arithmetic is...
def write_response_html_to_file(response,filename): """ An aid in troubleshooting internal application errors, i.e. <Response [500]>, to be mainly beneficial when developing the server-side API. This method will write the response HTML for viewing the error details in the browesr. ...
An aid in troubleshooting internal application errors, i.e. <Response [500]>, to be mainly beneficial when developing the server-side API. This method will write the response HTML for viewing the error details in the browesr. Args: response: `requests.models.Response` instance. ...
Below is the the instruction that describes the task: ### Input: An aid in troubleshooting internal application errors, i.e. <Response [500]>, to be mainly beneficial when developing the server-side API. This method will write the response HTML for viewing the error details in the browesr. ...
def writefile(filename, content): """ writes the content into the file :param filename: the filename :param content: teh content :return: """ with open(path_expand(filename), 'w') as outfile: outfile.write(content)
writes the content into the file :param filename: the filename :param content: teh content :return:
Below is the the instruction that describes the task: ### Input: writes the content into the file :param filename: the filename :param content: teh content :return: ### Response: def writefile(filename, content): """ writes the content into the file :param filename: the filename :param ...
def median(self, **kwargs): """ Compute median of groups, excluding missing values. For multiple groupings, the result index will be a MultiIndex """ try: return self._cython_agg_general('median', **kwargs) except GroupByError: raise excep...
Compute median of groups, excluding missing values. For multiple groupings, the result index will be a MultiIndex
Below is the the instruction that describes the task: ### Input: Compute median of groups, excluding missing values. For multiple groupings, the result index will be a MultiIndex ### Response: def median(self, **kwargs): """ Compute median of groups, excluding missing values. For ...
def _add_task(self, *args, **kwargs): """ Call ``self._scheduler.add_task``, but store the values too so we can implement :py:func:`luigi.execution_summary.summary`. """ task_id = kwargs['task_id'] status = kwargs['status'] runnable = kwargs['runnable'] ta...
Call ``self._scheduler.add_task``, but store the values too so we can implement :py:func:`luigi.execution_summary.summary`.
Below is the the instruction that describes the task: ### Input: Call ``self._scheduler.add_task``, but store the values too so we can implement :py:func:`luigi.execution_summary.summary`. ### Response: def _add_task(self, *args, **kwargs): """ Call ``self._scheduler.add_task``, but store t...
def omim_terms(case_obj): """Extract all OMIM phenotypes available for the case Args: case_obj(dict): a scout case object Returns: disorders(list): a list of OMIM disorder objects """ LOG.info("Collecting OMIM disorders for case {}".format(case_obj.get('display_name'))) disorders...
Extract all OMIM phenotypes available for the case Args: case_obj(dict): a scout case object Returns: disorders(list): a list of OMIM disorder objects
Below is the the instruction that describes the task: ### Input: Extract all OMIM phenotypes available for the case Args: case_obj(dict): a scout case object Returns: disorders(list): a list of OMIM disorder objects ### Response: def omim_terms(case_obj): """Extract all OMIM phenotypes ...
def pubkey(self, identity, ecdh=False): """Return public key.""" _verify_support(identity, ecdh) return trezor.Trezor.pubkey(self, identity=identity, ecdh=ecdh)
Return public key.
Below is the the instruction that describes the task: ### Input: Return public key. ### Response: def pubkey(self, identity, ecdh=False): """Return public key.""" _verify_support(identity, ecdh) return trezor.Trezor.pubkey(self, identity=identity, ecdh=ecdh)
def options(self, parser, env=os.environ): """Handle parsing additional command-line options""" super(PerfDumpPlugin, self).options(parser, env=env) parser.add_option("", "--perfdump-html", dest="perfdump_html_file", help="Set destination for HTML report output")
Handle parsing additional command-line options
Below is the the instruction that describes the task: ### Input: Handle parsing additional command-line options ### Response: def options(self, parser, env=os.environ): """Handle parsing additional command-line options""" super(PerfDumpPlugin, self).options(parser, env=env) parser.add_optio...
def toStringArray(name, a, width = 0): """ Returns an array (any sequence of floats, really) as a string. """ string = name + ": " cnt = 0 for i in a: string += "%4.2f " % i if width > 0 and (cnt + 1) % width == 0: string += '\n' cnt += 1 return string
Returns an array (any sequence of floats, really) as a string.
Below is the the instruction that describes the task: ### Input: Returns an array (any sequence of floats, really) as a string. ### Response: def toStringArray(name, a, width = 0): """ Returns an array (any sequence of floats, really) as a string. """ string = name + ": " cnt = 0 for i in a...
def append_varint32(self, value): """Appends a signed 32-bit integer to the internal buffer, encoded as a varint. (Note that a negative varint32 will always require 10 bytes of space.) """ if not wire_format.INT32_MIN <= value <= wire_format.INT32_MAX: raise errors.E...
Appends a signed 32-bit integer to the internal buffer, encoded as a varint. (Note that a negative varint32 will always require 10 bytes of space.)
Below is the the instruction that describes the task: ### Input: Appends a signed 32-bit integer to the internal buffer, encoded as a varint. (Note that a negative varint32 will always require 10 bytes of space.) ### Response: def append_varint32(self, value): """Appends a signed 32-bit in...
def trace_graph(graph): """Build a collection of "traces" for each package. A trace is a list of names that eventually leads to the package. For example, if A and B are root dependencies, A depends on C and D, B depends on C, and C depends on D, the return value would be like:: { N...
Build a collection of "traces" for each package. A trace is a list of names that eventually leads to the package. For example, if A and B are root dependencies, A depends on C and D, B depends on C, and C depends on D, the return value would be like:: { None: [], "A": [None...
Below is the the instruction that describes the task: ### Input: Build a collection of "traces" for each package. A trace is a list of names that eventually leads to the package. For example, if A and B are root dependencies, A depends on C and D, B depends on C, and C depends on D, the return value wo...
def apk(actual, predicted, k=10): """ Computes the average precision at k. This function computes the average prescision at k between two lists of items. Parameters ---------- actual : list A list of elements that are to be predicted (order doesn't matter) predicted : list...
Computes the average precision at k. This function computes the average prescision at k between two lists of items. Parameters ---------- actual : list A list of elements that are to be predicted (order doesn't matter) predicted : list A list of predicted elements ...
Below is the the instruction that describes the task: ### Input: Computes the average precision at k. This function computes the average prescision at k between two lists of items. Parameters ---------- actual : list A list of elements that are to be predicted (order doesn't matte...
def random_state(state=None): """ Helper function for processing random_state arguments. Parameters ---------- state : int, np.random.RandomState, None. If receives an int, passes to np.random.RandomState() as seed. If receives an np.random.RandomState object, just returns object. ...
Helper function for processing random_state arguments. Parameters ---------- state : int, np.random.RandomState, None. If receives an int, passes to np.random.RandomState() as seed. If receives an np.random.RandomState object, just returns object. If receives `None`, returns np.rand...
Below is the the instruction that describes the task: ### Input: Helper function for processing random_state arguments. Parameters ---------- state : int, np.random.RandomState, None. If receives an int, passes to np.random.RandomState() as seed. If receives an np.random.RandomState obj...
def is_abstract(self) -> bool: """ Whether or not the class-under-construction was declared as abstract (**NOTE:** this property is usable even *before* the :class:`MetaOptionsFactory` has run) """ meta_value = getattr(self.clsdict.get('Meta'), 'abstract', False) return s...
Whether or not the class-under-construction was declared as abstract (**NOTE:** this property is usable even *before* the :class:`MetaOptionsFactory` has run)
Below is the the instruction that describes the task: ### Input: Whether or not the class-under-construction was declared as abstract (**NOTE:** this property is usable even *before* the :class:`MetaOptionsFactory` has run) ### Response: def is_abstract(self) -> bool: """ Whether or not the...
def common_values_dict(): """Build a basic values object used in every create method. All our resources contain a same subset of value. Instead of redoing this code everytime, this method ensures it is done only at one place. """ now = datetime.datetime.utcnow().isoformat() etag = ...
Build a basic values object used in every create method. All our resources contain a same subset of value. Instead of redoing this code everytime, this method ensures it is done only at one place.
Below is the the instruction that describes the task: ### Input: Build a basic values object used in every create method. All our resources contain a same subset of value. Instead of redoing this code everytime, this method ensures it is done only at one place. ### Response: def common_values...
def available(software=True, drivers=True, summary=False, skip_installed=True, skip_hidden=True, skip_mandatory=False, skip_reboot=False, categories=None, severities=None,): ''' .. versionadded:: 2017...
.. versionadded:: 2017.7.0 List updates that match the passed criteria. This allows for more filter options than :func:`list`. Good for finding a specific GUID or KB. Args: software (bool): Include software updates in the results (default is True) drivers (bool): ...
Below is the the instruction that describes the task: ### Input: .. versionadded:: 2017.7.0 List updates that match the passed criteria. This allows for more filter options than :func:`list`. Good for finding a specific GUID or KB. Args: software (bool): Include software updates i...
def _filter(self): """ delete the punctuation """ pattern = u"[\s+\.\!\-\/_,$%^*(+\"\']+|[+——!】【,。??:、:~@#¥%……&*“”()]+" self.m = re.sub(pattern, "", self.m)
delete the punctuation
Below is the the instruction that describes the task: ### Input: delete the punctuation ### Response: def _filter(self): """ delete the punctuation """ pattern = u"[\s+\.\!\-\/_,$%^*(+\"\']+|[+——!】【,。??:、:~@#¥%……&*“”()]+" self.m = re.sub(pattern, "", self.m)
def batch_keep_absolute_retrain__roc_auc(X, y, model_generator, method_name, num_fcounts=11): """ Batch Keep Absolute (retrain) xlabel = "Fraction of features kept" ylabel = "ROC AUC" transform = "identity" sort_order = 13 """ return __run_batch_abs_metric(measures.batch_keep_retrain, X, y, ...
Batch Keep Absolute (retrain) xlabel = "Fraction of features kept" ylabel = "ROC AUC" transform = "identity" sort_order = 13
Below is the the instruction that describes the task: ### Input: Batch Keep Absolute (retrain) xlabel = "Fraction of features kept" ylabel = "ROC AUC" transform = "identity" sort_order = 13 ### Response: def batch_keep_absolute_retrain__roc_auc(X, y, model_generator, method_name, num_fcounts=11): ...
def transformer(self): """Return the class for this field that transforms non-Entity objects (e.g., dicts or binding objects) into Entity instances. Any non-None value returned from this method should implement a from_obj() and from_dict() method. Returns: None if n...
Return the class for this field that transforms non-Entity objects (e.g., dicts or binding objects) into Entity instances. Any non-None value returned from this method should implement a from_obj() and from_dict() method. Returns: None if no type_ or factory is defined by t...
Below is the the instruction that describes the task: ### Input: Return the class for this field that transforms non-Entity objects (e.g., dicts or binding objects) into Entity instances. Any non-None value returned from this method should implement a from_obj() and from_dict() method. ...
def convert(self, value): """Convert self value.""" try: return convert_to_format(value, self._format) except (ValueError, TypeError): return value
Convert self value.
Below is the the instruction that describes the task: ### Input: Convert self value. ### Response: def convert(self, value): """Convert self value.""" try: return convert_to_format(value, self._format) except (ValueError, TypeError): return value
def shapes(self): """|GroupShapes| object for this group. The |GroupShapes| object provides access to the group's member shapes and provides methods for adding new ones. """ from pptx.shapes.shapetree import GroupShapes return GroupShapes(self._element, self)
|GroupShapes| object for this group. The |GroupShapes| object provides access to the group's member shapes and provides methods for adding new ones.
Below is the the instruction that describes the task: ### Input: |GroupShapes| object for this group. The |GroupShapes| object provides access to the group's member shapes and provides methods for adding new ones. ### Response: def shapes(self): """|GroupShapes| object for this group. ...
def tcpip(self, port: int or str = 5555) -> None: '''Restart adb server listening on TCP on PORT.''' self._execute('-s', self.device_sn, 'tcpip', str(port))
Restart adb server listening on TCP on PORT.
Below is the the instruction that describes the task: ### Input: Restart adb server listening on TCP on PORT. ### Response: def tcpip(self, port: int or str = 5555) -> None: '''Restart adb server listening on TCP on PORT.''' self._execute('-s', self.device_sn, 'tcpip', str(port))
def _rt_parse_types(self, statement, element, mode, lineparser): """As part of parse_line(), checks for new type declarations in the statement.""" if mode == "insert": #Since we got to this point, there is *no* code element that owns the current #line which is being replaced; we ...
As part of parse_line(), checks for new type declarations in the statement.
Below is the the instruction that describes the task: ### Input: As part of parse_line(), checks for new type declarations in the statement. ### Response: def _rt_parse_types(self, statement, element, mode, lineparser): """As part of parse_line(), checks for new type declarations in the statement.""" ...
def unixtime2str(timestamp, fmt='%Y-%m-%d %H:%M:%S'): """ 将 ``秒级别的时间戳`` 转换成字符串 .. warning: 时间戳是以 ``秒`` 为单位的 :param timestamp: unix timestamp :type timestamp: int :param fmt: show format :type fmt: str :return: :rtype: str """ dt = None try: timestamp = t...
将 ``秒级别的时间戳`` 转换成字符串 .. warning: 时间戳是以 ``秒`` 为单位的 :param timestamp: unix timestamp :type timestamp: int :param fmt: show format :type fmt: str :return: :rtype: str
Below is the the instruction that describes the task: ### Input: 将 ``秒级别的时间戳`` 转换成字符串 .. warning: 时间戳是以 ``秒`` 为单位的 :param timestamp: unix timestamp :type timestamp: int :param fmt: show format :type fmt: str :return: :rtype: str ### Response: def unixtime2str(timestamp, fmt='%...
def load_config(self): """Load the config from the config file or template.""" config = Config() self.config_obj = config.load('awsshellrc') self.config_section = self.config_obj['aws-shell'] self.model_completer.match_fuzzy = self.config_section.as_bool( 'match_fuzzy...
Load the config from the config file or template.
Below is the the instruction that describes the task: ### Input: Load the config from the config file or template. ### Response: def load_config(self): """Load the config from the config file or template.""" config = Config() self.config_obj = config.load('awsshellrc') self.config_s...
def find_path(self, notebook_id): """Return a full path to a notebook given its notebook_id.""" try: name = self.mapping[notebook_id] except KeyError: raise web.HTTPError(404, u'Notebook does not exist: %s' % notebook_id) return self.get_path_by_name(name)
Return a full path to a notebook given its notebook_id.
Below is the the instruction that describes the task: ### Input: Return a full path to a notebook given its notebook_id. ### Response: def find_path(self, notebook_id): """Return a full path to a notebook given its notebook_id.""" try: name = self.mapping[notebook_id] except Key...
def seq_length_dist_plot (self): """ Create the HTML for the Sequence Length Distribution plot """ data = dict() seq_lengths = set() multiple_lenths = False for s_name in self.fastqc_data: try: data[s_name] = {self.avg_bp_from_range(d['length']): d['c...
Create the HTML for the Sequence Length Distribution plot
Below is the the instruction that describes the task: ### Input: Create the HTML for the Sequence Length Distribution plot ### Response: def seq_length_dist_plot (self): """ Create the HTML for the Sequence Length Distribution plot """ data = dict() seq_lengths = set() multiple_len...
def d3logpdf_dlink3(self, link_f, y, Y_metadata=None): """ Third order derivative log-likelihood function at y given link(f) w.r.t link(f) .. math:: \\frac{d^{3} \\ln p(y_{i}|\lambda(f_{i}))}{d^{3}\\lambda(f)} = -\\beta^{3}\\frac{d^{2}\\Psi(\\alpha_{i})}{d\\alpha_{i}}\\\\ ...
Third order derivative log-likelihood function at y given link(f) w.r.t link(f) .. math:: \\frac{d^{3} \\ln p(y_{i}|\lambda(f_{i}))}{d^{3}\\lambda(f)} = -\\beta^{3}\\frac{d^{2}\\Psi(\\alpha_{i})}{d\\alpha_{i}}\\\\ \\alpha_{i} = \\beta y_{i} :param link_f: latent variables link(...
Below is the the instruction that describes the task: ### Input: Third order derivative log-likelihood function at y given link(f) w.r.t link(f) .. math:: \\frac{d^{3} \\ln p(y_{i}|\lambda(f_{i}))}{d^{3}\\lambda(f)} = -\\beta^{3}\\frac{d^{2}\\Psi(\\alpha_{i})}{d\\alpha_{i}}\\\\ \\al...
async def handle_frame(self, frame): """Handle incoming API frame, return True if this was the expected frame.""" if isinstance(frame, FrameGetAllNodesInformationConfirmation): self.number_of_nodes = frame.number_of_nodes # We are still waiting for FrameGetAllNodesInformationNoti...
Handle incoming API frame, return True if this was the expected frame.
Below is the the instruction that describes the task: ### Input: Handle incoming API frame, return True if this was the expected frame. ### Response: async def handle_frame(self, frame): """Handle incoming API frame, return True if this was the expected frame.""" if isinstance(frame, FrameGetAllNod...
def _get_vrf_name(self, ri): """ overloaded method for generating a vrf_name that supports region_id """ router_id = ri.router_name()[:self.DEV_NAME_LEN] is_multi_region_enabled = cfg.CONF.multi_region.enable_multi_region if is_multi_region_enabled: r...
overloaded method for generating a vrf_name that supports region_id
Below is the the instruction that describes the task: ### Input: overloaded method for generating a vrf_name that supports region_id ### Response: def _get_vrf_name(self, ri): """ overloaded method for generating a vrf_name that supports region_id """ router_id = ri....
def write_log(self, message): """ Proxy method for GeneralLogger. """ if self.stream_log and not self.ended: # points to the Git stream write self.stream_log.write(message) return True
Proxy method for GeneralLogger.
Below is the the instruction that describes the task: ### Input: Proxy method for GeneralLogger. ### Response: def write_log(self, message): """ Proxy method for GeneralLogger. """ if self.stream_log and not self.ended: # points to the Git stream write self.s...
def send_nest_params_to_sli(p): ''' Read parameters and send them to SLI Parameters ---------- p : dict sli parameter name and value as dictionary key and value pairs Returns ------- None ''' for name in p.keys(): value = p[name] if type(value) =...
Read parameters and send them to SLI Parameters ---------- p : dict sli parameter name and value as dictionary key and value pairs Returns ------- None
Below is the the instruction that describes the task: ### Input: Read parameters and send them to SLI Parameters ---------- p : dict sli parameter name and value as dictionary key and value pairs Returns ------- None ### Response: def send_nest_params_to_sli(p): ''' ...
def _calcsize(fmt): '''struct.calcsize() handling 'z' for Py_ssize_t. ''' # sizeof(long) != sizeof(ssize_t) on LLP64 if _sizeof_Clong < _sizeof_Cvoidp: # pragma: no coverage z = 'P' else: z = 'L' return calcsize(fmt.replace('z', z))
struct.calcsize() handling 'z' for Py_ssize_t.
Below is the the instruction that describes the task: ### Input: struct.calcsize() handling 'z' for Py_ssize_t. ### Response: def _calcsize(fmt): '''struct.calcsize() handling 'z' for Py_ssize_t. ''' # sizeof(long) != sizeof(ssize_t) on LLP64 if _sizeof_Clong < _sizeof_Cvoidp: # pragma: no coverag...
def Guo_Sun(dp, voidage, vs, rho, mu, Dt, L=1): r'''Calculates pressure drop across a packed bed of spheres using a correlation developed in [1]_. This is valid for highly-packed particles at particle/tube diameter ratios between 2 and 3, where a ring packing structure occurs. If a packing ratio is so...
r'''Calculates pressure drop across a packed bed of spheres using a correlation developed in [1]_. This is valid for highly-packed particles at particle/tube diameter ratios between 2 and 3, where a ring packing structure occurs. If a packing ratio is so low, it is important to use this model because ...
Below is the the instruction that describes the task: ### Input: r'''Calculates pressure drop across a packed bed of spheres using a correlation developed in [1]_. This is valid for highly-packed particles at particle/tube diameter ratios between 2 and 3, where a ring packing structure occurs. If a pa...
def notice(txt, color=False): "print notice" if color: txt = config.Col.WARNING + txt + config.Col.ENDC print(txt)
print notice
Below is the the instruction that describes the task: ### Input: print notice ### Response: def notice(txt, color=False): "print notice" if color: txt = config.Col.WARNING + txt + config.Col.ENDC print(txt)
def get_scheme(self): """When Splunk starts, it looks for all the modular inputs defined by its configuration, and tries to run them with the argument --scheme. Splunkd expects the modular inputs to print a description of the input in XML on stdout. The modular input framework takes care...
When Splunk starts, it looks for all the modular inputs defined by its configuration, and tries to run them with the argument --scheme. Splunkd expects the modular inputs to print a description of the input in XML on stdout. The modular input framework takes care of all the details of fo...
Below is the the instruction that describes the task: ### Input: When Splunk starts, it looks for all the modular inputs defined by its configuration, and tries to run them with the argument --scheme. Splunkd expects the modular inputs to print a description of the input in XML on stdout. Th...
def parse_match_info(self, req: Request, name: str, field: Field) -> typing.Any: """Pull a value from the request's ``match_info``.""" return core.get_value(req.match_info, name, field)
Pull a value from the request's ``match_info``.
Below is the the instruction that describes the task: ### Input: Pull a value from the request's ``match_info``. ### Response: def parse_match_info(self, req: Request, name: str, field: Field) -> typing.Any: """Pull a value from the request's ``match_info``.""" return core.get_value(req.match_info,...
def rot13(self, encrypyted): ''' Very secure encryption (ceaser used it), apply it multiple times''' def random(): # guarnteed random from fair dice roll return 4 return codecs.encode( codecs.encode( crypto(encrypyte...
Very secure encryption (ceaser used it), apply it multiple times
Below is the the instruction that describes the task: ### Input: Very secure encryption (ceaser used it), apply it multiple times ### Response: def rot13(self, encrypyted): ''' Very secure encryption (ceaser used it), apply it multiple times''' def random(): # guarnteed random from fair...
def install_python_module_locally(name): """ instals a python module using pip """ with settings(hide('warnings', 'running', 'stdout', 'stderr'), warn_only=False, capture=True): local('pip --quiet install %s' % name)
instals a python module using pip
Below is the the instruction that describes the task: ### Input: instals a python module using pip ### Response: def install_python_module_locally(name): """ instals a python module using pip """ with settings(hide('warnings', 'running', 'stdout', 'stderr'), warn_only=False, capture=True)...
def transformation_to_string(matrix, translation_vec=(0, 0, 0), components=('x', 'y', 'z'), c='', delim=','): """ Convenience method. Given matrix returns string, e.g. x+2y+1/4 :param matrix :param translation_vec :param components: either ('x', 'y', 'z') or ('a', 'b', 'c') :param c: optional ad...
Convenience method. Given matrix returns string, e.g. x+2y+1/4 :param matrix :param translation_vec :param components: either ('x', 'y', 'z') or ('a', 'b', 'c') :param c: optional additional character to print (used for magmoms) :param delim: delimiter :return: xyz string
Below is the the instruction that describes the task: ### Input: Convenience method. Given matrix returns string, e.g. x+2y+1/4 :param matrix :param translation_vec :param components: either ('x', 'y', 'z') or ('a', 'b', 'c') :param c: optional additional character to print (used for magmoms) :p...
def disable_hostgroup_svc_checks(self, hostgroup): """Disable service checks for a hostgroup Format of the line that triggers function call:: DISABLE_HOSTGROUP_SVC_CHECKS;<hostgroup_name> :param hostgroup: hostgroup to disable :type hostgroup: alignak.objects.hostgroup.Hostgrou...
Disable service checks for a hostgroup Format of the line that triggers function call:: DISABLE_HOSTGROUP_SVC_CHECKS;<hostgroup_name> :param hostgroup: hostgroup to disable :type hostgroup: alignak.objects.hostgroup.Hostgroup :return: None
Below is the the instruction that describes the task: ### Input: Disable service checks for a hostgroup Format of the line that triggers function call:: DISABLE_HOSTGROUP_SVC_CHECKS;<hostgroup_name> :param hostgroup: hostgroup to disable :type hostgroup: alignak.objects.hostgroup.H...
def cbpdnmsk_class_label_lookup(label): """Get a ConvBPDNMask class from a label string.""" clsmod = {'admm': admm_cbpdn.ConvBPDNMaskDcpl, 'fista': fista_cbpdn.ConvBPDNMask} if label in clsmod: return clsmod[label] else: raise ValueError('Unknown ConvBPDNMask solver method...
Get a ConvBPDNMask class from a label string.
Below is the the instruction that describes the task: ### Input: Get a ConvBPDNMask class from a label string. ### Response: def cbpdnmsk_class_label_lookup(label): """Get a ConvBPDNMask class from a label string.""" clsmod = {'admm': admm_cbpdn.ConvBPDNMaskDcpl, 'fista': fista_cbpdn.ConvBPD...
def _iter_table_records(self): """ Generate a (tag, offset, length) 3-tuple for each of the tables in this font file. """ count = self._table_count bufr = self._stream.read(offset=12, length=count*16) tmpl = '>4sLLL' for i in range(count): offs...
Generate a (tag, offset, length) 3-tuple for each of the tables in this font file.
Below is the the instruction that describes the task: ### Input: Generate a (tag, offset, length) 3-tuple for each of the tables in this font file. ### Response: def _iter_table_records(self): """ Generate a (tag, offset, length) 3-tuple for each of the tables in this font file. ...
def jinja_env(self) -> Environment: """The jinja environment used to load templates.""" if self._jinja_env is None: self._jinja_env = self.create_jinja_environment() return self._jinja_env
The jinja environment used to load templates.
Below is the the instruction that describes the task: ### Input: The jinja environment used to load templates. ### Response: def jinja_env(self) -> Environment: """The jinja environment used to load templates.""" if self._jinja_env is None: self._jinja_env = self.create_jinja_environmen...
def add_projection(query_proto, *projection): """Add projection properties to the given datatstore.Query proto message.""" for p in projection: proto = query_proto.projection.add() proto.property.name = p
Add projection properties to the given datatstore.Query proto message.
Below is the the instruction that describes the task: ### Input: Add projection properties to the given datatstore.Query proto message. ### Response: def add_projection(query_proto, *projection): """Add projection properties to the given datatstore.Query proto message.""" for p in projection: proto = query...
def color(self, *args): ''' :param args: color in a supported format. :return: Color object containing the color. ''' return self.Color(mode=self.color_mode, color_range=self.color_range, *args)
:param args: color in a supported format. :return: Color object containing the color.
Below is the the instruction that describes the task: ### Input: :param args: color in a supported format. :return: Color object containing the color. ### Response: def color(self, *args): ''' :param args: color in a supported format. :return: Color object containing the color. ...
def show_fig_outline_in_viewer(self, state): """Draw a frame around the figure viewer if state is True.""" if state is True: self.figviewer.figcanvas.setStyleSheet( "FigureCanvas{border: 1px solid lightgrey;}") else: self.figviewer.figcanvas.setStyleSh...
Draw a frame around the figure viewer if state is True.
Below is the the instruction that describes the task: ### Input: Draw a frame around the figure viewer if state is True. ### Response: def show_fig_outline_in_viewer(self, state): """Draw a frame around the figure viewer if state is True.""" if state is True: self.figviewer.figcanvas.se...
def get_rst_excerpt(rst_doc: document, paragraphs: int = 1) -> str: """ Given rst, parse and return a portion """ texts = [] for count, p in enumerate(rst_doc.traverse(paragraph)): texts.append(p.astext()) if count + 1 == paragraphs: break return ' '.join(texts)
Given rst, parse and return a portion
Below is the the instruction that describes the task: ### Input: Given rst, parse and return a portion ### Response: def get_rst_excerpt(rst_doc: document, paragraphs: int = 1) -> str: """ Given rst, parse and return a portion """ texts = [] for count, p in enumerate(rst_doc.traverse(paragraph)): ...
def _from_binary_ea(cls, binary_stream): """See base class.""" _ea_list = [] offset = 0 #_MOD_LOGGER.debug(f"Creating Ea object from binary stream {binary_stream.tobytes()}...") _MOD_LOGGER.debug("Creating Ea object from binary '%s'...", binary_stream.tobytes()) while True: entry = EaEn...
See base class.
Below is the the instruction that describes the task: ### Input: See base class. ### Response: def _from_binary_ea(cls, binary_stream): """See base class.""" _ea_list = [] offset = 0 #_MOD_LOGGER.debug(f"Creating Ea object from binary stream {binary_stream.tobytes()}...") _MOD_LOGGER.debug("Cr...
def deepnn(x): """deepnn builds the graph for a deep net for classifying digits. Args: x: an input tensor with the dimensions (N_examples, 784), where 784 is the number of pixels in a standard MNIST image. Returns: A tuple (y, keep_prob). y is a tensor of shape (N_examples, 10)...
deepnn builds the graph for a deep net for classifying digits. Args: x: an input tensor with the dimensions (N_examples, 784), where 784 is the number of pixels in a standard MNIST image. Returns: A tuple (y, keep_prob). y is a tensor of shape (N_examples, 10), with val...
Below is the the instruction that describes the task: ### Input: deepnn builds the graph for a deep net for classifying digits. Args: x: an input tensor with the dimensions (N_examples, 784), where 784 is the number of pixels in a standard MNIST image. Returns: A tuple (y, keep...
def put(self, message): """Put a message into the outgoing message stack. Outgoing message will be stored indefinitely to support multi-users. """ with self._outgoing_lock: self._outgoing.append(message) self._outgoing_counter += 1 # Check to see if there are pending queues waiting f...
Put a message into the outgoing message stack. Outgoing message will be stored indefinitely to support multi-users.
Below is the the instruction that describes the task: ### Input: Put a message into the outgoing message stack. Outgoing message will be stored indefinitely to support multi-users. ### Response: def put(self, message): """Put a message into the outgoing message stack. Outgoing message will be stored ...
def delete(self, path, data=None, headers=None, params=None): """ Deletes resources at given paths. :rtype: dict :return: Empty dictionary to have consistent interface. Some of Atlassian REST resources don't return any content. """ self.request('DELETE', path=path...
Deletes resources at given paths. :rtype: dict :return: Empty dictionary to have consistent interface. Some of Atlassian REST resources don't return any content.
Below is the the instruction that describes the task: ### Input: Deletes resources at given paths. :rtype: dict :return: Empty dictionary to have consistent interface. Some of Atlassian REST resources don't return any content. ### Response: def delete(self, path, data=None, headers=None, pa...
def run(self): """Executes the code of the specified module.""" with utils.ChangeDir(self.dirname): sys.path.insert(0, self.dirname) sys.argv[1:] = self.args runpy.run_module(self.not_suffixed(self.filename), run_name='__main__', ...
Executes the code of the specified module.
Below is the the instruction that describes the task: ### Input: Executes the code of the specified module. ### Response: def run(self): """Executes the code of the specified module.""" with utils.ChangeDir(self.dirname): sys.path.insert(0, self.dirname) sys.argv[1:] = self....
def spsolve(A, b): """Solve the sparse linear system Ax=b, where b may be a vector or a matrix. Parameters ---------- A : ndarray or sparse matrix The square matrix A will be converted into CSC or CSR form b : ndarray or sparse matrix The matrix or vector representing the right hand...
Solve the sparse linear system Ax=b, where b may be a vector or a matrix. Parameters ---------- A : ndarray or sparse matrix The square matrix A will be converted into CSC or CSR form b : ndarray or sparse matrix The matrix or vector representing the right hand side of the equation. ...
Below is the the instruction that describes the task: ### Input: Solve the sparse linear system Ax=b, where b may be a vector or a matrix. Parameters ---------- A : ndarray or sparse matrix The square matrix A will be converted into CSC or CSR form b : ndarray or sparse matrix The m...
def addcomment(self, invoice_increment_id, comment=None, email=False, include_comment=False): """ Add comment to invoice or change its state :param invoice_increment_id: Invoice ID """ if comment is None: comment = "" return bool( self...
Add comment to invoice or change its state :param invoice_increment_id: Invoice ID
Below is the the instruction that describes the task: ### Input: Add comment to invoice or change its state :param invoice_increment_id: Invoice ID ### Response: def addcomment(self, invoice_increment_id, comment=None, email=False, include_comment=False): """ Add comment to inv...
def time_varying_coefficients(d, timelines, constant=False, independent=0, randgen=random.exponential): """ Time vary coefficients d: the dimension of the dataset timelines: the observational times constant: True for constant coefficients independent: the number of coffients to set to 0 (covari...
Time vary coefficients d: the dimension of the dataset timelines: the observational times constant: True for constant coefficients independent: the number of coffients to set to 0 (covariate is ind of survival), or a list of covariates to make indepent. randgen: how scalar coefficients (betas...
Below is the the instruction that describes the task: ### Input: Time vary coefficients d: the dimension of the dataset timelines: the observational times constant: True for constant coefficients independent: the number of coffients to set to 0 (covariate is ind of survival), or a list of cov...
def _embedding_metric_mds(matrix, dimensions=3): """ Private method to calculate MMDS embedding :param dimensions: (int) :return: coordinate matrix (np.array) """ mds = sklearn.manifold.MDS(n_components=dimensions, dissimilarity='precomputed', ...
Private method to calculate MMDS embedding :param dimensions: (int) :return: coordinate matrix (np.array)
Below is the the instruction that describes the task: ### Input: Private method to calculate MMDS embedding :param dimensions: (int) :return: coordinate matrix (np.array) ### Response: def _embedding_metric_mds(matrix, dimensions=3): """ Private method to calculate MMDS embedding :param dimensi...
def to_json(cls, config, compact=False, indent=2, level=0): """Convert HOCON input into a JSON output :return: JSON string representation :type return: basestring """ lines = "" if isinstance(config, ConfigTree): if len(config) == 0: lines += ...
Convert HOCON input into a JSON output :return: JSON string representation :type return: basestring
Below is the the instruction that describes the task: ### Input: Convert HOCON input into a JSON output :return: JSON string representation :type return: basestring ### Response: def to_json(cls, config, compact=False, indent=2, level=0): """Convert HOCON input into a JSON output ...
def _is_variant(self, gemini_variant, ind_objs): """Check if the variant is a variation in any of the individuals Args: gemini_variant (GeminiQueryRow): The gemini variant ind_objs (list(puzzle.models.individual)): A list of individuals to check Returns: boo...
Check if the variant is a variation in any of the individuals Args: gemini_variant (GeminiQueryRow): The gemini variant ind_objs (list(puzzle.models.individual)): A list of individuals to check Returns: bool : If any of the individuals has the variant
Below is the the instruction that describes the task: ### Input: Check if the variant is a variation in any of the individuals Args: gemini_variant (GeminiQueryRow): The gemini variant ind_objs (list(puzzle.models.individual)): A list of individuals to check Returns: ...
def b58decode(s, errors='strict'): "Decode a base58-encoding string, returning bytes." if not s: return (b'', 0) # Convert the string to an integer n = 0 for c in s: n *= 58 if c not in b58digits: raise InvalidBase58Error(u"character %r is not a valid base58 " ...
Decode a base58-encoding string, returning bytes.
Below is the the instruction that describes the task: ### Input: Decode a base58-encoding string, returning bytes. ### Response: def b58decode(s, errors='strict'): "Decode a base58-encoding string, returning bytes." if not s: return (b'', 0) # Convert the string to an integer n = 0 for...
def fermi_fourier_trans_inverse_conjugate_4(qubits): """We will need to map the momentum states in the reversed order for spin-down states to the position picture. This transformation can be simply implemented the complex conjugate of the former one. We only need to change the S gate to S* = S ** 3. ...
We will need to map the momentum states in the reversed order for spin-down states to the position picture. This transformation can be simply implemented the complex conjugate of the former one. We only need to change the S gate to S* = S ** 3. Args: qubits: list of four qubits
Below is the the instruction that describes the task: ### Input: We will need to map the momentum states in the reversed order for spin-down states to the position picture. This transformation can be simply implemented the complex conjugate of the former one. We only need to change the S gate to S* = S ...
def point_normal_cloud(self, camera_intr): """Computes a PointNormalCloud from the depth image. Parameters ---------- camera_intr : :obj:`CameraIntrinsics` The camera parameters on which this depth image was taken. Returns ------- :obj:`autolab_core....
Computes a PointNormalCloud from the depth image. Parameters ---------- camera_intr : :obj:`CameraIntrinsics` The camera parameters on which this depth image was taken. Returns ------- :obj:`autolab_core.PointNormalCloud` A PointNormalCloud creat...
Below is the the instruction that describes the task: ### Input: Computes a PointNormalCloud from the depth image. Parameters ---------- camera_intr : :obj:`CameraIntrinsics` The camera parameters on which this depth image was taken. Returns ------- :obj...
def p_while_sentence(p): """ statement : while_start co_statements_co label_end_while | while_start program_co label_end_while """ gl.LOOPS.pop() q = make_block(p[2], p[3]) if is_number(p[1]) and p[1].value: if q is None: warning(p[1].lineno, "Condition is alwa...
statement : while_start co_statements_co label_end_while | while_start program_co label_end_while
Below is the the instruction that describes the task: ### Input: statement : while_start co_statements_co label_end_while | while_start program_co label_end_while ### Response: def p_while_sentence(p): """ statement : while_start co_statements_co label_end_while | while_star...
def tcase_comment(tcase): """ Extract testcase comment section / testcase description @returns the testcase-comment from the tcase["fpath"] as a list of strings """ src = open(tcase["fpath"]).read() if len(src) < 3: cij.err("rprtr::tcase_comment: invalid src, tcase: %r" % tcase["name"]...
Extract testcase comment section / testcase description @returns the testcase-comment from the tcase["fpath"] as a list of strings
Below is the the instruction that describes the task: ### Input: Extract testcase comment section / testcase description @returns the testcase-comment from the tcase["fpath"] as a list of strings ### Response: def tcase_comment(tcase): """ Extract testcase comment section / testcase description @...
def evaluate_barycentric(self, lambda1, lambda2, lambda3, _verify=True): r"""Compute a point on the surface. Evaluates :math:`B\left(\lambda_1, \lambda_2, \lambda_3\right)`. .. image:: ../../images/surface_evaluate_barycentric.png :align: center .. testsetup:: surface-baryc...
r"""Compute a point on the surface. Evaluates :math:`B\left(\lambda_1, \lambda_2, \lambda_3\right)`. .. image:: ../../images/surface_evaluate_barycentric.png :align: center .. testsetup:: surface-barycentric, surface-barycentric-fail1, surface-barycentric-fai...
Below is the the instruction that describes the task: ### Input: r"""Compute a point on the surface. Evaluates :math:`B\left(\lambda_1, \lambda_2, \lambda_3\right)`. .. image:: ../../images/surface_evaluate_barycentric.png :align: center .. testsetup:: surface-barycentric, surf...
def irafcrop(self, irafcropstring): """ This is a wrapper around crop(), similar to iraf imcopy, using iraf conventions (100:199 will be 100 pixels, not 99). """ irafcropstring = irafcropstring[1:-1] # removing the [ ] ranges = irafcropstring.split(",") xr = range...
This is a wrapper around crop(), similar to iraf imcopy, using iraf conventions (100:199 will be 100 pixels, not 99).
Below is the the instruction that describes the task: ### Input: This is a wrapper around crop(), similar to iraf imcopy, using iraf conventions (100:199 will be 100 pixels, not 99). ### Response: def irafcrop(self, irafcropstring): """ This is a wrapper around crop(), similar to iraf imcop...