code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def printable_name(column, path=None): """Provided for debug output when rendering conditions. User.name[3]["foo"][0]["bar"] -> name[3].foo[0].bar """ pieces = [column.name] path = path or path_of(column) for segment in path: if isinstance(segment, str): pieces.append(segmen...
Provided for debug output when rendering conditions. User.name[3]["foo"][0]["bar"] -> name[3].foo[0].bar
Below is the the instruction that describes the task: ### Input: Provided for debug output when rendering conditions. User.name[3]["foo"][0]["bar"] -> name[3].foo[0].bar ### Response: def printable_name(column, path=None): """Provided for debug output when rendering conditions. User.name[3]["foo"][0]...
def train(self, s, path="spelling.txt"): """ Counts the words in the given string and saves the probabilities at the given path. This can be used to generate a new model for the Spelling() constructor. """ model = {} for w in re.findall("[a-z]+", s.lower()): model...
Counts the words in the given string and saves the probabilities at the given path. This can be used to generate a new model for the Spelling() constructor.
Below is the the instruction that describes the task: ### Input: Counts the words in the given string and saves the probabilities at the given path. This can be used to generate a new model for the Spelling() constructor. ### Response: def train(self, s, path="spelling.txt"): """ Counts the wor...
def _rr_line(self, section): """Process one line from the text format answer, authority, or additional data sections. """ deleting = None # Name token = self.tok.get(want_leading = True) if not token.is_whitespace(): self.last_name = dns.name.from_tex...
Process one line from the text format answer, authority, or additional data sections.
Below is the the instruction that describes the task: ### Input: Process one line from the text format answer, authority, or additional data sections. ### Response: def _rr_line(self, section): """Process one line from the text format answer, authority, or additional data sections. ...
def get_op(self): """Returns all symmetry operations (including inversions and subtranslations), but unlike get_symop(), they are returned as two ndarrays.""" if self.centrosymmetric: rot = np.tile(np.vstack((self.rotations, -self.rotations)), (self...
Returns all symmetry operations (including inversions and subtranslations), but unlike get_symop(), they are returned as two ndarrays.
Below is the the instruction that describes the task: ### Input: Returns all symmetry operations (including inversions and subtranslations), but unlike get_symop(), they are returned as two ndarrays. ### Response: def get_op(self): """Returns all symmetry operations (including inversions an...
def readerWalker(self): """Create an xmltextReader for a preparsed document. """ ret = libxml2mod.xmlReaderWalker(self._o) if ret is None:raise treeError('xmlReaderWalker() failed') __tmp = xmlTextReader(_obj=ret) return __tmp
Create an xmltextReader for a preparsed document.
Below is the the instruction that describes the task: ### Input: Create an xmltextReader for a preparsed document. ### Response: def readerWalker(self): """Create an xmltextReader for a preparsed document. """ ret = libxml2mod.xmlReaderWalker(self._o) if ret is None:raise treeError('xmlRead...
def mosaicMethod(self, value): """ get/set the mosaic method """ if value in self.__allowedMosaicMethods and \ self._mosaicMethod != value: self._mosaicMethod = value
get/set the mosaic method
Below is the the instruction that describes the task: ### Input: get/set the mosaic method ### Response: def mosaicMethod(self, value): """ get/set the mosaic method """ if value in self.__allowedMosaicMethods and \ self._mosaicMethod != value: self._mosaicMet...
def _parse_peer_address(self, config): """Scans the config block and parses the peer-address value Args: config (str): The config block to scan Returns: dict: A dict object that is intended to be merged into the resource dict """ match = ...
Scans the config block and parses the peer-address value Args: config (str): The config block to scan Returns: dict: A dict object that is intended to be merged into the resource dict
Below is the the instruction that describes the task: ### Input: Scans the config block and parses the peer-address value Args: config (str): The config block to scan Returns: dict: A dict object that is intended to be merged into the resource dict ### Respo...
def intersection(L1, L2): """Intersects two line segments Args: L1 ([float, float]): x and y coordinates L2 ([float, float]): x and y coordinates Returns: bool: if they intersect (float, float): x and y of intersection, if they do """ D = L1[0] * L2[1] - L1[1] * L2[0...
Intersects two line segments Args: L1 ([float, float]): x and y coordinates L2 ([float, float]): x and y coordinates Returns: bool: if they intersect (float, float): x and y of intersection, if they do
Below is the the instruction that describes the task: ### Input: Intersects two line segments Args: L1 ([float, float]): x and y coordinates L2 ([float, float]): x and y coordinates Returns: bool: if they intersect (float, float): x and y of intersection, if they do ### Resp...
def getNonDefaultsDict(self): """ Recursively retrieves values as a dictionary to be used for persistence. Does not save defaultData and other properties, only stores values if they differ from the defaultData. If the CTI and none of its children differ from their default, a ...
Recursively retrieves values as a dictionary to be used for persistence. Does not save defaultData and other properties, only stores values if they differ from the defaultData. If the CTI and none of its children differ from their default, a completely empty dictionary is returned. T...
Below is the the instruction that describes the task: ### Input: Recursively retrieves values as a dictionary to be used for persistence. Does not save defaultData and other properties, only stores values if they differ from the defaultData. If the CTI and none of its children differ from th...
def json_serial(obj): """JSON serializer for objects not serializable by default json code""" if isinstance(obj, LegipyModel): return obj.to_json() elif isinstance(obj, (datetime.date, datetime.datetime)): return obj.isoformat() raise TypeError("Type {0} not serializable".format(repr(typ...
JSON serializer for objects not serializable by default json code
Below is the the instruction that describes the task: ### Input: JSON serializer for objects not serializable by default json code ### Response: def json_serial(obj): """JSON serializer for objects not serializable by default json code""" if isinstance(obj, LegipyModel): return obj.to_json() el...
def add_message(self, text, type=None): """Add a message with an optional type.""" key = self._msg_key self.setdefault(key, []) self[key].append(message(type, text)) self.save()
Add a message with an optional type.
Below is the the instruction that describes the task: ### Input: Add a message with an optional type. ### Response: def add_message(self, text, type=None): """Add a message with an optional type.""" key = self._msg_key self.setdefault(key, []) self[key].append(message(type, text)) ...
def list_projects(root, backend=os.listdir): """List projects at `root` Arguments: root (str): Absolute path to the `be` root directory, typically the current working directory. """ projects = list() for project in sorted(backend(root)): abspath = os.path.join(root, pro...
List projects at `root` Arguments: root (str): Absolute path to the `be` root directory, typically the current working directory.
Below is the the instruction that describes the task: ### Input: List projects at `root` Arguments: root (str): Absolute path to the `be` root directory, typically the current working directory. ### Response: def list_projects(root, backend=os.listdir): """List projects at `root` ...
def _get_snapshot(vm, snapshot_name): """ Returns snapshot object by its name :param vm: :param snapshot_name: :type snapshot_name: str :return: Snapshot by its name :rtype vim.vm.Snapshot """ snapshots = SnapshotRetriever.get_vm_snapshots(vm) ...
Returns snapshot object by its name :param vm: :param snapshot_name: :type snapshot_name: str :return: Snapshot by its name :rtype vim.vm.Snapshot
Below is the the instruction that describes the task: ### Input: Returns snapshot object by its name :param vm: :param snapshot_name: :type snapshot_name: str :return: Snapshot by its name :rtype vim.vm.Snapshot ### Response: def _get_snapshot(vm, snapshot_name): """...
def _constructClient(client_version, username, user_domain, password, project_name, project_domain, auth_url): """Return a novaclient from the given args.""" loader = loading.get_plugin_loader('password') # These only work with v3 if user_domain is not None or p...
Return a novaclient from the given args.
Below is the the instruction that describes the task: ### Input: Return a novaclient from the given args. ### Response: def _constructClient(client_version, username, user_domain, password, project_name, project_domain, auth_url): """Return a novaclient from the given args.""" ...
def get_transactions(self, account_id, **params): """https://developers.coinbase.com/api/v2#list-transactions""" response = self._get('v2', 'accounts', account_id, 'transactions', params=params) return self._make_api_object(response, Transaction)
https://developers.coinbase.com/api/v2#list-transactions
Below is the the instruction that describes the task: ### Input: https://developers.coinbase.com/api/v2#list-transactions ### Response: def get_transactions(self, account_id, **params): """https://developers.coinbase.com/api/v2#list-transactions""" response = self._get('v2', 'accounts', account_id,...
def serialize(pca, **kwargs): """ Serialize an orientation object to a dict suitable for JSON """ strike, dip, rake = pca.strike_dip_rake() hyp_axes = sampling_axes(pca) return dict( **kwargs, principal_axes = pca.axes.tolist(), hyperbolic_axes = hyp_axes.tolist(), ...
Serialize an orientation object to a dict suitable for JSON
Below is the the instruction that describes the task: ### Input: Serialize an orientation object to a dict suitable for JSON ### Response: def serialize(pca, **kwargs): """ Serialize an orientation object to a dict suitable for JSON """ strike, dip, rake = pca.strike_dip_rake() hyp_axes...
def data(self, index, role): """Get the information of the levels.""" if not index.isValid(): return None if role == Qt.FontRole: return self._font label = '' if index.column() == self.model.header_shape[1] - 1: label = str(self.model.n...
Get the information of the levels.
Below is the the instruction that describes the task: ### Input: Get the information of the levels. ### Response: def data(self, index, role): """Get the information of the levels.""" if not index.isValid(): return None if role == Qt.FontRole: return self._font ...
def path_join(*args): """Join path parts to single path.""" return SEP.join((x for x in args if x not in (None, ''))).strip(SEP)
Join path parts to single path.
Below is the the instruction that describes the task: ### Input: Join path parts to single path. ### Response: def path_join(*args): """Join path parts to single path.""" return SEP.join((x for x in args if x not in (None, ''))).strip(SEP)
def on_start(self): """ start publisher """ LOGGER.debug("zeromq.Publisher.on_start") try: self.zmqsocket.bind(self.zmqbind_url) except Exception as e: LOGGER.error("zeromq.Publisher.on_start - error while binding publisher ! " + e.__cause__) ...
start publisher
Below is the the instruction that describes the task: ### Input: start publisher ### Response: def on_start(self): """ start publisher """ LOGGER.debug("zeromq.Publisher.on_start") try: self.zmqsocket.bind(self.zmqbind_url) except Exception as e: ...
def solve(self, value, filter_): """Get slice or entry defined by an index from the given value. Arguments --------- value : ? A value to solve in combination with the given filter. filter_ : dataql.resource.SliceFilter An instance of ``SliceFilter``to so...
Get slice or entry defined by an index from the given value. Arguments --------- value : ? A value to solve in combination with the given filter. filter_ : dataql.resource.SliceFilter An instance of ``SliceFilter``to solve with the given value. Example ...
Below is the the instruction that describes the task: ### Input: Get slice or entry defined by an index from the given value. Arguments --------- value : ? A value to solve in combination with the given filter. filter_ : dataql.resource.SliceFilter An instanc...
def path(self): "Return a list of nodes forming the path from the root to this node." node, path_back = self, [] while node: path_back.append(node) node = node.parent return list(reversed(path_back))
Return a list of nodes forming the path from the root to this node.
Below is the the instruction that describes the task: ### Input: Return a list of nodes forming the path from the root to this node. ### Response: def path(self): "Return a list of nodes forming the path from the root to this node." node, path_back = self, [] while node: path_ba...
def save(self, name, content, max_length=None): """ Saves the given content with the given name using the local storage. If the :attr:`~queued_storage.backends.QueuedStorage.delayed` attribute is ``True`` this will automatically call the :meth:`~queued_storage.backends.QueuedStor...
Saves the given content with the given name using the local storage. If the :attr:`~queued_storage.backends.QueuedStorage.delayed` attribute is ``True`` this will automatically call the :meth:`~queued_storage.backends.QueuedStorage.transfer` method queuing the transfer from local to remo...
Below is the the instruction that describes the task: ### Input: Saves the given content with the given name using the local storage. If the :attr:`~queued_storage.backends.QueuedStorage.delayed` attribute is ``True`` this will automatically call the :meth:`~queued_storage.backends.QueuedSto...
def toProtocolElement(self): """ Returns the GA4GH protocol representation of this ReadGroup. """ # TODO this is very incomplete, but we don't have the # implementation to fill out the rest of the fields currently readGroup = protocol.ReadGroup() readGroup.id = se...
Returns the GA4GH protocol representation of this ReadGroup.
Below is the the instruction that describes the task: ### Input: Returns the GA4GH protocol representation of this ReadGroup. ### Response: def toProtocolElement(self): """ Returns the GA4GH protocol representation of this ReadGroup. """ # TODO this is very incomplete, but we don't ...
def get_assessment_offered(self): """Gets the ``AssessmentOffered``. return: (osid.assessment.AssessmentOffered) - the assessment offered raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.* """ ...
Gets the ``AssessmentOffered``. return: (osid.assessment.AssessmentOffered) - the assessment offered 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 ``AssessmentOffered``. return: (osid.assessment.AssessmentOffered) - the assessment offered raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemente...
def _call_api_single_related_resource(self, resource, full_resource_url, method_name, **kwargs): """ For HypermediaResource - make an API call to a known URL """ url = full_resource_url params = { 'headers': self.get_http_head...
For HypermediaResource - make an API call to a known URL
Below is the the instruction that describes the task: ### Input: For HypermediaResource - make an API call to a known URL ### Response: def _call_api_single_related_resource(self, resource, full_resource_url, method_name, **kwargs): """ For HypermediaResour...
def start_event_stream(self): """ Start streaming events from `gerrit stream-events`. """ if not self._stream: self._stream = GerritStream(self, ssh_client=self._ssh_client) self._stream.start()
Start streaming events from `gerrit stream-events`.
Below is the the instruction that describes the task: ### Input: Start streaming events from `gerrit stream-events`. ### Response: def start_event_stream(self): """ Start streaming events from `gerrit stream-events`. """ if not self._stream: self._stream = GerritStream(self, ssh_client=...
def offsets_for_times(self, timestamps): """Look up the offsets for the given partitions by timestamp. The returned offset for each partition is the earliest offset whose timestamp is greater than or equal to the given timestamp in the corresponding partition. This is a blocking...
Look up the offsets for the given partitions by timestamp. The returned offset for each partition is the earliest offset whose timestamp is greater than or equal to the given timestamp in the corresponding partition. This is a blocking call. The consumer does not have to be assigned the...
Below is the the instruction that describes the task: ### Input: Look up the offsets for the given partitions by timestamp. The returned offset for each partition is the earliest offset whose timestamp is greater than or equal to the given timestamp in the corresponding partition. T...
def decode(cls, value): """ take a utf-8 encoded byte-string from redis and turn it back into a list :param value: bytes :return: list """ try: return None if value is None else \ list(json.loads(value.decode(cls._encoding))) e...
take a utf-8 encoded byte-string from redis and turn it back into a list :param value: bytes :return: list
Below is the the instruction that describes the task: ### Input: take a utf-8 encoded byte-string from redis and turn it back into a list :param value: bytes :return: list ### Response: def decode(cls, value): """ take a utf-8 encoded byte-string from redis and turn...
def get_extra_restriction(self, where_class, alias, remote_alias): """ Overrides ForeignObject's get_extra_restriction function that returns an SQL statement which is appended to a JOIN's conditional filtering part :return: SQL conditional statement :rtype: WhereNode ...
Overrides ForeignObject's get_extra_restriction function that returns an SQL statement which is appended to a JOIN's conditional filtering part :return: SQL conditional statement :rtype: WhereNode
Below is the the instruction that describes the task: ### Input: Overrides ForeignObject's get_extra_restriction function that returns an SQL statement which is appended to a JOIN's conditional filtering part :return: SQL conditional statement :rtype: WhereNode ### Response: def ge...
def updateReplicationMetadataResponse( self, pid, replicaMetadata, serialVersion, vendorSpecific=None ): """CNReplication.updateReplicationMetadata(session, pid, replicaMetadata, serialVersion) → boolean https://releases.dataone.org/online/api- documentation-v2.0.1/apis/CN_AP Is.html...
CNReplication.updateReplicationMetadata(session, pid, replicaMetadata, serialVersion) → boolean https://releases.dataone.org/online/api- documentation-v2.0.1/apis/CN_AP Is.html#CNReplication.updateReplicationMetadata Not implemented. Args: pid: replicaMetadata: ...
Below is the the instruction that describes the task: ### Input: CNReplication.updateReplicationMetadata(session, pid, replicaMetadata, serialVersion) → boolean https://releases.dataone.org/online/api- documentation-v2.0.1/apis/CN_AP Is.html#CNReplication.updateReplicationMetadata Not implem...
def make_bitransformer( input_vocab_size=gin.REQUIRED, output_vocab_size=gin.REQUIRED, layout=None, mesh_shape=None): """Gin-configurable bitransformer constructor. In your config file you need to set the encoder and decoder layers like this: encoder/make_layer_stack.layers = [ @transformer_l...
Gin-configurable bitransformer constructor. In your config file you need to set the encoder and decoder layers like this: encoder/make_layer_stack.layers = [ @transformer_layers.SelfAttention, @transformer_layers.DenseReluDense, ] decoder/make_layer_stack.layers = [ @transformer_layers.SelfAttentio...
Below is the the instruction that describes the task: ### Input: Gin-configurable bitransformer constructor. In your config file you need to set the encoder and decoder layers like this: encoder/make_layer_stack.layers = [ @transformer_layers.SelfAttention, @transformer_layers.DenseReluDense, ] dec...
def _process_irrational_functions(self, functions, predetermined_function_addrs, blockaddr_to_function): """ For unresolveable indirect jumps, angr marks those jump targets as individual functions. For example, usually the following pattern is seen: sub_0x400010: push ebp ...
For unresolveable indirect jumps, angr marks those jump targets as individual functions. For example, usually the following pattern is seen: sub_0x400010: push ebp mov esp, ebp ... cmp eax, 10 ja end mov eax, jumptable[eax] ...
Below is the the instruction that describes the task: ### Input: For unresolveable indirect jumps, angr marks those jump targets as individual functions. For example, usually the following pattern is seen: sub_0x400010: push ebp mov esp, ebp ... cmp e...
def _register_user_models(user_models, admin=None, schema=None): """Register any user-defined models with the API Service. :param list user_models: A list of user-defined models to include in the API service """ if any([issubclass(cls, AutomapModel) for cls in user_models])...
Register any user-defined models with the API Service. :param list user_models: A list of user-defined models to include in the API service
Below is the the instruction that describes the task: ### Input: Register any user-defined models with the API Service. :param list user_models: A list of user-defined models to include in the API service ### Response: def _register_user_models(user_models, admin=None, schema=None...
def sum_fields(layer, output_field_key, input_fields): """Sum the value of input_fields and put it as output_field. :param layer: The vector layer. :type layer: QgsVectorLayer :param output_field_key: The output field definition key. :type output_field_key: basestring :param input_fields: Lis...
Sum the value of input_fields and put it as output_field. :param layer: The vector layer. :type layer: QgsVectorLayer :param output_field_key: The output field definition key. :type output_field_key: basestring :param input_fields: List of input fields' name. :type input_fields: list
Below is the the instruction that describes the task: ### Input: Sum the value of input_fields and put it as output_field. :param layer: The vector layer. :type layer: QgsVectorLayer :param output_field_key: The output field definition key. :type output_field_key: basestring :param input_fiel...
def acl_required(permission, context): """Returns a decorator that checks if a user has the requested permission from the passed acl context. This function constructs a decorator that can be used to check a aiohttp's view for authorization before calling it. It uses the get_permission() function to...
Returns a decorator that checks if a user has the requested permission from the passed acl context. This function constructs a decorator that can be used to check a aiohttp's view for authorization before calling it. It uses the get_permission() function to check the request against the passed permissi...
Below is the the instruction that describes the task: ### Input: Returns a decorator that checks if a user has the requested permission from the passed acl context. This function constructs a decorator that can be used to check a aiohttp's view for authorization before calling it. It uses the get_permi...
def user_config_dir(): r"""Return the per-user config dir (full path). - Linux, *BSD, SunOS: ~/.config/glances - macOS: ~/Library/Application Support/glances - Windows: %APPDATA%\glances """ if WINDOWS: path = os.environ.get('APPDATA') elif MACOS: path = os.path.expanduser('...
r"""Return the per-user config dir (full path). - Linux, *BSD, SunOS: ~/.config/glances - macOS: ~/Library/Application Support/glances - Windows: %APPDATA%\glances
Below is the the instruction that describes the task: ### Input: r"""Return the per-user config dir (full path). - Linux, *BSD, SunOS: ~/.config/glances - macOS: ~/Library/Application Support/glances - Windows: %APPDATA%\glances ### Response: def user_config_dir(): r"""Return the per-user config d...
def ziparchive_opener(path, pattern='', verbose=False): """Opener that opens files from zip archive.. :param str path: Path. :param str pattern: Regular expression pattern. :return: Filehandle(s). """ with zipfile.ZipFile(io.BytesIO(urlopen(path).read()), 'r') if is_url(path) else zipfile.ZipFi...
Opener that opens files from zip archive.. :param str path: Path. :param str pattern: Regular expression pattern. :return: Filehandle(s).
Below is the the instruction that describes the task: ### Input: Opener that opens files from zip archive.. :param str path: Path. :param str pattern: Regular expression pattern. :return: Filehandle(s). ### Response: def ziparchive_opener(path, pattern='', verbose=False): """Opener that opens file...
def create_socks_endpoint(self, reactor, socks_config): """ Creates a new TorSocksEndpoint instance given a valid configuration line for ``SocksPort``; if this configuration isn't already in the underlying tor, we add it. Note that this method may call :meth:`txtorcon.TorConfig.s...
Creates a new TorSocksEndpoint instance given a valid configuration line for ``SocksPort``; if this configuration isn't already in the underlying tor, we add it. Note that this method may call :meth:`txtorcon.TorConfig.save()` on this instance. Note that calling this with `socks_config=...
Below is the the instruction that describes the task: ### Input: Creates a new TorSocksEndpoint instance given a valid configuration line for ``SocksPort``; if this configuration isn't already in the underlying tor, we add it. Note that this method may call :meth:`txtorcon.TorConfig.save()` ...
def __set_svd(self): """private method to set SVD components. Note: this should not be called directly """ if self.isdiagonal: x = np.diag(self.x.flatten()) else: # just a pointer to x x = self.x try: u, s, v = la.svd(x, ...
private method to set SVD components. Note: this should not be called directly
Below is the the instruction that describes the task: ### Input: private method to set SVD components. Note: this should not be called directly ### Response: def __set_svd(self): """private method to set SVD components. Note: this should not be called directly """ if self...
def get_jid(jid): ''' Return the information returned from a specified jid ''' log.debug('sqlite3 returner <get_jid> called jid: %s', jid) conn = _get_conn(ret=None) cur = conn.cursor() sql = '''SELECT id, full_ret FROM salt_returns WHERE jid = :jid''' cur.execute(sql, {'...
Return the information returned from a specified jid
Below is the the instruction that describes the task: ### Input: Return the information returned from a specified jid ### Response: def get_jid(jid): ''' Return the information returned from a specified jid ''' log.debug('sqlite3 returner <get_jid> called jid: %s', jid) conn = _get_conn(ret=Non...
def _resolve_array_type(self): """Return one of the ARRAY_TYPES members of DIMENSION_TYPE. This method distinguishes between CA and MR dimensions. The return value is only meaningful if the dimension is known to be of array type (i.e. either CA or MR, base-type 'enum.variable'). ...
Return one of the ARRAY_TYPES members of DIMENSION_TYPE. This method distinguishes between CA and MR dimensions. The return value is only meaningful if the dimension is known to be of array type (i.e. either CA or MR, base-type 'enum.variable').
Below is the the instruction that describes the task: ### Input: Return one of the ARRAY_TYPES members of DIMENSION_TYPE. This method distinguishes between CA and MR dimensions. The return value is only meaningful if the dimension is known to be of array type (i.e. either CA or MR, base-typ...
def add_params(endpoint, params): """ Combine query endpoint and params. Example:: >>> add_params("https://www.google.com/search", {"q": "iphone"}) https://www.google.com/search?q=iphone """ p = PreparedRequest() p.prepare(url=endpoint, params=params) if PY2: # pragma: no ...
Combine query endpoint and params. Example:: >>> add_params("https://www.google.com/search", {"q": "iphone"}) https://www.google.com/search?q=iphone
Below is the the instruction that describes the task: ### Input: Combine query endpoint and params. Example:: >>> add_params("https://www.google.com/search", {"q": "iphone"}) https://www.google.com/search?q=iphone ### Response: def add_params(endpoint, params): """ Combine query endpo...
def first(self): """Attempt to retrieve only the first resource matching this request. :return: Result instance, or `None` if there are no matching resources. """ self.params['limit'] = 1 result = self.all() return result.items[0] if result.total > 0 else None
Attempt to retrieve only the first resource matching this request. :return: Result instance, or `None` if there are no matching resources.
Below is the the instruction that describes the task: ### Input: Attempt to retrieve only the first resource matching this request. :return: Result instance, or `None` if there are no matching resources. ### Response: def first(self): """Attempt to retrieve only the first resource matching this re...
def get_pixels_on_line(self, x1, y1, x2, y2, getvalues=True): """Uses Bresenham's line algorithm to enumerate the pixels along a line. (see http://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm) If `getvalues`==False then it will return tuples of (x, y) coordinates instead o...
Uses Bresenham's line algorithm to enumerate the pixels along a line. (see http://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm) If `getvalues`==False then it will return tuples of (x, y) coordinates instead of pixel values.
Below is the the instruction that describes the task: ### Input: Uses Bresenham's line algorithm to enumerate the pixels along a line. (see http://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm) If `getvalues`==False then it will return tuples of (x, y) coordinates instead of pi...
def asn(self, ip, announce_date=None): """ Give an IP, maybe a date, get the ASN. This is the fastest command. :param ip: IP address to search for :param announce_date: Date of the announcement :rtype: String, ASN. """ assignations, ...
Give an IP, maybe a date, get the ASN. This is the fastest command. :param ip: IP address to search for :param announce_date: Date of the announcement :rtype: String, ASN.
Below is the the instruction that describes the task: ### Input: Give an IP, maybe a date, get the ASN. This is the fastest command. :param ip: IP address to search for :param announce_date: Date of the announcement :rtype: String, ASN. ### Response: def asn(self, ...
def alignmentPanelHTML(titlesAlignments, sortOn='maxScore', outputDir=None, idList=False, equalizeXAxes=False, xRange='subject', logLinearXAxis=False, logBase=DEFAULT_LOG_LINEAR_X_AXIS_BASE, rankScores=False, showFeatures=True, ...
Produces an HTML index file in C{outputDir} and a collection of alignment graphs and FASTA files to summarize the information in C{titlesAlignments}. @param titlesAlignments: A L{dark.titles.TitlesAlignments} instance. @param sortOn: The attribute to sort subplots on. Either "maxScore", "medianScor...
Below is the the instruction that describes the task: ### Input: Produces an HTML index file in C{outputDir} and a collection of alignment graphs and FASTA files to summarize the information in C{titlesAlignments}. @param titlesAlignments: A L{dark.titles.TitlesAlignments} instance. @param sortOn: The ...
def crossValidation(self,seed=0,n_folds=10,fullVector=True,verbose=None,D=None,**keywords): """ Split the dataset in n folds, predict each fold after training the model on all the others Args: seed: seed n_folds: number of folds to train the model on ...
Split the dataset in n folds, predict each fold after training the model on all the others Args: seed: seed n_folds: number of folds to train the model on fullVector: Bolean indicator, if true it stops if no convergence is observed for one of the folds, otherwise...
Below is the the instruction that describes the task: ### Input: Split the dataset in n folds, predict each fold after training the model on all the others Args: seed: seed n_folds: number of folds to train the model on fullVector: Bolean indicator, if true i...
def encode_request(name, expected, updated): """ Encode request into client_message""" client_message = ClientMessage(payload_size=calculate_size(name, expected, updated)) client_message.set_message_type(REQUEST_TYPE) client_message.set_retryable(RETRYABLE) client_message.append_str(name) client...
Encode request into client_message
Below is the the instruction that describes the task: ### Input: Encode request into client_message ### Response: def encode_request(name, expected, updated): """ Encode request into client_message""" client_message = ClientMessage(payload_size=calculate_size(name, expected, updated)) client_message.se...
def _check_contraint(self, edge1, edge2): """Check if two edges satisfy vine constraint. Args: :param edge1: edge object representing edge1 :param edge2: edge object representing edge2 :type edge1: Edge object :type edge2: Edge object Returns: ...
Check if two edges satisfy vine constraint. Args: :param edge1: edge object representing edge1 :param edge2: edge object representing edge2 :type edge1: Edge object :type edge2: Edge object Returns: Boolean True if the two edges satisfy vine ...
Below is the the instruction that describes the task: ### Input: Check if two edges satisfy vine constraint. Args: :param edge1: edge object representing edge1 :param edge2: edge object representing edge2 :type edge1: Edge object :type edge2: Edge object ...
def _xfs_prune_output(out, uuid): ''' Parse prune output. ''' data = {} cnt = [] cutpoint = False for line in [l.strip() for l in out.split("\n") if l]: if line.startswith("-"): if cutpoint: break else: cutpoint = True ...
Parse prune output.
Below is the the instruction that describes the task: ### Input: Parse prune output. ### Response: def _xfs_prune_output(out, uuid): ''' Parse prune output. ''' data = {} cnt = [] cutpoint = False for line in [l.strip() for l in out.split("\n") if l]: if line.startswith("-"): ...
def symb_to_block(symb, coupling = 'full'): """ Maps a symbolic factorization to a block-diagonal structure with coupling constraints. :param symb: :py:class:`symbolic` :param coupling: optional :return dims: list of block dimensions :return sparse_to_b...
Maps a symbolic factorization to a block-diagonal structure with coupling constraints. :param symb: :py:class:`symbolic` :param coupling: optional :return dims: list of block dimensions :return sparse_to_block: dictionary :return constraints: list o...
Below is the the instruction that describes the task: ### Input: Maps a symbolic factorization to a block-diagonal structure with coupling constraints. :param symb: :py:class:`symbolic` :param coupling: optional :return dims: list of block dimensions :retur...
def has_add_permission(self, request): """ Can add this object """ return request.user.is_authenticated and request.user.is_active and request.user.is_staff
Can add this object
Below is the the instruction that describes the task: ### Input: Can add this object ### Response: def has_add_permission(self, request): """ Can add this object """ return request.user.is_authenticated and request.user.is_active and request.user.is_staff
def drop(self, relation): """Drop the named relation and cascade it appropriately to all dependent relations. Because dbt proactively does many `drop relation if exist ... cascade` that are noops, nonexistent relation drops cause a debug log and no other actions. :param...
Drop the named relation and cascade it appropriately to all dependent relations. Because dbt proactively does many `drop relation if exist ... cascade` that are noops, nonexistent relation drops cause a debug log and no other actions. :param str schema: The schema of the relati...
Below is the the instruction that describes the task: ### Input: Drop the named relation and cascade it appropriately to all dependent relations. Because dbt proactively does many `drop relation if exist ... cascade` that are noops, nonexistent relation drops cause a debug log and no ...
def _as_decode(self, msg): """AS: Arming status report.""" return {'armed_statuses': [x for x in msg[4:12]], 'arm_up_states': [x for x in msg[12:20]], 'alarm_states': [x for x in msg[20:28]]}
AS: Arming status report.
Below is the the instruction that describes the task: ### Input: AS: Arming status report. ### Response: def _as_decode(self, msg): """AS: Arming status report.""" return {'armed_statuses': [x for x in msg[4:12]], 'arm_up_states': [x for x in msg[12:20]], 'alarm_stat...
def grab_checksums_file(entry): """Grab the checksum file for a given entry.""" http_url = convert_ftp_url(entry['ftp_path']) full_url = '{}/md5checksums.txt'.format(http_url) req = requests.get(full_url) return req.text
Grab the checksum file for a given entry.
Below is the the instruction that describes the task: ### Input: Grab the checksum file for a given entry. ### Response: def grab_checksums_file(entry): """Grab the checksum file for a given entry.""" http_url = convert_ftp_url(entry['ftp_path']) full_url = '{}/md5checksums.txt'.format(http_url) re...
def verify_token_string(self, token_string, action=None, timeout=None, current_time=None): """Generate a hash of the given token contents that can be verified. :param token_string: ...
Generate a hash of the given token contents that can be verified. :param token_string: A string containing the hashed token (generated by `generate_token_string`). :param action: A string containing the action that is being verified. :param timeout: ...
Below is the the instruction that describes the task: ### Input: Generate a hash of the given token contents that can be verified. :param token_string: A string containing the hashed token (generated by `generate_token_string`). :param action: A string containing...
def validate_reference(self, reference: ReferenceDefinitionType) -> Optional[Path]: """ Converts reference to :class:`Path <pathlib.Path>` :raise ValueError: If ``reference`` can't be converted to :class:`Path <pathlib.Path>`. """ if reference is not None: if isinstance(refe...
Converts reference to :class:`Path <pathlib.Path>` :raise ValueError: If ``reference`` can't be converted to :class:`Path <pathlib.Path>`.
Below is the the instruction that describes the task: ### Input: Converts reference to :class:`Path <pathlib.Path>` :raise ValueError: If ``reference`` can't be converted to :class:`Path <pathlib.Path>`. ### Response: def validate_reference(self, reference: ReferenceDefinitionType) -> Optional[Path]: ...
def listpid(toggle='basic'): # Add method to exclude elements from list '''list pids''' proc=psutil.process_iter()# evalute if its better to keep one instance of this or generate here? if toggle=='basic': host=gethostname() host2=os.getenv('HOME').split(sep='/' )[-1] for row in pro...
list pids
Below is the the instruction that describes the task: ### Input: list pids ### Response: def listpid(toggle='basic'): # Add method to exclude elements from list '''list pids''' proc=psutil.process_iter()# evalute if its better to keep one instance of this or generate here? if toggle=='basic': h...
def extract_segment_types(urml_document_element, namespace): """Return a map from segment node IDs to their segment type ('nucleus', 'satellite' or 'isolated'). """ segment_types = \ {namespace+':'+seg.attrib['id']: seg.tag for seg in urml_document_element.iter('nucleus', 'satellite')} ...
Return a map from segment node IDs to their segment type ('nucleus', 'satellite' or 'isolated').
Below is the the instruction that describes the task: ### Input: Return a map from segment node IDs to their segment type ('nucleus', 'satellite' or 'isolated'). ### Response: def extract_segment_types(urml_document_element, namespace): """Return a map from segment node IDs to their segment type ('nucl...
def set_display(self, brightness=100, brightness_mode="auto"): """ allows to modify display state (change brightness) :param int brightness: display brightness [0, 100] (default: 100) :param str brightness_mode: the brightness mode of the display [aut...
allows to modify display state (change brightness) :param int brightness: display brightness [0, 100] (default: 100) :param str brightness_mode: the brightness mode of the display [auto, manual] (default: auto)
Below is the the instruction that describes the task: ### Input: allows to modify display state (change brightness) :param int brightness: display brightness [0, 100] (default: 100) :param str brightness_mode: the brightness mode of the display [auto, manual] (de...
def get_dsl_by_hash(self, node_hash: str) -> Optional[BaseEntity]: """Look up a node by the hash and returns the corresponding PyBEL node tuple.""" node = self.get_node_by_hash(node_hash) if node is not None: return node.as_bel()
Look up a node by the hash and returns the corresponding PyBEL node tuple.
Below is the the instruction that describes the task: ### Input: Look up a node by the hash and returns the corresponding PyBEL node tuple. ### Response: def get_dsl_by_hash(self, node_hash: str) -> Optional[BaseEntity]: """Look up a node by the hash and returns the corresponding PyBEL node tuple.""" ...
def _render_hs_label(self, hs): """Return the label of the given Hilbert space as a string""" if isinstance(hs.__class__, Singleton): return self._render_str(hs.label) else: return self._tensor_sym.join( [self._render_str(ls.label) for ls in hs.local_facto...
Return the label of the given Hilbert space as a string
Below is the the instruction that describes the task: ### Input: Return the label of the given Hilbert space as a string ### Response: def _render_hs_label(self, hs): """Return the label of the given Hilbert space as a string""" if isinstance(hs.__class__, Singleton): return self._rende...
def keyUp(key, pause=None, _pause=True): """Performs a keyboard key release (without the press down beforehand). Args: key (str): The key to be released up. The valid names are listed in KEYBOARD_KEYS. Returns: None """ if len(key) > 1: key = key.lower() _failSafeChe...
Performs a keyboard key release (without the press down beforehand). Args: key (str): The key to be released up. The valid names are listed in KEYBOARD_KEYS. Returns: None
Below is the the instruction that describes the task: ### Input: Performs a keyboard key release (without the press down beforehand). Args: key (str): The key to be released up. The valid names are listed in KEYBOARD_KEYS. Returns: None ### Response: def keyUp(key, pause=None, _pause=Tr...
def write(histogram): """Convert a histogram to a protobuf message. Note: Currently, all binnings are converted to static form. When you load the histogram again, you will lose any related behaviour. Note: A histogram collection is also planned. Parameters ---------- histogram...
Convert a histogram to a protobuf message. Note: Currently, all binnings are converted to static form. When you load the histogram again, you will lose any related behaviour. Note: A histogram collection is also planned. Parameters ---------- histogram : HistogramBase | list | dic...
Below is the the instruction that describes the task: ### Input: Convert a histogram to a protobuf message. Note: Currently, all binnings are converted to static form. When you load the histogram again, you will lose any related behaviour. Note: A histogram collection is also planned. ...
def print_usage(self, file=None): """ Outputs usage information to the file if specified, or to the io_manager's stdout if available, or to sys.stdout. """ optparse.OptionParser.print_usage(self, file) file.flush()
Outputs usage information to the file if specified, or to the io_manager's stdout if available, or to sys.stdout.
Below is the the instruction that describes the task: ### Input: Outputs usage information to the file if specified, or to the io_manager's stdout if available, or to sys.stdout. ### Response: def print_usage(self, file=None): """ Outputs usage information to the file if specified, or to th...
def _set_categories_on_workflow(global_workflow_id, categories_to_set): """ Note: Categories are set on the workflow series level, i.e. the same set applies to all versions. """ assert(isinstance(categories_to_set, list)) existing_categories = dxpy.api.global_workflow_list_categories(global_wor...
Note: Categories are set on the workflow series level, i.e. the same set applies to all versions.
Below is the the instruction that describes the task: ### Input: Note: Categories are set on the workflow series level, i.e. the same set applies to all versions. ### Response: def _set_categories_on_workflow(global_workflow_id, categories_to_set): """ Note: Categories are set on the workflow series le...
def has_arrlist(type_str): """ A predicate that matches a type string with an array dimension list. """ try: abi_type = grammar.parse(type_str) except exceptions.ParseError: return False return abi_type.arrlist is not None
A predicate that matches a type string with an array dimension list.
Below is the the instruction that describes the task: ### Input: A predicate that matches a type string with an array dimension list. ### Response: def has_arrlist(type_str): """ A predicate that matches a type string with an array dimension list. """ try: abi_type = grammar.parse(type_str)...
def add_voice_call_api(mock): '''Add org.ofono.VoiceCallManager API to a mock''' # also add an emergency number which is not a real one, in case one runs a # test case against a production ofono :-) mock.AddProperty('org.ofono.VoiceCallManager', 'EmergencyNumbers', ['911', '13373']) mock.calls = [...
Add org.ofono.VoiceCallManager API to a mock
Below is the the instruction that describes the task: ### Input: Add org.ofono.VoiceCallManager API to a mock ### Response: def add_voice_call_api(mock): '''Add org.ofono.VoiceCallManager API to a mock''' # also add an emergency number which is not a real one, in case one runs a # test case against a ...
def cache_factor(self, col_list, refresh=False): """ Existing todos here are: these should be hidden helper carrays As in: not normal columns that you would normally see as a user The factor (label index) carray is as long as the original carray (and the rest of the table theref...
Existing todos here are: these should be hidden helper carrays As in: not normal columns that you would normally see as a user The factor (label index) carray is as long as the original carray (and the rest of the table therefore) But the (unique) values carray is not as long (as long a...
Below is the the instruction that describes the task: ### Input: Existing todos here are: these should be hidden helper carrays As in: not normal columns that you would normally see as a user The factor (label index) carray is as long as the original carray (and the rest of the table theref...
def make_library(self, diffuse_yaml, catalog_yaml, binning_yaml): """ Build up the library of all the components Parameters ---------- diffuse_yaml : str Name of the yaml file with the library of diffuse component definitions catalog_yaml : str Name of t...
Build up the library of all the components Parameters ---------- diffuse_yaml : str Name of the yaml file with the library of diffuse component definitions catalog_yaml : str Name of the yaml file width the library of catalog split definitions binning_ya...
Below is the the instruction that describes the task: ### Input: Build up the library of all the components Parameters ---------- diffuse_yaml : str Name of the yaml file with the library of diffuse component definitions catalog_yaml : str Name of the yaml f...
def remove_all_containers(self, stop_timeout=10, list_only=False): """ First stops (if necessary) and them removes all containers present on the Docker instance. :param stop_timeout: Timeout to stopping each container. :type stop_timeout: int :param list_only: When set to ``True...
First stops (if necessary) and them removes all containers present on the Docker instance. :param stop_timeout: Timeout to stopping each container. :type stop_timeout: int :param list_only: When set to ``True`` only lists containers, but does not actually stop or remove them. :type list...
Below is the the instruction that describes the task: ### Input: First stops (if necessary) and them removes all containers present on the Docker instance. :param stop_timeout: Timeout to stopping each container. :type stop_timeout: int :param list_only: When set to ``True`` only lists cont...
def apply_augments(self, auglist, p_elem, pset): """Handle substatements of augments from `auglist`. The augments are applied in the context of `p_elem`. `pset` is a patch set containing patches that may be applicable to descendants. """ for a in auglist: pa...
Handle substatements of augments from `auglist`. The augments are applied in the context of `p_elem`. `pset` is a patch set containing patches that may be applicable to descendants.
Below is the the instruction that describes the task: ### Input: Handle substatements of augments from `auglist`. The augments are applied in the context of `p_elem`. `pset` is a patch set containing patches that may be applicable to descendants. ### Response: def apply_augments(self, aug...
def split_line(line, min_line_length=30, max_line_length=100): """ This is designed to work with prettified output from Beautiful Soup which indents with a single space. :param line: The line to split :param min_line_length: The minimum desired line length :param max_line_length: The maximum desire...
This is designed to work with prettified output from Beautiful Soup which indents with a single space. :param line: The line to split :param min_line_length: The minimum desired line length :param max_line_length: The maximum desired line length :return: A list of lines
Below is the the instruction that describes the task: ### Input: This is designed to work with prettified output from Beautiful Soup which indents with a single space. :param line: The line to split :param min_line_length: The minimum desired line length :param max_line_length: The maximum desired line...
def checkForChanges(f, sde, isTable): """ returns False if there are no changes """ # try simple feature count first fCount = int(arcpy.GetCount_management(f).getOutput(0)) sdeCount = int(arcpy.GetCount_management(sde).getOutput(0)) if fCount != sdeCount: return True fields = [...
returns False if there are no changes
Below is the the instruction that describes the task: ### Input: returns False if there are no changes ### Response: def checkForChanges(f, sde, isTable): """ returns False if there are no changes """ # try simple feature count first fCount = int(arcpy.GetCount_management(f).getOutput(0)) ...
def sync_remote_to_local(force="no"): """ Replace your remote db with your local Example: sync_remote_to_local:force=yes """ assert "local_wp_dir" in env, "Missing local_wp_dir in env" if force != "yes": message = "This will replace your local database with your "\ ...
Replace your remote db with your local Example: sync_remote_to_local:force=yes
Below is the the instruction that describes the task: ### Input: Replace your remote db with your local Example: sync_remote_to_local:force=yes ### Response: def sync_remote_to_local(force="no"): """ Replace your remote db with your local Example: sync_remote_to_local:force=yes ...
def Run(self, unused_arg): """Run the kill.""" # Send a message back to the service to say that we are about to shutdown. reply = rdf_flows.GrrStatus(status=rdf_flows.GrrStatus.ReturnedStatus.OK) # Queue up the response message, jump the queue. self.SendReply(reply, message_type=rdf_flows.GrrMessage...
Run the kill.
Below is the the instruction that describes the task: ### Input: Run the kill. ### Response: def Run(self, unused_arg): """Run the kill.""" # Send a message back to the service to say that we are about to shutdown. reply = rdf_flows.GrrStatus(status=rdf_flows.GrrStatus.ReturnedStatus.OK) # Queue up...
def set_description(self, description, lang='en'): """ Set the description for a WD item in a certain language :param description: The description of the item in a certain language :type description: str :param lang: The language a description should be set for. :type lan...
Set the description for a WD item in a certain language :param description: The description of the item in a certain language :type description: str :param lang: The language a description should be set for. :type lang: str :return: None
Below is the the instruction that describes the task: ### Input: Set the description for a WD item in a certain language :param description: The description of the item in a certain language :type description: str :param lang: The language a description should be set for. :type lang:...
def get_gradebook_ids_by_gradebook_column(self, gradebook_column_id): """Gets the list of ``Gradebook`` ``Ids`` mapped to a ``GradebookColumn``. arg: gradebook_column_id (osid.id.Id): ``Id`` of a ``GradebookColumn`` return: (osid.id.IdList) - list of gradebook ``Ids`` ...
Gets the list of ``Gradebook`` ``Ids`` mapped to a ``GradebookColumn``. arg: gradebook_column_id (osid.id.Id): ``Id`` of a ``GradebookColumn`` return: (osid.id.IdList) - list of gradebook ``Ids`` raise: NotFound - ``gradebook_column_id`` is not found raise: NullArg...
Below is the the instruction that describes the task: ### Input: Gets the list of ``Gradebook`` ``Ids`` mapped to a ``GradebookColumn``. arg: gradebook_column_id (osid.id.Id): ``Id`` of a ``GradebookColumn`` return: (osid.id.IdList) - list of gradebook ``Ids`` raise: No...
def polish(commit_indexes=None, urls=None): ''' Apply certain behaviors to commits or URLs that need polishing before they are ready for screenshots For example, if you have 10 commits in a row where static file links were broken, you could re-write the html in memory as it is interpreted. Keyword...
Apply certain behaviors to commits or URLs that need polishing before they are ready for screenshots For example, if you have 10 commits in a row where static file links were broken, you could re-write the html in memory as it is interpreted. Keyword arguments: commit_indexes -- A list of indexes to a...
Below is the the instruction that describes the task: ### Input: Apply certain behaviors to commits or URLs that need polishing before they are ready for screenshots For example, if you have 10 commits in a row where static file links were broken, you could re-write the html in memory as it is interpreted....
def _partition_runs_by_day(self): """Split the runs by day, so we can display them grouped that way.""" run_infos = self._get_all_run_infos() for x in run_infos: ts = float(x['timestamp']) x['time_of_day_text'] = datetime.fromtimestamp(ts).strftime('%H:%M:%S') def date_text(dt): delta...
Split the runs by day, so we can display them grouped that way.
Below is the the instruction that describes the task: ### Input: Split the runs by day, so we can display them grouped that way. ### Response: def _partition_runs_by_day(self): """Split the runs by day, so we can display them grouped that way.""" run_infos = self._get_all_run_infos() for x in run_infos...
def get_short_status(self, hosts, services): """Get the short status of this host :return: "O", "W", "C", "U', or "n/a" based on service state_id or business_rule state :rtype: str """ mapping = { 0: "O", 1: "W", 2: "C", 3: "U", ...
Get the short status of this host :return: "O", "W", "C", "U', or "n/a" based on service state_id or business_rule state :rtype: str
Below is the the instruction that describes the task: ### Input: Get the short status of this host :return: "O", "W", "C", "U', or "n/a" based on service state_id or business_rule state :rtype: str ### Response: def get_short_status(self, hosts, services): """Get the short status of this h...
def get(self, transform=None): """ Return the JSON defined at the S3 location in the constructor. The get method will reload the S3 object after the TTL has expired. Fetch the JSON object from cache or S3 if necessary """ if not self.has_expired() and self._cache...
Return the JSON defined at the S3 location in the constructor. The get method will reload the S3 object after the TTL has expired. Fetch the JSON object from cache or S3 if necessary
Below is the the instruction that describes the task: ### Input: Return the JSON defined at the S3 location in the constructor. The get method will reload the S3 object after the TTL has expired. Fetch the JSON object from cache or S3 if necessary ### Response: def get(self, transform=None...
def set_iscsi_boot_info(self, mac, target_name, lun, ip_address, port='3260', auth_method=None, username=None, password=None): """Set iscsi details of the system in uefi boot mode. The initiator system is set with the target details like I...
Set iscsi details of the system in uefi boot mode. The initiator system is set with the target details like IQN, LUN, IP, Port etc. :param mac: The MAC of the NIC to be set with iSCSI information :param target_name: Target Name for iscsi. :param lun: logical unit number. ...
Below is the the instruction that describes the task: ### Input: Set iscsi details of the system in uefi boot mode. The initiator system is set with the target details like IQN, LUN, IP, Port etc. :param mac: The MAC of the NIC to be set with iSCSI information :param target_name: Ta...
def totals(iter, keyfunc, sumfunc): """groups items by field described in keyfunc and counts totals using value from sumfunc """ data = sorted(iter, key=keyfunc) res = {} for k, group in groupby(data, keyfunc): res[k] = sum([sumfunc(entry) for entry in group]) return res
groups items by field described in keyfunc and counts totals using value from sumfunc
Below is the the instruction that describes the task: ### Input: groups items by field described in keyfunc and counts totals using value from sumfunc ### Response: def totals(iter, keyfunc, sumfunc): """groups items by field described in keyfunc and counts totals using value from sumfunc """...
def is_restricted(self): """ Returns True or False according to number of objects in queryset. If queryset contains too much objects the widget will be restricted and won't be used select box with choices. """ return ( not hasattr(self.choices, 'queryset') or ...
Returns True or False according to number of objects in queryset. If queryset contains too much objects the widget will be restricted and won't be used select box with choices.
Below is the the instruction that describes the task: ### Input: Returns True or False according to number of objects in queryset. If queryset contains too much objects the widget will be restricted and won't be used select box with choices. ### Response: def is_restricted(self): """ Return...
def azimuth(self, point): """ Compute the azimuth (in decimal degrees) between this point and the given point. :param point: Destination point. :type point: Instance of :class:`Point` :returns: The azimuth, value in a range ``[0, 360)`...
Compute the azimuth (in decimal degrees) between this point and the given point. :param point: Destination point. :type point: Instance of :class:`Point` :returns: The azimuth, value in a range ``[0, 360)``. :rtype: float
Below is the the instruction that describes the task: ### Input: Compute the azimuth (in decimal degrees) between this point and the given point. :param point: Destination point. :type point: Instance of :class:`Point` :returns: The azimuth, value...
def write_version(path, ref=None): """Update version file using git desribe""" with lcd(dirname(path)): version = make_version(ref) if (env.get('full') or not os.path.exists(path) or version != open(path).read().strip()): with open(path, 'w') as out: out.write(version...
Update version file using git desribe
Below is the the instruction that describes the task: ### Input: Update version file using git desribe ### Response: def write_version(path, ref=None): """Update version file using git desribe""" with lcd(dirname(path)): version = make_version(ref) if (env.get('full') or not os.path.exists(path...
def real_space(self): """The space corresponding to this space's `real_dtype`. Raises ------ ValueError If `dtype` is not a numeric data type. """ if not is_numeric_dtype(self.dtype): raise ValueError( '`real_space` not defined for...
The space corresponding to this space's `real_dtype`. Raises ------ ValueError If `dtype` is not a numeric data type.
Below is the the instruction that describes the task: ### Input: The space corresponding to this space's `real_dtype`. Raises ------ ValueError If `dtype` is not a numeric data type. ### Response: def real_space(self): """The space corresponding to this space's `real_dt...
def _ast_to_code(self, node, **kwargs): """Convert an abstract syntax tree to python source code.""" if isinstance(node, OptreeNode): return self._ast_optree_node_to_code(node, **kwargs) elif isinstance(node, Identifier): return self._ast_identifier_to_code(node, **kwargs) elif isinstance(no...
Convert an abstract syntax tree to python source code.
Below is the the instruction that describes the task: ### Input: Convert an abstract syntax tree to python source code. ### Response: def _ast_to_code(self, node, **kwargs): """Convert an abstract syntax tree to python source code.""" if isinstance(node, OptreeNode): return self._ast_optree_node_to_c...
def get_role_members(self, role): """get permissions of a user""" targetRoleDb = AuthGroup.objects(creator=self.client, role=role) members = AuthMembership.objects(groups__in=targetRoleDb).only('user') return json.loads(members.to_json())
get permissions of a user
Below is the the instruction that describes the task: ### Input: get permissions of a user ### Response: def get_role_members(self, role): """get permissions of a user""" targetRoleDb = AuthGroup.objects(creator=self.client, role=role) members = AuthMembership.objects(groups__in=targetRoleD...
def load(cls, path): """ load DictTree from json files. """ try: with open(path, "rb") as f: return cls(__data__=json.loads(f.read().decode("utf-8"))) except: pass with open(path, "rb") as f: return cls(__data__=pickle....
load DictTree from json files.
Below is the the instruction that describes the task: ### Input: load DictTree from json files. ### Response: def load(cls, path): """ load DictTree from json files. """ try: with open(path, "rb") as f: return cls(__data__=json.loads(f.read().decode("utf-...
def handle_signature(self, sig, signode): """Parses out pieces from construct signatures Parses out prefix and argument list from construct definition. This is assuming that the .NET languages this will support will be in a common format, such as:: Namespace.Class.method(ar...
Parses out pieces from construct signatures Parses out prefix and argument list from construct definition. This is assuming that the .NET languages this will support will be in a common format, such as:: Namespace.Class.method(argument, argument, ...) The namespace and cla...
Below is the the instruction that describes the task: ### Input: Parses out pieces from construct signatures Parses out prefix and argument list from construct definition. This is assuming that the .NET languages this will support will be in a common format, such as:: Namespace...
def maintain_leases(self): """Maintain all of the leases being managed. This method modifies the ack deadline for all of the managed ack IDs, then waits for most of that time (but with jitter), and repeats. """ while self._manager.is_active and not self._stop_event.is_se...
Maintain all of the leases being managed. This method modifies the ack deadline for all of the managed ack IDs, then waits for most of that time (but with jitter), and repeats.
Below is the the instruction that describes the task: ### Input: Maintain all of the leases being managed. This method modifies the ack deadline for all of the managed ack IDs, then waits for most of that time (but with jitter), and repeats. ### Response: def maintain_leases(self): ...
def from_dict(d): """ Re-create the noise model from a dictionary representation. :param Dict[str,Any] d: The dictionary representation. :return: The restored noise model. :rtype: NoiseModel """ return NoiseModel( gates=[KrausModel.from_dict(t) for t ...
Re-create the noise model from a dictionary representation. :param Dict[str,Any] d: The dictionary representation. :return: The restored noise model. :rtype: NoiseModel
Below is the the instruction that describes the task: ### Input: Re-create the noise model from a dictionary representation. :param Dict[str,Any] d: The dictionary representation. :return: The restored noise model. :rtype: NoiseModel ### Response: def from_dict(d): """ Re-c...
def eof(): '''Parser EOF flag of a string.''' @Parser def eof_parser(text, index=0): if index >= len(text): return Value.success(index, None) else: return Value.failure(index, 'EOF') return eof_parser
Parser EOF flag of a string.
Below is the the instruction that describes the task: ### Input: Parser EOF flag of a string. ### Response: def eof(): '''Parser EOF flag of a string.''' @Parser def eof_parser(text, index=0): if index >= len(text): return Value.success(index, None) else: return ...
def tops(symbols=None, token='', version=''): '''TOPS provides IEX’s aggregated best quoted bid and offer position in near real time for all securities on IEX’s displayed limit order book. TOPS is ideal for developers needing both quote and trade data. https://iexcloud.io/docs/api/#tops Args: ...
TOPS provides IEX’s aggregated best quoted bid and offer position in near real time for all securities on IEX’s displayed limit order book. TOPS is ideal for developers needing both quote and trade data. https://iexcloud.io/docs/api/#tops Args: symbol (string); Ticker to request token (str...
Below is the the instruction that describes the task: ### Input: TOPS provides IEX’s aggregated best quoted bid and offer position in near real time for all securities on IEX’s displayed limit order book. TOPS is ideal for developers needing both quote and trade data. https://iexcloud.io/docs/api/#tops ...
def embeddable(self, path, variant): """Is the asset embeddable ?""" name, ext = os.path.splitext(path) font = ext in FONT_EXTS if not variant: return False if not (re.search(settings.EMBED_PATH, path.replace('\\', '/')) and self.storage.exists(path)): ret...
Is the asset embeddable ?
Below is the the instruction that describes the task: ### Input: Is the asset embeddable ? ### Response: def embeddable(self, path, variant): """Is the asset embeddable ?""" name, ext = os.path.splitext(path) font = ext in FONT_EXTS if not variant: return False i...
def left_corner_label(self, label, position=None, rotation=0, offset=0.08, **kwargs): """ Sets the label on the left corner (complements right axis.) Parameters ---------- label: string The axis label position: 3-Tuple of floats, Non...
Sets the label on the left corner (complements right axis.) Parameters ---------- label: string The axis label position: 3-Tuple of floats, None The position of the text label rotation: float, 0 The angle of rotation of the label offse...
Below is the the instruction that describes the task: ### Input: Sets the label on the left corner (complements right axis.) Parameters ---------- label: string The axis label position: 3-Tuple of floats, None The position of the text label rotation: ...
def get_slot_bindings(self): """ Returns slot bindings. :returns: slot bindings (adapter names) list """ slot_bindings = yield from self._hypervisor.send('vm slot_bindings "{}"'.format(self._name)) return slot_bindings
Returns slot bindings. :returns: slot bindings (adapter names) list
Below is the the instruction that describes the task: ### Input: Returns slot bindings. :returns: slot bindings (adapter names) list ### Response: def get_slot_bindings(self): """ Returns slot bindings. :returns: slot bindings (adapter names) list """ slot_binding...
def twisted_consume(callback, bindings=None, queues=None): """ Start a consumer using the provided callback and run it using the Twisted event loop (reactor). .. note:: Callbacks run in a Twisted-managed thread pool using the :func:`twisted.internet.threads.deferToThread` API to avoid them bloc...
Start a consumer using the provided callback and run it using the Twisted event loop (reactor). .. note:: Callbacks run in a Twisted-managed thread pool using the :func:`twisted.internet.threads.deferToThread` API to avoid them blocking the event loop. If you wish to use Twisted APIs in your ca...
Below is the the instruction that describes the task: ### Input: Start a consumer using the provided callback and run it using the Twisted event loop (reactor). .. note:: Callbacks run in a Twisted-managed thread pool using the :func:`twisted.internet.threads.deferToThread` API to avoid them blocki...