code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def json(self): """ Return JSON representation of object. """ if self.meta_type == 'list': ret = [] for dat in self._list: if not isinstance(dat, composite): ret.append(dat) else: ret.append(d...
Return JSON representation of object.
Below is the the instruction that describes the task: ### Input: Return JSON representation of object. ### Response: def json(self): """ Return JSON representation of object. """ if self.meta_type == 'list': ret = [] for dat in self._list: if ...
def parse_date(datestring): """Attepmts to parse an ISO8601 formatted ``datestring``. Returns a ``datetime.datetime`` object. """ datestring = str(datestring).strip() if not datestring[0].isdigit(): raise ParseError() if 'W' in datestring.upper(): try: datestring =...
Attepmts to parse an ISO8601 formatted ``datestring``. Returns a ``datetime.datetime`` object.
Below is the the instruction that describes the task: ### Input: Attepmts to parse an ISO8601 formatted ``datestring``. Returns a ``datetime.datetime`` object. ### Response: def parse_date(datestring): """Attepmts to parse an ISO8601 formatted ``datestring``. Returns a ``datetime.datetime`` object. ...
def _generate_cpu_stats(): """Read and display processor name """ cpu_name = urwid.Text("CPU Name N/A", align="center") try: cpu_name = urwid.Text(get_processor_name().strip(), align="center") except OSError: logging.info("CPU name not available") return [...
Read and display processor name
Below is the the instruction that describes the task: ### Input: Read and display processor name ### Response: def _generate_cpu_stats(): """Read and display processor name """ cpu_name = urwid.Text("CPU Name N/A", align="center") try: cpu_name = urwid.Text(get_processor_name()....
def one_hot(cls, n, l): """ n: position of "hot" l: lenght of vector """ v = [0.0] * l v[n] = 1.0 return Vector(v)
n: position of "hot" l: lenght of vector
Below is the the instruction that describes the task: ### Input: n: position of "hot" l: lenght of vector ### Response: def one_hot(cls, n, l): """ n: position of "hot" l: lenght of vector """ v = [0.0] * l v[n] = 1.0 return Vector(v)
def _compute_intra_event_alpha(self, C, vs30, pga1100): """ Returns the linearised functional relationship between fsite and pga1100, determined from the partial derivative defined on equation 17 on page 148 """ alpha = np.zeros_like(vs30, dtype=float) idx = vs30 ...
Returns the linearised functional relationship between fsite and pga1100, determined from the partial derivative defined on equation 17 on page 148
Below is the the instruction that describes the task: ### Input: Returns the linearised functional relationship between fsite and pga1100, determined from the partial derivative defined on equation 17 on page 148 ### Response: def _compute_intra_event_alpha(self, C, vs30, pga1100): """ ...
def RotateServerKey(cn=u"grr", keylength=4096): """This function creates and installs a new server key. Note that - Clients might experience intermittent connection problems after the server keys rotated. - It's not possible to go back to an earlier key. Clients that see a new certificate will rememb...
This function creates and installs a new server key. Note that - Clients might experience intermittent connection problems after the server keys rotated. - It's not possible to go back to an earlier key. Clients that see a new certificate will remember the cert's serial number and refuse to accept ...
Below is the the instruction that describes the task: ### Input: This function creates and installs a new server key. Note that - Clients might experience intermittent connection problems after the server keys rotated. - It's not possible to go back to an earlier key. Clients that see a new certifi...
def update_token(self): """If a username and password are present - attempt to use them to request a fresh SAS token. """ if not self.username or not self.password: raise errors.TokenExpired("Unable to refresh token - no username or password.") encoded_uri = compat.qu...
If a username and password are present - attempt to use them to request a fresh SAS token.
Below is the the instruction that describes the task: ### Input: If a username and password are present - attempt to use them to request a fresh SAS token. ### Response: def update_token(self): """If a username and password are present - attempt to use them to request a fresh SAS token. ...
def add(self, name, *vals): ''' Add values as iter() compatible items in the current scope frame. ''' item = self.frames[-1].get(name) if item is None: self.frames[-1][name] = item = [] item.extend(vals)
Add values as iter() compatible items in the current scope frame.
Below is the the instruction that describes the task: ### Input: Add values as iter() compatible items in the current scope frame. ### Response: def add(self, name, *vals): ''' Add values as iter() compatible items in the current scope frame. ''' item = self.frames[-1].get(name) ...
def _bytelist2longBigEndian(list): "Transform a list of characters into a list of longs." imax = len(list) // 4 hl = [0] * imax j = 0 i = 0 while i < imax: b0 = ord(list[j]) << 24 b1 = ord(list[j+1]) << 16 b2 = ord(list[j+2]) << 8 b3 = ord(list[j+3]) hl[...
Transform a list of characters into a list of longs.
Below is the the instruction that describes the task: ### Input: Transform a list of characters into a list of longs. ### Response: def _bytelist2longBigEndian(list): "Transform a list of characters into a list of longs." imax = len(list) // 4 hl = [0] * imax j = 0 i = 0 while i < imax: ...
def parse_response(resp): """ Method to parse response from the Optimizely API and return results as JSON. Errors are thrown for various errors that the API can throw. """ if resp.status_code in [200, 201, 202]: return resp.json() elif resp.status_code == 204:...
Method to parse response from the Optimizely API and return results as JSON. Errors are thrown for various errors that the API can throw.
Below is the the instruction that describes the task: ### Input: Method to parse response from the Optimizely API and return results as JSON. Errors are thrown for various errors that the API can throw. ### Response: def parse_response(resp): """ Method to parse response from the Optimizely...
def _set_igmps_interface(self, v, load=False): """ Setter method for igmps_interface, mapped from YANG variable /interface_vlan/vlan/ip/igmpVlan/snooping/igmps_mrouter/igmps_interface (list) If this variable is read-only (config: false) in the source YANG file, then _set_igmps_interface is considered as...
Setter method for igmps_interface, mapped from YANG variable /interface_vlan/vlan/ip/igmpVlan/snooping/igmps_mrouter/igmps_interface (list) If this variable is read-only (config: false) in the source YANG file, then _set_igmps_interface is considered as a private method. Backends looking to populate this va...
Below is the the instruction that describes the task: ### Input: Setter method for igmps_interface, mapped from YANG variable /interface_vlan/vlan/ip/igmpVlan/snooping/igmps_mrouter/igmps_interface (list) If this variable is read-only (config: false) in the source YANG file, then _set_igmps_interface is con...
def coords(self): """The current absolute coordinates of the touch event, in mm from the top left corner of the device. To get the corresponding output screen coordinates, use :meth:`transform_coords`. For events not of type :attr:`~libinput.constant.EventType.TOUCH_DOWN`, :attr:`~libinput.constant.EventT...
The current absolute coordinates of the touch event, in mm from the top left corner of the device. To get the corresponding output screen coordinates, use :meth:`transform_coords`. For events not of type :attr:`~libinput.constant.EventType.TOUCH_DOWN`, :attr:`~libinput.constant.EventType.TOUCH_MOTION`, this...
Below is the the instruction that describes the task: ### Input: The current absolute coordinates of the touch event, in mm from the top left corner of the device. To get the corresponding output screen coordinates, use :meth:`transform_coords`. For events not of type :attr:`~libinput.constant.EventType.T...
def override_operation(self, operation, reason): """Re-Classify entry pair.""" prev_class = (self.local_classification, self.remote_classification) prev_op = self.operation assert operation != prev_op assert operation in PAIR_OPERATIONS if self.any_entry.target.synchroniz...
Re-Classify entry pair.
Below is the the instruction that describes the task: ### Input: Re-Classify entry pair. ### Response: def override_operation(self, operation, reason): """Re-Classify entry pair.""" prev_class = (self.local_classification, self.remote_classification) prev_op = self.operation assert ...
def taskfileinfo_task_data(tfi, role): """Return the data for task :param tfi: the :class:`jukeboxcore.filesys.TaskFileInfo` holds the data :type tfi: :class:`jukeboxcore.filesys.TaskFileInfo` :param role: item data role :type role: QtCore.Qt.ItemDataRole :returns: data for the task :rtype:...
Return the data for task :param tfi: the :class:`jukeboxcore.filesys.TaskFileInfo` holds the data :type tfi: :class:`jukeboxcore.filesys.TaskFileInfo` :param role: item data role :type role: QtCore.Qt.ItemDataRole :returns: data for the task :rtype: depending on role :raises: None
Below is the the instruction that describes the task: ### Input: Return the data for task :param tfi: the :class:`jukeboxcore.filesys.TaskFileInfo` holds the data :type tfi: :class:`jukeboxcore.filesys.TaskFileInfo` :param role: item data role :type role: QtCore.Qt.ItemDataRole :returns: data f...
def training_data(job_id): '''Returns training_examples for a given job_id from offset to limit If full_info parameter is greater than 0, will return extra architecture info, GET /jobs/139/vectors?offset=0&limit=10&full_info=1 { "labeled_vectors": [{"vector":{"indices": {"0": 1}, "reductions": 3...
Returns training_examples for a given job_id from offset to limit If full_info parameter is greater than 0, will return extra architecture info, GET /jobs/139/vectors?offset=0&limit=10&full_info=1 { "labeled_vectors": [{"vector":{"indices": {"0": 1}, "reductions": 3}, "label":0}, ...
Below is the the instruction that describes the task: ### Input: Returns training_examples for a given job_id from offset to limit If full_info parameter is greater than 0, will return extra architecture info, GET /jobs/139/vectors?offset=0&limit=10&full_info=1 { "labeled_vectors": [{"vector":{"...
def relocate_image(self, new_ImageBase): """Apply the relocation information to the image using the provided new image base. This method will apply the relocation information to the image. Given the new base, all the relocations will be processed and both the raw data and the section's data ...
Apply the relocation information to the image using the provided new image base. This method will apply the relocation information to the image. Given the new base, all the relocations will be processed and both the raw data and the section's data will be fixed accordingly. The resultin...
Below is the the instruction that describes the task: ### Input: Apply the relocation information to the image using the provided new image base. This method will apply the relocation information to the image. Given the new base, all the relocations will be processed and both the raw data and the s...
def check(self, state, when): """ Checks state `state` to see if the breakpoint should fire. :param state: The state. :param when: Whether the check is happening before or after the event. :return: A boolean representing whether the checkpoint should fire. ""...
Checks state `state` to see if the breakpoint should fire. :param state: The state. :param when: Whether the check is happening before or after the event. :return: A boolean representing whether the checkpoint should fire.
Below is the the instruction that describes the task: ### Input: Checks state `state` to see if the breakpoint should fire. :param state: The state. :param when: Whether the check is happening before or after the event. :return: A boolean representing whether the checkpoint shou...
def _search(self, search_state, include_current_position=False, count=1): """ Execute search. Return (working_index, cursor_position) tuple when this search is applied. Returns `None` when this text cannot be found. """ assert isinstance(search_state, SearchState) assert ...
Execute search. Return (working_index, cursor_position) tuple when this search is applied. Returns `None` when this text cannot be found.
Below is the the instruction that describes the task: ### Input: Execute search. Return (working_index, cursor_position) tuple when this search is applied. Returns `None` when this text cannot be found. ### Response: def _search(self, search_state, include_current_position=False, count=1): """ ...
def WaitForTasks(tasks, raiseOnError=True, si=None, pc=None, onProgressUpdate=None, results=None): """ Wait for mulitiple tasks to complete. Much faster than calling WaitForTask N times """ if not tasks: re...
Wait for mulitiple tasks to complete. Much faster than calling WaitForTask N times
Below is the the instruction that describes the task: ### Input: Wait for mulitiple tasks to complete. Much faster than calling WaitForTask N times ### Response: def WaitForTasks(tasks, raiseOnError=True, si=None, pc=None, onProgressUpdate=Non...
def handle(request, message=None, redirect=None, ignore=False, escalate=False, log_level=None, force_log=None): """Centralized error handling for Horizon. Because Horizon consumes so many different APIs with completely different ``Exception`` types, it's necessary to have a centralized place...
Centralized error handling for Horizon. Because Horizon consumes so many different APIs with completely different ``Exception`` types, it's necessary to have a centralized place for handling exceptions which may be raised. Exceptions are roughly divided into 3 types: #. ``UNAUTHORIZED``: Errors r...
Below is the the instruction that describes the task: ### Input: Centralized error handling for Horizon. Because Horizon consumes so many different APIs with completely different ``Exception`` types, it's necessary to have a centralized place for handling exceptions which may be raised. Exceptions...
def _build_url(self): """Build url based on searching by date or by show.""" url_params = [ BASE_URL, self.category + ' ratings', self.day, self.year, self.month ] return SEARCH_URL.format(*url_params)
Build url based on searching by date or by show.
Below is the the instruction that describes the task: ### Input: Build url based on searching by date or by show. ### Response: def _build_url(self): """Build url based on searching by date or by show.""" url_params = [ BASE_URL, self.category + ' ratings', self.day, self.year, self.mon...
def sort(self, ids): """ Sort the given list of identifiers, returning a new (sorted) list. :param list ids: the list of identifiers to be sorted :rtype: list """ def extract_int(string): """ Extract an integer from the given string. ...
Sort the given list of identifiers, returning a new (sorted) list. :param list ids: the list of identifiers to be sorted :rtype: list
Below is the the instruction that describes the task: ### Input: Sort the given list of identifiers, returning a new (sorted) list. :param list ids: the list of identifiers to be sorted :rtype: list ### Response: def sort(self, ids): """ Sort the given list of identifiers, ...
def find_in_coord_list_pbc(fcoord_list, fcoord, atol=1e-8): """ Get the indices of all points in a fractional coord list that are equal to a fractional coord (with a tolerance), taking into account periodic boundary conditions. Args: fcoord_list: List of fractional coords fcoord: A ...
Get the indices of all points in a fractional coord list that are equal to a fractional coord (with a tolerance), taking into account periodic boundary conditions. Args: fcoord_list: List of fractional coords fcoord: A specific fractional coord to test. atol: Absolute tolerance. Def...
Below is the the instruction that describes the task: ### Input: Get the indices of all points in a fractional coord list that are equal to a fractional coord (with a tolerance), taking into account periodic boundary conditions. Args: fcoord_list: List of fractional coords fcoord: A spe...
def _split_span(self, span, index, length=0): """Split a span into two or three separate spans at certain indices.""" offset = span[1] + index if index < 0 else span[0] + index # log.debug([(span[0], offset), (offset, offset + length), (offset + length, span[1])]) return [(span[0], offse...
Split a span into two or three separate spans at certain indices.
Below is the the instruction that describes the task: ### Input: Split a span into two or three separate spans at certain indices. ### Response: def _split_span(self, span, index, length=0): """Split a span into two or three separate spans at certain indices.""" offset = span[1] + index if index < ...
def get_window_location(self, window): """ Get a window's location. """ screen_ret = Screen() x_ret = ctypes.c_int(0) y_ret = ctypes.c_int(0) _libxdo.xdo_get_window_location( self._xdo, window, ctypes.byref(x_ret), ctypes.byref(y_ret), ctyp...
Get a window's location.
Below is the the instruction that describes the task: ### Input: Get a window's location. ### Response: def get_window_location(self, window): """ Get a window's location. """ screen_ret = Screen() x_ret = ctypes.c_int(0) y_ret = ctypes.c_int(0) _libxdo.xdo_g...
def get_write_fields(self): """ Get the list of fields used to write the header, separating record and signal specification fields. Returns the default required fields, the user defined fields, and their dependencies. Does NOT include `d_signal` or `e_d_signal`. ...
Get the list of fields used to write the header, separating record and signal specification fields. Returns the default required fields, the user defined fields, and their dependencies. Does NOT include `d_signal` or `e_d_signal`. Returns ------- rec_write_field...
Below is the the instruction that describes the task: ### Input: Get the list of fields used to write the header, separating record and signal specification fields. Returns the default required fields, the user defined fields, and their dependencies. Does NOT include `d_signal` or `...
def get_compositions(self): """Gets the composition list resulting from a search. return: (osid.repository.CompositionList) - the composition list raise: IllegalState - the list has already been retrieved *compliance: mandatory -- This method must be implemented.* """ ...
Gets the composition list resulting from a search. return: (osid.repository.CompositionList) - the composition list raise: IllegalState - the list has already been retrieved *compliance: mandatory -- This method must be implemented.*
Below is the the instruction that describes the task: ### Input: Gets the composition list resulting from a search. return: (osid.repository.CompositionList) - the composition list raise: IllegalState - the list has already been retrieved *compliance: mandatory -- This method must be imple...
def release(self): """Try to delete the lock files. Doesn't matter if we fail""" if self.lock_filename != self.pid_filename: try: os.unlink(self.lock_filename) except OSError: pass try: os.remove(self.pid_filename) exce...
Try to delete the lock files. Doesn't matter if we fail
Below is the the instruction that describes the task: ### Input: Try to delete the lock files. Doesn't matter if we fail ### Response: def release(self): """Try to delete the lock files. Doesn't matter if we fail""" if self.lock_filename != self.pid_filename: try: os.unl...
def write(self, data, assert_ss=True, deassert_ss=True): """Half-duplex SPI write. If assert_ss is True, the SS line will be asserted low, the specified bytes will be clocked out the MOSI line, and if deassert_ss is True the SS line be put back high. """ # Fail MOSI is not speci...
Half-duplex SPI write. If assert_ss is True, the SS line will be asserted low, the specified bytes will be clocked out the MOSI line, and if deassert_ss is True the SS line be put back high.
Below is the the instruction that describes the task: ### Input: Half-duplex SPI write. If assert_ss is True, the SS line will be asserted low, the specified bytes will be clocked out the MOSI line, and if deassert_ss is True the SS line be put back high. ### Response: def write(self, data, assert...
def load_tf_weights_in_bert(model, tf_checkpoint_path): """ Load tf checkpoints in a pytorch model """ try: import re import numpy as np import tensorflow as tf except ImportError: print("Loading a TensorFlow models in PyTorch, requires TensorFlow to be installed. Please ...
Load tf checkpoints in a pytorch model
Below is the the instruction that describes the task: ### Input: Load tf checkpoints in a pytorch model ### Response: def load_tf_weights_in_bert(model, tf_checkpoint_path): """ Load tf checkpoints in a pytorch model """ try: import re import numpy as np import tensorflow as tf ...
def delayed_burst_run(self, target_cycles_per_sec): """ Run CPU not faster than given speedlimit """ old_cycles = self.cycles start_time = time.time() self.burst_run() is_duration = time.time() - start_time new_cycles = self.cycles - old_cycles try: ...
Run CPU not faster than given speedlimit
Below is the the instruction that describes the task: ### Input: Run CPU not faster than given speedlimit ### Response: def delayed_burst_run(self, target_cycles_per_sec): """ Run CPU not faster than given speedlimit """ old_cycles = self.cycles start_time = time.time() self.burst_...
def to_tsv(): """ Save all regular expressions to a tsv file so they can be more easily copy/pasted in Sublime """ with open(os.path.join(DATA_PATH, 'regexes.tsv'), mode='wt') as fout: vars = copy.copy(tuple(globals().items())) for k, v in vars: if k.lower().startswith('cre_'): ...
Save all regular expressions to a tsv file so they can be more easily copy/pasted in Sublime
Below is the the instruction that describes the task: ### Input: Save all regular expressions to a tsv file so they can be more easily copy/pasted in Sublime ### Response: def to_tsv(): """ Save all regular expressions to a tsv file so they can be more easily copy/pasted in Sublime """ with open(os.path.jo...
def build_graph(self): """ Read lazy dependency list and build graph. """ for child, parents in self.dependencies.items(): if child not in self.nodes: raise NodeNotFoundError( "App %s SQL item dependencies reference nonexistent child node %...
Read lazy dependency list and build graph.
Below is the the instruction that describes the task: ### Input: Read lazy dependency list and build graph. ### Response: def build_graph(self): """ Read lazy dependency list and build graph. """ for child, parents in self.dependencies.items(): if child not in self.nodes...
def getMac256Hash(challenge, appId="msmsgs@msnmsgr.com", key="Q1P7W2E4J9R8U3S5"): """ Generate the lock-and-key response, needed to acquire registration tokens. """ clearText = challenge + appId clearText += "0" * (8 - len(clearText) % 8) def int32ToHexString(n): ...
Generate the lock-and-key response, needed to acquire registration tokens.
Below is the the instruction that describes the task: ### Input: Generate the lock-and-key response, needed to acquire registration tokens. ### Response: def getMac256Hash(challenge, appId="msmsgs@msnmsgr.com", key="Q1P7W2E4J9R8U3S5"): """ Generate the lock-and-key response, needed to acquire regis...
def _parse_custom_mpi_options(custom_mpi_options): # type: (str) -> Tuple[argparse.Namespace, List[str]] """Parse custom MPI options provided by user. Known options default value will be overridden and unknown options would be identified separately.""" parser = argparse.ArgumentParser() parser.add_...
Parse custom MPI options provided by user. Known options default value will be overridden and unknown options would be identified separately.
Below is the the instruction that describes the task: ### Input: Parse custom MPI options provided by user. Known options default value will be overridden and unknown options would be identified separately. ### Response: def _parse_custom_mpi_options(custom_mpi_options): # type: (str) -> Tuple[argparse.Nam...
def install(name, minimum_version=None, required_version=None, scope=None, repository=None): ''' Install a Powershell module from powershell gallery on the system. :param name: Name of a Powershell module :type name: ``str`` :param minimum_version: The maximum version to install, e.g....
Install a Powershell module from powershell gallery on the system. :param name: Name of a Powershell module :type name: ``str`` :param minimum_version: The maximum version to install, e.g. 1.23.2 :type minimum_version: ``str`` :param required_version: Install a specific version :type requi...
Below is the the instruction that describes the task: ### Input: Install a Powershell module from powershell gallery on the system. :param name: Name of a Powershell module :type name: ``str`` :param minimum_version: The maximum version to install, e.g. 1.23.2 :type minimum_version: ``str`` ...
def commits(self, branch, since = 0, to = int(time.time()) + 86400): """For given branch return a list of commits. Each commit contains basic information about itself. :param branch: git branch :type branch: [str]{} :param since: minimal timestamp for commit's commit date :type since: int :param to: ma...
For given branch return a list of commits. Each commit contains basic information about itself. :param branch: git branch :type branch: [str]{} :param since: minimal timestamp for commit's commit date :type since: int :param to: maximal timestamp for commit's commit date :type to: int
Below is the the instruction that describes the task: ### Input: For given branch return a list of commits. Each commit contains basic information about itself. :param branch: git branch :type branch: [str]{} :param since: minimal timestamp for commit's commit date :type since: int :param to: maximal...
def _split_names(namestr): """Split a comma-separated list of channel names. """ out = [] namestr = QUOTE_REGEX.sub('', namestr) while True: namestr = namestr.strip('\' \n') if ',' not in namestr: break for nds2type in io_nds2.N...
Split a comma-separated list of channel names.
Below is the the instruction that describes the task: ### Input: Split a comma-separated list of channel names. ### Response: def _split_names(namestr): """Split a comma-separated list of channel names. """ out = [] namestr = QUOTE_REGEX.sub('', namestr) while True: ...
def svm_load_model(model_file_name): """ svm_load_model(model_file_name) -> model Load a LIBSVM model from model_file_name and return. """ model = libsvm.svm_load_model(model_file_name.encode()) if not model: print("can't open model file %s" % model_file_name) return None model = toPyModel(model) return mo...
svm_load_model(model_file_name) -> model Load a LIBSVM model from model_file_name and return.
Below is the the instruction that describes the task: ### Input: svm_load_model(model_file_name) -> model Load a LIBSVM model from model_file_name and return. ### Response: def svm_load_model(model_file_name): """ svm_load_model(model_file_name) -> model Load a LIBSVM model from model_file_name and return. ...
def form_invalid(self, form, prefix=None): """ If form invalid return error list in JSON response """ response = super(FormAjaxMixin, self).form_invalid(form) if self.request.is_ajax(): data = { "errors_list": self.add_prefix(form.errors, prefix), } ...
If form invalid return error list in JSON response
Below is the the instruction that describes the task: ### Input: If form invalid return error list in JSON response ### Response: def form_invalid(self, form, prefix=None): """ If form invalid return error list in JSON response """ response = super(FormAjaxMixin, self).form_invalid(form) if...
def convert_leakyrelu(node, **kwargs): """Map MXNet's LeakyReLU operator attributes to onnx's Elu/LeakyRelu/PRelu operators based on the input node's attributes and return the created node. """ name, input_nodes, attrs = get_inputs(node, kwargs) act_type = attrs.get("act_type", "leaky") alpha =...
Map MXNet's LeakyReLU operator attributes to onnx's Elu/LeakyRelu/PRelu operators based on the input node's attributes and return the created node.
Below is the the instruction that describes the task: ### Input: Map MXNet's LeakyReLU operator attributes to onnx's Elu/LeakyRelu/PRelu operators based on the input node's attributes and return the created node. ### Response: def convert_leakyrelu(node, **kwargs): """Map MXNet's LeakyReLU operator attribu...
def get_accounts(self, owner_id=None, member_id=None, properties=None): """GetAccounts. Get a list of accounts for a specific owner or a specific member. :param str owner_id: ID for the owner of the accounts. :param str member_id: ID for a member of the accounts. :param str prope...
GetAccounts. Get a list of accounts for a specific owner or a specific member. :param str owner_id: ID for the owner of the accounts. :param str member_id: ID for a member of the accounts. :param str properties: :rtype: [Account]
Below is the the instruction that describes the task: ### Input: GetAccounts. Get a list of accounts for a specific owner or a specific member. :param str owner_id: ID for the owner of the accounts. :param str member_id: ID for a member of the accounts. :param str properties: ...
def run(path, code=None, params=None, **meta): """Check code with pycodestyle. :return list: List of errors. """ parser = get_parser() for option in parser.option_list: if option.dest and option.dest in params: value = params[option.dest] ...
Check code with pycodestyle. :return list: List of errors.
Below is the the instruction that describes the task: ### Input: Check code with pycodestyle. :return list: List of errors. ### Response: def run(path, code=None, params=None, **meta): """Check code with pycodestyle. :return list: List of errors. """ parser = get_parser() ...
def get_departures(self, station): """ Fetch the current departure times from this station http://webservices.ns.nl/ns-api-avt?station=${Naam of afkorting Station} @param station: station to lookup """ url = 'http://webservices.ns.nl/ns-api-avt?station=' + station ...
Fetch the current departure times from this station http://webservices.ns.nl/ns-api-avt?station=${Naam of afkorting Station} @param station: station to lookup
Below is the the instruction that describes the task: ### Input: Fetch the current departure times from this station http://webservices.ns.nl/ns-api-avt?station=${Naam of afkorting Station} @param station: station to lookup ### Response: def get_departures(self, station): """ Fetch ...
def all(self, endpoint, *args, **kwargs): """Retrieve all the data of a paginated endpoint, using GET. :returns: The endpoint unpaginated data :rtype: dict """ # 1. Initialize the pagination parameters. kwargs.setdefault('params', {})['offset'] = 0 kwargs.setdefau...
Retrieve all the data of a paginated endpoint, using GET. :returns: The endpoint unpaginated data :rtype: dict
Below is the the instruction that describes the task: ### Input: Retrieve all the data of a paginated endpoint, using GET. :returns: The endpoint unpaginated data :rtype: dict ### Response: def all(self, endpoint, *args, **kwargs): """Retrieve all the data of a paginated endpoint, using GET...
def __get_boxes(self): """ Get all the word boxes of this page. """ boxfile = self.__box_path try: box_builder = pyocr.builders.LineBoxBuilder() with self.fs.open(boxfile, 'r') as file_desc: boxes = box_builder.read_file(file_desc) ...
Get all the word boxes of this page.
Below is the the instruction that describes the task: ### Input: Get all the word boxes of this page. ### Response: def __get_boxes(self): """ Get all the word boxes of this page. """ boxfile = self.__box_path try: box_builder = pyocr.builders.LineBoxBuilder() ...
def generate_jobs(args, job_list, argument_string): """Generate actual scripts to be submitted to the cluster :param args: argparse argument collection :param job_list: dictionary containing each each job to be submitted :param argument_string: string containing general arguments to be used by mvtest.p...
Generate actual scripts to be submitted to the cluster :param args: argparse argument collection :param job_list: dictionary containing each each job to be submitted :param argument_string: string containing general arguments to be used by mvtest.py during execution :return: None
Below is the the instruction that describes the task: ### Input: Generate actual scripts to be submitted to the cluster :param args: argparse argument collection :param job_list: dictionary containing each each job to be submitted :param argument_string: string containing general arguments to be used b...
def main_dev(**kwargs): """Main entry point. you-get-dev """ # Get (branch, commit) if running from a git repo. head = git.get_head(kwargs['repo_path']) # Get options and arguments. try: opts, args = getopt.getopt(sys.argv[1:], _short_options, _options) except getopt.GetoptErro...
Main entry point. you-get-dev
Below is the the instruction that describes the task: ### Input: Main entry point. you-get-dev ### Response: def main_dev(**kwargs): """Main entry point. you-get-dev """ # Get (branch, commit) if running from a git repo. head = git.get_head(kwargs['repo_path']) # Get options and argum...
def get_conda_root(): """Get the PREFIX of the conda installation. Returns: str: the ROOT_PREFIX of the conda installation """ try: # Fast-path # We're in the root environment conda_root = _import_conda_root() except ImportError: # We're not in the root envir...
Get the PREFIX of the conda installation. Returns: str: the ROOT_PREFIX of the conda installation
Below is the the instruction that describes the task: ### Input: Get the PREFIX of the conda installation. Returns: str: the ROOT_PREFIX of the conda installation ### Response: def get_conda_root(): """Get the PREFIX of the conda installation. Returns: str: the ROOT_PREFIX of the cond...
def get_metadata(self, filename): '''Fetch all available metadata''' dest = self.path(filename) with open(dest, 'rb', buffering=0) as f: checksum = 'sha1:{0}'.format(sha1(f)) return { 'checksum': checksum, 'size': os.path.getsize(dest), 'mi...
Fetch all available metadata
Below is the the instruction that describes the task: ### Input: Fetch all available metadata ### Response: def get_metadata(self, filename): '''Fetch all available metadata''' dest = self.path(filename) with open(dest, 'rb', buffering=0) as f: checksum = 'sha1:{0}'.format(sha1(...
def register(self, target): """Registers url_rules on the blueprint """ for rule, options in self.url_rules: target.add_url_rule(rule, self.name, self.dispatch_request, **options)
Registers url_rules on the blueprint
Below is the the instruction that describes the task: ### Input: Registers url_rules on the blueprint ### Response: def register(self, target): """Registers url_rules on the blueprint """ for rule, options in self.url_rules: target.add_url_rule(rule, self.name, self.dispatch_req...
def _estimate_param_scan_worker(estimator, params, X, evaluate, evaluate_args, failfast, return_exceptions): """ Method that runs estimation for several parameter settings. Defined as a worker for parallelization """ # run estimation model = None try: # catch a...
Method that runs estimation for several parameter settings. Defined as a worker for parallelization
Below is the the instruction that describes the task: ### Input: Method that runs estimation for several parameter settings. Defined as a worker for parallelization ### Response: def _estimate_param_scan_worker(estimator, params, X, evaluate, evaluate_args, failfast, return_exc...
def _user_thread_main(self, target): """Main entry point for the thread that will run user's code.""" try: # Run user's code. return_code = target() # Assume good result (0 return code) if none is returned. if return_code is None: return_co...
Main entry point for the thread that will run user's code.
Below is the the instruction that describes the task: ### Input: Main entry point for the thread that will run user's code. ### Response: def _user_thread_main(self, target): """Main entry point for the thread that will run user's code.""" try: # Run user's code. return_code...
def get_homes(self, query=None, gps_lat=None, gps_lng=None, offset=0, items_per_grid=8): """ Search listings with * Query (e.g. query="Lisbon, Portugal") or * Location (e.g. gps_lat=55.6123352&gps_lng=37.7117917) """ params = { 'is_guided_search': 'tru...
Search listings with * Query (e.g. query="Lisbon, Portugal") or * Location (e.g. gps_lat=55.6123352&gps_lng=37.7117917)
Below is the the instruction that describes the task: ### Input: Search listings with * Query (e.g. query="Lisbon, Portugal") or * Location (e.g. gps_lat=55.6123352&gps_lng=37.7117917) ### Response: def get_homes(self, query=None, gps_lat=None, gps_lng=None, offset=0, items_per_grid=8): ...
def connect( project_id: Optional[str] = None, dataset_id: Optional[str] = None, credentials: Optional[google.auth.credentials.Credentials] = None, ) -> BigQueryClient: """Create a BigQueryClient for use with Ibis. Parameters ---------- project_id : str A BigQuery project id. da...
Create a BigQueryClient for use with Ibis. Parameters ---------- project_id : str A BigQuery project id. dataset_id : str A dataset id that lives inside of the project indicated by `project_id`. credentials : google.auth.credentials.Credentials Returns ------- B...
Below is the the instruction that describes the task: ### Input: Create a BigQueryClient for use with Ibis. Parameters ---------- project_id : str A BigQuery project id. dataset_id : str A dataset id that lives inside of the project indicated by `project_id`. credentials...
def rename_tabs_after_change(self, given_name): """Rename tabs after a change in name.""" client = self.get_current_client() # Prevent renames that want to assign the same name of # a previous tab repeated = False for cl in self.get_clients(): if id(c...
Rename tabs after a change in name.
Below is the the instruction that describes the task: ### Input: Rename tabs after a change in name. ### Response: def rename_tabs_after_change(self, given_name): """Rename tabs after a change in name.""" client = self.get_current_client() # Prevent renames that want to assign the same...
def build_send(self, entity: BaseEntity, from_user: UserType, to_user_key: RsaKey = None) -> Union[str, Dict]: """ Build POST data for sending out to remotes. :param entity: The outbound ready entity for this protocol. :param from_user: The user sending this payload. Must have ``private...
Build POST data for sending out to remotes. :param entity: The outbound ready entity for this protocol. :param from_user: The user sending this payload. Must have ``private_key`` and ``id`` properties. :param to_user_key: (Optional) Public key of user we're sending a private payload to. ...
Below is the the instruction that describes the task: ### Input: Build POST data for sending out to remotes. :param entity: The outbound ready entity for this protocol. :param from_user: The user sending this payload. Must have ``private_key`` and ``id`` properties. :param to_user_key: (Opt...
def update_token(self): """Request a new token and store it for future use""" logger.info('updating token') if None in self.credentials.values(): raise RuntimeError("You must provide an username and a password") credentials = dict(auth=self.credentials) url = self.tes...
Request a new token and store it for future use
Below is the the instruction that describes the task: ### Input: Request a new token and store it for future use ### Response: def update_token(self): """Request a new token and store it for future use""" logger.info('updating token') if None in self.credentials.values(): raise ...
def mesh(self,xyzs): """ Evaluate basis function on a mesh of points *xyz*. """ I,J,K = self.powers d = np.asarray(xyzs,'d')-self.origin # Got help from stackoverflow user @unutbu with this. # See: http://stackoverflow.com/questions/17391052/compute-square-distanc...
Evaluate basis function on a mesh of points *xyz*.
Below is the the instruction that describes the task: ### Input: Evaluate basis function on a mesh of points *xyz*. ### Response: def mesh(self,xyzs): """ Evaluate basis function on a mesh of points *xyz*. """ I,J,K = self.powers d = np.asarray(xyzs,'d')-self.origin ...
def compute_stable_poses(self, center_mass=None, sigma=0.0, n_samples=1, threshold=0.0): """ Computes stable orientations of a mesh and their quasi-static probabilites. This metho...
Computes stable orientations of a mesh and their quasi-static probabilites. This method samples the location of the center of mass from a multivariate gaussian (mean at com, cov equal to identity times sigma) over n_samples. For each sample, it computes the stable resting poses of the mesh on a...
Below is the the instruction that describes the task: ### Input: Computes stable orientations of a mesh and their quasi-static probabilites. This method samples the location of the center of mass from a multivariate gaussian (mean at com, cov equal to identity times sigma) over n_samples. F...
def transform(self, data, centers=None): """ Find entries of all hypercubes. If `centers=None`, then use `self.centers_` as computed in `self.fit`. Empty hypercubes are removed from the result Parameters =========== data: array-like Data to find in ...
Find entries of all hypercubes. If `centers=None`, then use `self.centers_` as computed in `self.fit`. Empty hypercubes are removed from the result Parameters =========== data: array-like Data to find in entries in cube. Warning: first column must be index ...
Below is the the instruction that describes the task: ### Input: Find entries of all hypercubes. If `centers=None`, then use `self.centers_` as computed in `self.fit`. Empty hypercubes are removed from the result Parameters =========== data: array-like ...
def help(self, *args): """ Show help """ res = '' if len(args) == 0: res = 'Help:\n' for name, value in inspect.getmembers(self): if not inspect.isgeneratorfunction(value): continue if name.startswith('_') or (len(args) ...
Show help
Below is the the instruction that describes the task: ### Input: Show help ### Response: def help(self, *args): """ Show help """ res = '' if len(args) == 0: res = 'Help:\n' for name, value in inspect.getmembers(self): if not inspect.isgenerat...
def _make_spec_file(self): """ Customize spec file inserting %config section """ spec_file = setuptools.command.bdist_rpm.bdist_rpm._make_spec_file(self) spec_file.append('%config(noreplace) /etc/lograptor/lograptor.conf') spec_file.append('%config(noreplace) /etc/lograpt...
Customize spec file inserting %config section
Below is the the instruction that describes the task: ### Input: Customize spec file inserting %config section ### Response: def _make_spec_file(self): """ Customize spec file inserting %config section """ spec_file = setuptools.command.bdist_rpm.bdist_rpm._make_spec_file(self) ...
def rename_command(source, destination): """ Executor for `globus rename` """ source_ep, source_path = source dest_ep, dest_path = destination if source_ep != dest_ep: raise click.UsageError( ( "rename requires that the source and dest " "endp...
Executor for `globus rename`
Below is the the instruction that describes the task: ### Input: Executor for `globus rename` ### Response: def rename_command(source, destination): """ Executor for `globus rename` """ source_ep, source_path = source dest_ep, dest_path = destination if source_ep != dest_ep: raise ...
def check_args(args): """ Parse arguments and check if the arguments are valid """ if not os.path.exists(args.fd): print("Not a valid path", args.fd, file=ERROR_LOG) return [], [], False if args.fl is not None: # we already ensure the file can be opened and opened the file ...
Parse arguments and check if the arguments are valid
Below is the the instruction that describes the task: ### Input: Parse arguments and check if the arguments are valid ### Response: def check_args(args): """ Parse arguments and check if the arguments are valid """ if not os.path.exists(args.fd): print("Not a valid path", args.fd, file=ERR...
def _move_files_to_compute(compute, project_id, directory, files_path): """ Move the files to a remote compute """ location = os.path.join(directory, files_path) if os.path.exists(location): for (dirpath, dirnames, filenames) in os.walk(location): for filename in filenames: ...
Move the files to a remote compute
Below is the the instruction that describes the task: ### Input: Move the files to a remote compute ### Response: def _move_files_to_compute(compute, project_id, directory, files_path): """ Move the files to a remote compute """ location = os.path.join(directory, files_path) if os.path.exists(l...
def __get_metrics(self): """ Each metric must have its own filters copy to modify it freely""" esfilters_merge = None esfilters_abandon = None if self.esfilters: esfilters_merge = self.esfilters.copy() esfilters_abandon = self.esfilters.copy() merged = Me...
Each metric must have its own filters copy to modify it freely
Below is the the instruction that describes the task: ### Input: Each metric must have its own filters copy to modify it freely ### Response: def __get_metrics(self): """ Each metric must have its own filters copy to modify it freely""" esfilters_merge = None esfilters_abandon = None ...
def sorted_keywords_by_order(keywords, order): """Sort keywords based on defined order. :param keywords: Keyword to be sorted. :type keywords: dict :param order: Ordered list of key. :type order: list :return: Ordered dictionary based on order list. :rtype: OrderedDict """ # we n...
Sort keywords based on defined order. :param keywords: Keyword to be sorted. :type keywords: dict :param order: Ordered list of key. :type order: list :return: Ordered dictionary based on order list. :rtype: OrderedDict
Below is the the instruction that describes the task: ### Input: Sort keywords based on defined order. :param keywords: Keyword to be sorted. :type keywords: dict :param order: Ordered list of key. :type order: list :return: Ordered dictionary based on order list. :rtype: OrderedDict ### ...
def detectSyntax(self, xmlFileName=None, mimeType=None, language=None, sourceFilePath=None, firstLine=None): """Get syntax by next parameters (fill as many, as known): * name of XML file with sy...
Get syntax by next parameters (fill as many, as known): * name of XML file with syntax definition * MIME type of source file * Programming language name * Source file path * First line of source file First parameter in the list has the hightest prior...
Below is the the instruction that describes the task: ### Input: Get syntax by next parameters (fill as many, as known): * name of XML file with syntax definition * MIME type of source file * Programming language name * Source file path * First line of so...
def retrieve(pdb_id, cache_dir = None, strict = True, parse_ligands = False): '''Creates a PDB object by using a cached copy of the file if it exists or by retrieving the file from the RCSB.''' # Check to see whether we have a cached copy pdb_id = pdb_id.upper() if cache_dir: ...
Creates a PDB object by using a cached copy of the file if it exists or by retrieving the file from the RCSB.
Below is the the instruction that describes the task: ### Input: Creates a PDB object by using a cached copy of the file if it exists or by retrieving the file from the RCSB. ### Response: def retrieve(pdb_id, cache_dir = None, strict = True, parse_ligands = False): '''Creates a PDB object by using a cache...
def _set_port_channel(self, v, load=False): """ Setter method for port_channel, mapped from YANG variable /protocol/spanning_tree/rpvst/port_channel (container) If this variable is read-only (config: false) in the source YANG file, then _set_port_channel is considered as a private method. Backends l...
Setter method for port_channel, mapped from YANG variable /protocol/spanning_tree/rpvst/port_channel (container) If this variable is read-only (config: false) in the source YANG file, then _set_port_channel is considered as a private method. Backends looking to populate this variable should do so via ca...
Below is the the instruction that describes the task: ### Input: Setter method for port_channel, mapped from YANG variable /protocol/spanning_tree/rpvst/port_channel (container) If this variable is read-only (config: false) in the source YANG file, then _set_port_channel is considered as a private metho...
def nsplit(seq, n=2): """ Split a sequence into pieces of length n If the length of the sequence isn't a multiple of n, the rest is discarded. Note that nsplit will split strings into individual characters. Examples: >>> nsplit("aabbcc") [("a", "a"), ("b", "b"), ("c", "c")] >>> nsplit("aab...
Split a sequence into pieces of length n If the length of the sequence isn't a multiple of n, the rest is discarded. Note that nsplit will split strings into individual characters. Examples: >>> nsplit("aabbcc") [("a", "a"), ("b", "b"), ("c", "c")] >>> nsplit("aabbcc",n=3) [("a", "a", "b")...
Below is the the instruction that describes the task: ### Input: Split a sequence into pieces of length n If the length of the sequence isn't a multiple of n, the rest is discarded. Note that nsplit will split strings into individual characters. Examples: >>> nsplit("aabbcc") [("a", "a"), ("b"...
def convert_and_compare_caffe_to_mxnet(image_url, gpu, caffe_prototxt_path, caffe_model_path, caffe_mean, mean_diff_allowed, max_diff_allowed): """ Run the layer comparison on a caffe model, given its prototxt, weights and mean. The comparison is done by inferring on a...
Run the layer comparison on a caffe model, given its prototxt, weights and mean. The comparison is done by inferring on a given image using both caffe and mxnet model :param image_url: image file or url to run inference on :param gpu: gpu to use, -1 for cpu :param caffe_prototxt_path: path to caffe prot...
Below is the the instruction that describes the task: ### Input: Run the layer comparison on a caffe model, given its prototxt, weights and mean. The comparison is done by inferring on a given image using both caffe and mxnet model :param image_url: image file or url to run inference on :param gpu: gpu ...
def speziale_grun(v, v0, gamma0, q0, q1): """ calculate Gruneisen parameter for the Speziale equation :param v: unit-cell volume in A^3 :param v0: unit-cell volume in A^3 at 1 bar :param gamma0: Gruneisen parameter at 1 bar :param q0: logarithmic derivative of Gruneisen parameter :param q1:...
calculate Gruneisen parameter for the Speziale equation :param v: unit-cell volume in A^3 :param v0: unit-cell volume in A^3 at 1 bar :param gamma0: Gruneisen parameter at 1 bar :param q0: logarithmic derivative of Gruneisen parameter :param q1: logarithmic derivative of Gruneisen parameter :re...
Below is the the instruction that describes the task: ### Input: calculate Gruneisen parameter for the Speziale equation :param v: unit-cell volume in A^3 :param v0: unit-cell volume in A^3 at 1 bar :param gamma0: Gruneisen parameter at 1 bar :param q0: logarithmic derivative of Gruneisen parameter...
def insert_many(ol,eles,locs,**kwargs): ''' from elist.elist import * ol = [1,2,3,4,5] eles = [7,77,777] locs = [0,2,4] id(ol) new = insert_many(ol,eles,locs) ol new id(new) #### ol = [1,2,3,4,5] eles = [7,77,777] ...
from elist.elist import * ol = [1,2,3,4,5] eles = [7,77,777] locs = [0,2,4] id(ol) new = insert_many(ol,eles,locs) ol new id(new) #### ol = [1,2,3,4,5] eles = [7,77,777] locs = [0,2,4] id(ol) rslt = insert_ma...
Below is the the instruction that describes the task: ### Input: from elist.elist import * ol = [1,2,3,4,5] eles = [7,77,777] locs = [0,2,4] id(ol) new = insert_many(ol,eles,locs) ol new id(new) #### ol = [1,2,3,4,5] eles = [7,7...
def enable_spi(self): """Set this to `True` to enable the hardware SPI interface. If set to `False` the hardware interface will be disabled and its pins (MISO, MOSI, SCK and SS) can be used as GPIOs. """ config = self._interface_configuration(CONFIG_QUERY) return config =...
Set this to `True` to enable the hardware SPI interface. If set to `False` the hardware interface will be disabled and its pins (MISO, MOSI, SCK and SS) can be used as GPIOs.
Below is the the instruction that describes the task: ### Input: Set this to `True` to enable the hardware SPI interface. If set to `False` the hardware interface will be disabled and its pins (MISO, MOSI, SCK and SS) can be used as GPIOs. ### Response: def enable_spi(self): """Set this to ...
def state(self, state=vanilla.message.NoState): """ Returns a `State`_ `Pair`_. *state* if supplied sets the intial state. """ return vanilla.message.State(self, state=state)
Returns a `State`_ `Pair`_. *state* if supplied sets the intial state.
Below is the the instruction that describes the task: ### Input: Returns a `State`_ `Pair`_. *state* if supplied sets the intial state. ### Response: def state(self, state=vanilla.message.NoState): """ Returns a `State`_ `Pair`_. *state* if supplied sets the intial state. ...
def load(self, *args, **kwargs): """Load the required datasets from the multiple scenes.""" self._generate_scene_func(self._scenes, 'load', False, *args, **kwargs)
Load the required datasets from the multiple scenes.
Below is the the instruction that describes the task: ### Input: Load the required datasets from the multiple scenes. ### Response: def load(self, *args, **kwargs): """Load the required datasets from the multiple scenes.""" self._generate_scene_func(self._scenes, 'load', False, *args, **kwargs)
def add_device(self, device_id): """ Method for `Add device to collection <https://m2x.att.com/developer/documentation/v2/collections#Add-device-to-collection>`_ endpoint. :param device_id: ID of the Device being added to Collection :type device_id: str :raises: :class:`~requests.excep...
Method for `Add device to collection <https://m2x.att.com/developer/documentation/v2/collections#Add-device-to-collection>`_ endpoint. :param device_id: ID of the Device being added to Collection :type device_id: str :raises: :class:`~requests.exceptions.HTTPError` if an error occurs when send...
Below is the the instruction that describes the task: ### Input: Method for `Add device to collection <https://m2x.att.com/developer/documentation/v2/collections#Add-device-to-collection>`_ endpoint. :param device_id: ID of the Device being added to Collection :type device_id: str :raises:...
def get_secure_cookie_key_version( self, name: str, value: str = None ) -> Optional[int]: """Returns the signing key version of the secure cookie. The version is returned as int. """ self.require_setting("cookie_secret", "secure cookies") if value is None: ...
Returns the signing key version of the secure cookie. The version is returned as int.
Below is the the instruction that describes the task: ### Input: Returns the signing key version of the secure cookie. The version is returned as int. ### Response: def get_secure_cookie_key_version( self, name: str, value: str = None ) -> Optional[int]: """Returns the signing key vers...
def write_script(self): """ Write the workflow to a script (.sh instead of .dag). Assuming that parents were added to the DAG before their children, dependencies should be handled correctly. """ if not self.__dag_file_path: raise CondorDAGError, "No path for DAG file" try: dfp =...
Write the workflow to a script (.sh instead of .dag). Assuming that parents were added to the DAG before their children, dependencies should be handled correctly.
Below is the the instruction that describes the task: ### Input: Write the workflow to a script (.sh instead of .dag). Assuming that parents were added to the DAG before their children, dependencies should be handled correctly. ### Response: def write_script(self): """ Write the workflow to a scri...
def long_to_bytes(n, blocksize=0): """long_to_bytes(n:long, blocksize:int) : string Convert a long integer to a byte string. If optional blocksize is given and greater than zero, pad the front of the byte string with binary zeros so that the length is a multiple of blocksize. """ # after mu...
long_to_bytes(n:long, blocksize:int) : string Convert a long integer to a byte string. If optional blocksize is given and greater than zero, pad the front of the byte string with binary zeros so that the length is a multiple of blocksize.
Below is the the instruction that describes the task: ### Input: long_to_bytes(n:long, blocksize:int) : string Convert a long integer to a byte string. If optional blocksize is given and greater than zero, pad the front of the byte string with binary zeros so that the length is a multiple of blocks...
def delete_metadata_at_key(self, key): """ :: DELETE /:login/machines/:id/metadata/:key :param key: identifier for matadata entry :type key: :py:class:`basestring` :Returns: current metadata :rtype: :py:class:`dict` ...
:: DELETE /:login/machines/:id/metadata/:key :param key: identifier for matadata entry :type key: :py:class:`basestring` :Returns: current metadata :rtype: :py:class:`dict` Deletes the machine metadata contained at 'key'. Also expli...
Below is the the instruction that describes the task: ### Input: :: DELETE /:login/machines/:id/metadata/:key :param key: identifier for matadata entry :type key: :py:class:`basestring` :Returns: current metadata :rtype: :py:class:`dict` ...
def to_json(self): """ put the object to json and remove the internal stuff salesking schema stores the type in the title """ data = json.dumps(self) out = u'{"%s":%s}' % (self.schema['title'], data) return out
put the object to json and remove the internal stuff salesking schema stores the type in the title
Below is the the instruction that describes the task: ### Input: put the object to json and remove the internal stuff salesking schema stores the type in the title ### Response: def to_json(self): """ put the object to json and remove the internal stuff salesking schema stores the t...
def insertion_sort(arr, simulation=False): """ Insertion Sort Complexity: O(n^2) """ iteration = 0 if simulation: print("iteration",iteration,":",*arr) for i in range(len(arr)): cursor = arr[i] pos = i while pos > 0 and arr[pos - 1] > cu...
Insertion Sort Complexity: O(n^2)
Below is the the instruction that describes the task: ### Input: Insertion Sort Complexity: O(n^2) ### Response: def insertion_sort(arr, simulation=False): """ Insertion Sort Complexity: O(n^2) """ iteration = 0 if simulation: print("iteration",iteration,":",*arr) ...
def _get_max_name_len(instances): """get max length of Tag:Name""" # FIXME: ec2.instanceCollection doesn't have __len__ for i in instances: return max([len(get_tag_value(i.tags, 'Name')) for i in instances]) return 0
get max length of Tag:Name
Below is the the instruction that describes the task: ### Input: get max length of Tag:Name ### Response: def _get_max_name_len(instances): """get max length of Tag:Name""" # FIXME: ec2.instanceCollection doesn't have __len__ for i in instances: return max([len(get_tag_value(i.tags, 'Name')) fo...
def circle_intersection(self, p: "Point2", r: Union[int, float]) -> Set["Point2"]: """ self is point1, p is point2, r is the radius for circles originating in both points Used in ramp finding """ assert self != p distanceBetweenPoints = self.distance_to(p) assert r > distanceBetw...
self is point1, p is point2, r is the radius for circles originating in both points Used in ramp finding
Below is the the instruction that describes the task: ### Input: self is point1, p is point2, r is the radius for circles originating in both points Used in ramp finding ### Response: def circle_intersection(self, p: "Point2", r: Union[int, float]) -> Set["Point2"]: """ self is point1, p is point2,...
def assign_dna_reads_to_protein_database(query_fasta_fp, database_fasta_fp, output_fp, temp_dir="/tmp", params=None): """Assign DNA reads to a database fasta of protein sequences. Wraps assign_reads_to_database, setting database and query types. All parameters are s...
Assign DNA reads to a database fasta of protein sequences. Wraps assign_reads_to_database, setting database and query types. All parameters are set to default unless params is passed. A temporary file must be written containing the translated sequences from the input query fasta file because BLAT canno...
Below is the the instruction that describes the task: ### Input: Assign DNA reads to a database fasta of protein sequences. Wraps assign_reads_to_database, setting database and query types. All parameters are set to default unless params is passed. A temporary file must be written containing the transl...
def login(provider_id): """Starts the provider login OAuth flow""" provider = get_provider_or_404(provider_id) callback_url = get_authorize_callback('login', provider_id) post_login = request.form.get('next', get_post_login_redirect()) session[config_value('POST_OAUTH_LOGIN_SESSION_KEY')] = post_log...
Starts the provider login OAuth flow
Below is the the instruction that describes the task: ### Input: Starts the provider login OAuth flow ### Response: def login(provider_id): """Starts the provider login OAuth flow""" provider = get_provider_or_404(provider_id) callback_url = get_authorize_callback('login', provider_id) post_login =...
def set_package(fxn): """Set __package__ on the returned module. This function is deprecated. """ @functools.wraps(fxn) def set_package_wrapper(*args, **kwargs): warnings.warn('The import system now takes care of this automatically.', DeprecationWarning, stacklevel=2) ...
Set __package__ on the returned module. This function is deprecated.
Below is the the instruction that describes the task: ### Input: Set __package__ on the returned module. This function is deprecated. ### Response: def set_package(fxn): """Set __package__ on the returned module. This function is deprecated. """ @functools.wraps(fxn) def set_package_wrapper...
def value(self): """Get tensor that the random variable corresponds to.""" if self._value is None: try: self._value = self.distribution.sample(self.sample_shape_tensor()) except NotImplementedError: raise NotImplementedError( "sample is not implemented for {0}. You must e...
Get tensor that the random variable corresponds to.
Below is the the instruction that describes the task: ### Input: Get tensor that the random variable corresponds to. ### Response: def value(self): """Get tensor that the random variable corresponds to.""" if self._value is None: try: self._value = self.distribution.sample(self.sample_shape_t...
def get_pil_mode(value, alpha=False): """Get PIL mode from ColorMode.""" name = { 'GRAYSCALE': 'L', 'BITMAP': '1', 'DUOTONE': 'L', 'INDEXED': 'P', }.get(value, value) if alpha and name in ('L', 'RGB'): name += 'A' return name
Get PIL mode from ColorMode.
Below is the the instruction that describes the task: ### Input: Get PIL mode from ColorMode. ### Response: def get_pil_mode(value, alpha=False): """Get PIL mode from ColorMode.""" name = { 'GRAYSCALE': 'L', 'BITMAP': '1', 'DUOTONE': 'L', 'INDEXED': 'P', }.get(value, val...
def rearrange_pads(pads): """ Interleave pad values to match NNabla format (S0,S1,E0,E1) => (S0,E0,S1,E1)""" half = len(pads)//2 starts = pads[:half] ends = pads[half:] return [j for i in zip(starts, ends) for j in i]
Interleave pad values to match NNabla format (S0,S1,E0,E1) => (S0,E0,S1,E1)
Below is the the instruction that describes the task: ### Input: Interleave pad values to match NNabla format (S0,S1,E0,E1) => (S0,E0,S1,E1) ### Response: def rearrange_pads(pads): """ Interleave pad values to match NNabla format (S0,S1,E0,E1) => (S0,E0,S1,E1)""" half = len(pads)//2 starts = pa...
def elasticsearch(serializer, catalog): """ https://www.elastic.co/guide/en/elasticsearch/reference/current/_the_search_api.html :param serializer: :return: """ search_engine_endpoint = "{0}/{1}/_search".format(SEARCH_URL, catalog.slug) q_text = serializer.validated_data.get("q_text") ...
https://www.elastic.co/guide/en/elasticsearch/reference/current/_the_search_api.html :param serializer: :return:
Below is the the instruction that describes the task: ### Input: https://www.elastic.co/guide/en/elasticsearch/reference/current/_the_search_api.html :param serializer: :return: ### Response: def elasticsearch(serializer, catalog): """ https://www.elastic.co/guide/en/elasticsearch/reference/current...
def send(self, commands): """Send commands to LASAF through CAM-socket. Parameters ---------- commands : list of tuples or bytes string Commands as a list of tuples or a bytes string. cam.prefix is allways prepended before sending. Returns ------...
Send commands to LASAF through CAM-socket. Parameters ---------- commands : list of tuples or bytes string Commands as a list of tuples or a bytes string. cam.prefix is allways prepended before sending. Returns ------- int Bytes sent....
Below is the the instruction that describes the task: ### Input: Send commands to LASAF through CAM-socket. Parameters ---------- commands : list of tuples or bytes string Commands as a list of tuples or a bytes string. cam.prefix is allways prepended before sending....
def get_provider(self): """Gets the ``Resource`` representing the provider. return: (osid.resource.Resource) - the provider raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.* """ if 'providerId' not in self._...
Gets the ``Resource`` representing the provider. return: (osid.resource.Resource) - the provider raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.*
Below is the the instruction that describes the task: ### Input: Gets the ``Resource`` representing the provider. return: (osid.resource.Resource) - the provider raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.* ### Response: d...
def cell(filename=None, mass=None, instrument=None, logging_mode="INFO", cycle_mode=None, auto_summary=True): """Create a CellpyData object""" from cellpy import log log.setup_logging(default_level=logging_mode) cellpy_instance = setup_cellpy_instance() if instrument is not None: ...
Create a CellpyData object
Below is the the instruction that describes the task: ### Input: Create a CellpyData object ### Response: def cell(filename=None, mass=None, instrument=None, logging_mode="INFO", cycle_mode=None, auto_summary=True): """Create a CellpyData object""" from cellpy import log log.setup_logging(de...
def lockFile(self, fileName, byteOffset, length, dokanFileInfo): """Lock a file. :param fileName: name of file to lock :type fileName: ctypes.c_wchar_p :param byteOffset: location to start lock :type byteOffset: ctypes.c_longlong :param length: number of bytes to lock ...
Lock a file. :param fileName: name of file to lock :type fileName: ctypes.c_wchar_p :param byteOffset: location to start lock :type byteOffset: ctypes.c_longlong :param length: number of bytes to lock :type length: ctypes.c_longlong :param dokanFileInfo: used by ...
Below is the the instruction that describes the task: ### Input: Lock a file. :param fileName: name of file to lock :type fileName: ctypes.c_wchar_p :param byteOffset: location to start lock :type byteOffset: ctypes.c_longlong :param length: number of bytes to lock :...
def unlock(): ''' Unlocks the candidate configuration. CLI Example: .. code-block:: bash salt 'device_name' junos.unlock ''' conn = __proxy__['junos.conn']() ret = {} ret['out'] = True try: conn.cu.unlock() ret['message'] = "Successfully unlocked the config...
Unlocks the candidate configuration. CLI Example: .. code-block:: bash salt 'device_name' junos.unlock
Below is the the instruction that describes the task: ### Input: Unlocks the candidate configuration. CLI Example: .. code-block:: bash salt 'device_name' junos.unlock ### Response: def unlock(): ''' Unlocks the candidate configuration. CLI Example: .. code-block:: bash ...
def is_array(self, data_type): '''Check if a type is a known array type Args: data_type (str): Name of type to check Returns: True if ``data_type`` is a known array type. ''' # Split off any brackets data_type = data_type.split('[')[0].strip() return data_type.lower() in s...
Check if a type is a known array type Args: data_type (str): Name of type to check Returns: True if ``data_type`` is a known array type.
Below is the the instruction that describes the task: ### Input: Check if a type is a known array type Args: data_type (str): Name of type to check Returns: True if ``data_type`` is a known array type. ### Response: def is_array(self, data_type): '''Check if a type is a known array typ...