code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def wp_loop(self): '''close the loop on a mission''' loader = self.wploader if loader.count() < 2: print("Not enough waypoints (%u)" % loader.count()) return wp = loader.wp(loader.count()-2) if wp.command == mavutil.mavlink.MAV_CMD_DO_JUMP: pri...
close the loop on a mission
Below is the the instruction that describes the task: ### Input: close the loop on a mission ### Response: def wp_loop(self): '''close the loop on a mission''' loader = self.wploader if loader.count() < 2: print("Not enough waypoints (%u)" % loader.count()) return ...
def conv3x3(in_planes, out_planes, fn, stride=1): """3x3 convolution with padding""" return fn(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False)
3x3 convolution with padding
Below is the the instruction that describes the task: ### Input: 3x3 convolution with padding ### Response: def conv3x3(in_planes, out_planes, fn, stride=1): """3x3 convolution with padding""" return fn(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False)
def list_images(self): # type: () -> List[str] """ List images stored in the registry. Returns: list[str]: List of image names. """ r = self.get(self.registry_url + '/v2/_catalog', auth=self.auth) return r.json()['repositories']
List images stored in the registry. Returns: list[str]: List of image names.
Below is the the instruction that describes the task: ### Input: List images stored in the registry. Returns: list[str]: List of image names. ### Response: def list_images(self): # type: () -> List[str] """ List images stored in the registry. Returns: list[...
def term_to_binary(term, compressed=False): """ Encode Python types into Erlang terms in binary data """ data_uncompressed = _term_to_binary(term) if compressed is False: return b_chr(_TAG_VERSION) + data_uncompressed else: if compressed is True: compressed = 6 ...
Encode Python types into Erlang terms in binary data
Below is the the instruction that describes the task: ### Input: Encode Python types into Erlang terms in binary data ### Response: def term_to_binary(term, compressed=False): """ Encode Python types into Erlang terms in binary data """ data_uncompressed = _term_to_binary(term) if compressed is...
def extractParamMap(self, extra=None): """ Extracts the embedded default param values and user-supplied values, and then merges them with extra values from input into a flat param map, where the latter value is used if there exist conflicts, i.e., with ordering: default param val...
Extracts the embedded default param values and user-supplied values, and then merges them with extra values from input into a flat param map, where the latter value is used if there exist conflicts, i.e., with ordering: default param values < user-supplied values < extra. :param...
Below is the the instruction that describes the task: ### Input: Extracts the embedded default param values and user-supplied values, and then merges them with extra values from input into a flat param map, where the latter value is used if there exist conflicts, i.e., with ordering: default...
def _int_to_words(self, pattern): """ Given a bit-pattern expressed an integer number, return a sequence of the individual words that make up the pattern. The number of bits per word will be obtained from the internal SPI interface. """ try: bits_required = in...
Given a bit-pattern expressed an integer number, return a sequence of the individual words that make up the pattern. The number of bits per word will be obtained from the internal SPI interface.
Below is the the instruction that describes the task: ### Input: Given a bit-pattern expressed an integer number, return a sequence of the individual words that make up the pattern. The number of bits per word will be obtained from the internal SPI interface. ### Response: def _int_to_words(self, p...
def com_google_fonts_check_metadata_normal_style(ttFont, font_metadata): """METADATA.pb font.style "normal" matches font internals?""" from fontbakery.utils import get_name_entry_strings from fontbakery.constants import MacStyle if font_metadata.style != "normal": yield SKIP, "This check only applies to no...
METADATA.pb font.style "normal" matches font internals?
Below is the the instruction that describes the task: ### Input: METADATA.pb font.style "normal" matches font internals? ### Response: def com_google_fonts_check_metadata_normal_style(ttFont, font_metadata): """METADATA.pb font.style "normal" matches font internals?""" from fontbakery.utils import get_name_ent...
def get_context_data(self, **kwargs): """ Add filter form to the context. TODO: Currently we construct the filter form object twice - in get_queryset and here, in get_context_data. Will need to figure out a good way to eliminate extra initialization. """ context ...
Add filter form to the context. TODO: Currently we construct the filter form object twice - in get_queryset and here, in get_context_data. Will need to figure out a good way to eliminate extra initialization.
Below is the the instruction that describes the task: ### Input: Add filter form to the context. TODO: Currently we construct the filter form object twice - in get_queryset and here, in get_context_data. Will need to figure out a good way to eliminate extra initialization. ### Response: de...
def send(self, xso): """ Send a single XML stream object. :param xso: Object to serialise and send. :type xso: :class:`aioxmpp.xso.XSO` :raises Exception: from any serialisation errors, usually :class:`ValueError`. Serialise the `xso` and send...
Send a single XML stream object. :param xso: Object to serialise and send. :type xso: :class:`aioxmpp.xso.XSO` :raises Exception: from any serialisation errors, usually :class:`ValueError`. Serialise the `xso` and send it over the stream. If any serialisation...
Below is the the instruction that describes the task: ### Input: Send a single XML stream object. :param xso: Object to serialise and send. :type xso: :class:`aioxmpp.xso.XSO` :raises Exception: from any serialisation errors, usually :class:`ValueError`. ...
def start_dashboard(redis_address, temp_dir, stdout_file=None, stderr_file=None, redis_password=None): """Start a dashboard process. Args: redis_address (str): The address of the Redis instance. temp_dir (str): The ...
Start a dashboard process. Args: redis_address (str): The address of the Redis instance. temp_dir (str): The temporary directory used for log files and information for this Ray session. stdout_file: A file handle opened for writing to redirect stdout to. If no redire...
Below is the the instruction that describes the task: ### Input: Start a dashboard process. Args: redis_address (str): The address of the Redis instance. temp_dir (str): The temporary directory used for log files and information for this Ray session. stdout_file: A file hand...
def phase_from_frequencyseries(htilde, remove_start_phase=True): """Returns the phase from the given frequency-domain waveform. This assumes that the waveform has been sampled finely enough that the phase cannot change by more than pi radians between each step. Parameters ---------- htilde : Fr...
Returns the phase from the given frequency-domain waveform. This assumes that the waveform has been sampled finely enough that the phase cannot change by more than pi radians between each step. Parameters ---------- htilde : FrequencySeries The waveform to get the phase for; must be a compl...
Below is the the instruction that describes the task: ### Input: Returns the phase from the given frequency-domain waveform. This assumes that the waveform has been sampled finely enough that the phase cannot change by more than pi radians between each step. Parameters ---------- htilde : Frequ...
def func_globals_inject(func, **overrides): ''' Override specific variables within a function's global context. ''' # recognize methods if hasattr(func, 'im_func'): func = func.__func__ # Get a reference to the function globals dictionary func_globals = func.__globals__ # Save t...
Override specific variables within a function's global context.
Below is the the instruction that describes the task: ### Input: Override specific variables within a function's global context. ### Response: def func_globals_inject(func, **overrides): ''' Override specific variables within a function's global context. ''' # recognize methods if hasattr(func,...
def n_frames_total(self, stride=1, skip=0): r"""Returns total number of frames. Parameters ---------- stride : int return value is the number of frames in trajectories when running through them with a step size of `stride`. skip : int, default=0 ...
r"""Returns total number of frames. Parameters ---------- stride : int return value is the number of frames in trajectories when running through them with a step size of `stride`. skip : int, default=0 skip the first initial n frames per trajectory. ...
Below is the the instruction that describes the task: ### Input: r"""Returns total number of frames. Parameters ---------- stride : int return value is the number of frames in trajectories when running through them with a step size of `stride`. skip : int, de...
def populate(projects_to_filter=None, group=None): """ Populate the list of projects that belong to this experiment. Args: projects_to_filter (list(Project)): List of projects we want to assign to this experiment. We intersect the list of projects with the list of supported ...
Populate the list of projects that belong to this experiment. Args: projects_to_filter (list(Project)): List of projects we want to assign to this experiment. We intersect the list of projects with the list of supported projects to get the list of projects that belong to...
Below is the the instruction that describes the task: ### Input: Populate the list of projects that belong to this experiment. Args: projects_to_filter (list(Project)): List of projects we want to assign to this experiment. We intersect the list of projects with the list of supp...
def copy_submission_locally(self, cloud_path): """Copies submission from Google Cloud Storage to local directory. Args: cloud_path: path of the submission in Google Cloud Storage Returns: name of the local file where submission is copied to """ local_path = os.path.join(self.download_d...
Copies submission from Google Cloud Storage to local directory. Args: cloud_path: path of the submission in Google Cloud Storage Returns: name of the local file where submission is copied to
Below is the the instruction that describes the task: ### Input: Copies submission from Google Cloud Storage to local directory. Args: cloud_path: path of the submission in Google Cloud Storage Returns: name of the local file where submission is copied to ### Response: def copy_submission_loc...
def calculate(self, order, transaction): """ Pay commission based on dollar value of shares. """ cost_per_share = transaction.price * self.cost_per_dollar return abs(transaction.amount) * cost_per_share
Pay commission based on dollar value of shares.
Below is the the instruction that describes the task: ### Input: Pay commission based on dollar value of shares. ### Response: def calculate(self, order, transaction): """ Pay commission based on dollar value of shares. """ cost_per_share = transaction.price * self.cost_per_dollar ...
def get_ntlmv2_response(domain, user, password, server_challenge, client_challenge, timestamp, target_info): """ [MS-NLMP] v20140502 NT LAN Manager (NTLM) Authentication Protocol 3.3.2 NTLM v2 Authentication Computes an appropriate NTLMv2 response. The algorithm is based on jCIFS and th...
[MS-NLMP] v20140502 NT LAN Manager (NTLM) Authentication Protocol 3.3.2 NTLM v2 Authentication Computes an appropriate NTLMv2 response. The algorithm is based on jCIFS and the ComputeResponse() implementation the protocol documentation. Note: The MS ComputeResponse() implementation refe...
Below is the the instruction that describes the task: ### Input: [MS-NLMP] v20140502 NT LAN Manager (NTLM) Authentication Protocol 3.3.2 NTLM v2 Authentication Computes an appropriate NTLMv2 response. The algorithm is based on jCIFS and the ComputeResponse() implementation the protocol docu...
def get_prediction_results(model_dir_or_id, data, headers, img_cols=None, cloud=False, with_source=True, show_image=True): """ Predict with a specified model. It predicts with the model, join source data with prediction results, and formats the results so they can be displayed nicely i...
Predict with a specified model. It predicts with the model, join source data with prediction results, and formats the results so they can be displayed nicely in Datalab. Args: model_dir_or_id: The model directory if cloud is False, or model.version if cloud is True. data: Can be a list of dictionaries, ...
Below is the the instruction that describes the task: ### Input: Predict with a specified model. It predicts with the model, join source data with prediction results, and formats the results so they can be displayed nicely in Datalab. Args: model_dir_or_id: The model directory if cloud is False, or mode...
def get_history_item_for_tree_iter(self, child_tree_iter): """Hands history item for tree iter and compensate if tree item is a dummy item :param Gtk.TreeIter child_tree_iter: Tree iter of row :rtype rafcon.core.execution.execution_history.HistoryItem: :return history tree item: ...
Hands history item for tree iter and compensate if tree item is a dummy item :param Gtk.TreeIter child_tree_iter: Tree iter of row :rtype rafcon.core.execution.execution_history.HistoryItem: :return history tree item:
Below is the the instruction that describes the task: ### Input: Hands history item for tree iter and compensate if tree item is a dummy item :param Gtk.TreeIter child_tree_iter: Tree iter of row :rtype rafcon.core.execution.execution_history.HistoryItem: :return history tree item: ### Resp...
def itable(*args, **kwargs): ''' itable(...) yields a new immutable table object from the given set of arguments. The arguments may be any number of maps or itables followed by any number of keyword arguments. All the entries from the arguments and keywords are collapsed left-to-right (respecting la...
itable(...) yields a new immutable table object from the given set of arguments. The arguments may be any number of maps or itables followed by any number of keyword arguments. All the entries from the arguments and keywords are collapsed left-to-right (respecting laziness), and the resulting column s...
Below is the the instruction that describes the task: ### Input: itable(...) yields a new immutable table object from the given set of arguments. The arguments may be any number of maps or itables followed by any number of keyword arguments. All the entries from the arguments and keywords are collapsed ...
def create(cls, statement_format, date_start, date_end, monetary_account_id=None, regional_format=None, custom_headers=None): """ :type user_id: int :type monetary_account_id: int :param statement_format: The format type of statement. Allowed values: ...
:type user_id: int :type monetary_account_id: int :param statement_format: The format type of statement. Allowed values: MT940, CSV, PDF. :type statement_format: str :param date_start: The start date for making statements. :type date_start: str :param date_end: Th...
Below is the the instruction that describes the task: ### Input: :type user_id: int :type monetary_account_id: int :param statement_format: The format type of statement. Allowed values: MT940, CSV, PDF. :type statement_format: str :param date_start: The start date for making ...
def post(self, request, *args, **kwargs): """ Method for handling POST requests. Validates submitted form and formsets. Saves if valid, re displays page with errors if invalid. """ self.object = self.get_object() form_class = self.get_form_class() ...
Method for handling POST requests. Validates submitted form and formsets. Saves if valid, re displays page with errors if invalid.
Below is the the instruction that describes the task: ### Input: Method for handling POST requests. Validates submitted form and formsets. Saves if valid, re displays page with errors if invalid. ### Response: def post(self, request, *args, **kwargs): """ Method for handling...
def file_add(backend, kitchen, recipe, message, filepath): """ Add a newly created file to a Recipe """ err_str, use_kitchen = Backend.get_kitchen_from_user(kitchen) if use_kitchen is None: raise click.ClickException(err_str) if recipe is None: recipe = DKRecipeDisk.find_recipe_n...
Add a newly created file to a Recipe
Below is the the instruction that describes the task: ### Input: Add a newly created file to a Recipe ### Response: def file_add(backend, kitchen, recipe, message, filepath): """ Add a newly created file to a Recipe """ err_str, use_kitchen = Backend.get_kitchen_from_user(kitchen) if use_kitche...
def send_photo(self, chat_id, photo, caption=None, reply_to_message_id=None, reply_markup=None): """ Use this method to send photos. On success, the sent Message is returned. """ self.logger.info('send photo %s', photo) payload = dict(chat_id=chat_id, c...
Use this method to send photos. On success, the sent Message is returned.
Below is the the instruction that describes the task: ### Input: Use this method to send photos. On success, the sent Message is returned. ### Response: def send_photo(self, chat_id, photo, caption=None, reply_to_message_id=None, reply_markup=None): """ Use this method to send photos. On succes...
def convert_to_str(l: Node) -> str: """ converts the non-negative number list into a string. """ result = "" while l: result += str(l.val) l = l.next return result
converts the non-negative number list into a string.
Below is the the instruction that describes the task: ### Input: converts the non-negative number list into a string. ### Response: def convert_to_str(l: Node) -> str: """ converts the non-negative number list into a string. """ result = "" while l: result += str(l.val) l = ...
def download(self): """Download SRA files. Returns: :obj:`list` of :obj:`str`: List of downloaded files. """ self.downloaded_paths = list() for path in self.paths_for_download: downloaded_path = list() utils.mkdir_p(os.path.abspath(self.direct...
Download SRA files. Returns: :obj:`list` of :obj:`str`: List of downloaded files.
Below is the the instruction that describes the task: ### Input: Download SRA files. Returns: :obj:`list` of :obj:`str`: List of downloaded files. ### Response: def download(self): """Download SRA files. Returns: :obj:`list` of :obj:`str`: List of downloaded files....
def pad_to_size(data, shape, value=0.0): """ This is similar to `pad`, except you specify the final shape of the array. Parameters ---------- data : ndarray Numpy array of any dimension and type. shape : tuple Final shape of padded array. Should be tuple of length ``data.ndim``....
This is similar to `pad`, except you specify the final shape of the array. Parameters ---------- data : ndarray Numpy array of any dimension and type. shape : tuple Final shape of padded array. Should be tuple of length ``data.ndim``. If it has to pad unevenly, it will pad one m...
Below is the the instruction that describes the task: ### Input: This is similar to `pad`, except you specify the final shape of the array. Parameters ---------- data : ndarray Numpy array of any dimension and type. shape : tuple Final shape of padded array. Should be tuple of lengt...
def sym(self, nested_scope=None): """Return the correspond symbolic number.""" operation = self.children[0].operation() expr = self.children[1].sym(nested_scope) return operation(expr)
Return the correspond symbolic number.
Below is the the instruction that describes the task: ### Input: Return the correspond symbolic number. ### Response: def sym(self, nested_scope=None): """Return the correspond symbolic number.""" operation = self.children[0].operation() expr = self.children[1].sym(nested_scope) ret...
def get_running(): ''' Return a list of all running services, so far as systemd is concerned CLI Example: .. code-block:: bash salt '*' service.get_running ''' ret = set() # Get running systemd units out = __salt__['cmd.run']( _systemctl_cmd('--full --no-legend --no-pa...
Return a list of all running services, so far as systemd is concerned CLI Example: .. code-block:: bash salt '*' service.get_running
Below is the the instruction that describes the task: ### Input: Return a list of all running services, so far as systemd is concerned CLI Example: .. code-block:: bash salt '*' service.get_running ### Response: def get_running(): ''' Return a list of all running services, so far as syst...
def get_profile_form(): """ Returns the profile form defined by ``settings.ACCOUNTS_PROFILE_FORM_CLASS``. """ from yacms.conf import settings try: return import_dotted_path(settings.ACCOUNTS_PROFILE_FORM_CLASS) except ImportError: raise ImproperlyConfigured("Value for ACCOUNT...
Returns the profile form defined by ``settings.ACCOUNTS_PROFILE_FORM_CLASS``.
Below is the the instruction that describes the task: ### Input: Returns the profile form defined by ``settings.ACCOUNTS_PROFILE_FORM_CLASS``. ### Response: def get_profile_form(): """ Returns the profile form defined by ``settings.ACCOUNTS_PROFILE_FORM_CLASS``. """ from yacms.conf import s...
def set_dhcp_only_all(interface): ''' Configure specified adapter to use DHCP only Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the settings were applied, otherwise an exception will be thr...
Configure specified adapter to use DHCP only Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the settings were applied, otherwise an exception will be thrown. :rtype: bool CLI Example: ....
Below is the the instruction that describes the task: ### Input: Configure specified adapter to use DHCP only Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the settings were applied, otherwise a...
def get_real_time_locate(ipAddress): """ function takes the ipAddress of a specific host and issues a RESTFUL call to get the device and interface that the target host is currently connected to. :param ipAddress: str value valid IPv4 IP address :return: dictionary containing hostIp, devId, deviceIP,...
function takes the ipAddress of a specific host and issues a RESTFUL call to get the device and interface that the target host is currently connected to. :param ipAddress: str value valid IPv4 IP address :return: dictionary containing hostIp, devId, deviceIP, ifDesc, ifIndex
Below is the the instruction that describes the task: ### Input: function takes the ipAddress of a specific host and issues a RESTFUL call to get the device and interface that the target host is currently connected to. :param ipAddress: str value valid IPv4 IP address :return: dictionary containing host...
def change_directory(path=None): """ Context manager that changes directory and resets it when existing >>> with change_directory('/tmp'): >>> pass """ if path is not None: try: oldpwd = getcwd() logger.debug('changing directory from %s to %s' % (oldpwd, ...
Context manager that changes directory and resets it when existing >>> with change_directory('/tmp'): >>> pass
Below is the the instruction that describes the task: ### Input: Context manager that changes directory and resets it when existing >>> with change_directory('/tmp'): >>> pass ### Response: def change_directory(path=None): """ Context manager that changes directory and resets it when exist...
def open_channel(self): """Open a new channel with RabbitMQ. When RabbitMQ responds that the channel is open, the on_channel_open callback will be invoked by pika. """ logger.debug('Creating new channel') self._connection.channel(on_open_callback=self.on_channel_open)
Open a new channel with RabbitMQ. When RabbitMQ responds that the channel is open, the on_channel_open callback will be invoked by pika.
Below is the the instruction that describes the task: ### Input: Open a new channel with RabbitMQ. When RabbitMQ responds that the channel is open, the on_channel_open callback will be invoked by pika. ### Response: def open_channel(self): """Open a new channel with RabbitMQ. When...
def select(self, selection_specs=None, **selection): """Applies selection by dimension name Applies a selection along the dimensions of the object using keyword arguments. The selection may be narrowed to certain objects using selection_specs. For container objects the selection...
Applies selection by dimension name Applies a selection along the dimensions of the object using keyword arguments. The selection may be narrowed to certain objects using selection_specs. For container objects the selection will be applied to all children as well. Selections ma...
Below is the the instruction that describes the task: ### Input: Applies selection by dimension name Applies a selection along the dimensions of the object using keyword arguments. The selection may be narrowed to certain objects using selection_specs. For container objects the sele...
def setxattr(self, req, ino, name, value, flags): """ Set an extended attribute Valid replies: reply_err """ self.reply_err(req, errno.ENOSYS)
Set an extended attribute Valid replies: reply_err
Below is the the instruction that describes the task: ### Input: Set an extended attribute Valid replies: reply_err ### Response: def setxattr(self, req, ino, name, value, flags): """ Set an extended attribute Valid replies: reply_err """ self.reply_err(r...
def tfhub_cache_dir(default_cache_dir=None, use_temp=False): """Returns cache directory. Returns cache directory from either TFHUB_CACHE_DIR environment variable or --tfhub_cache_dir or default, if set. Args: default_cache_dir: Default cache location to use if neither TFHUB_CACHE_DIR ...
Returns cache directory. Returns cache directory from either TFHUB_CACHE_DIR environment variable or --tfhub_cache_dir or default, if set. Args: default_cache_dir: Default cache location to use if neither TFHUB_CACHE_DIR environment variable nor --tfhub_cache_dir are ...
Below is the the instruction that describes the task: ### Input: Returns cache directory. Returns cache directory from either TFHUB_CACHE_DIR environment variable or --tfhub_cache_dir or default, if set. Args: default_cache_dir: Default cache location to use if neither TFHUB_CACHE_DIR ...
def create_consumer(user, password, config_file_path, process_message, *args, **kwargs): '''Create a pulse consumer. Call listen() to start listening.''' queue_config = _read_json_file(filepath=config_file_path) exchanges = map(lambda x: queue_config['sources'][x]['exchange'], queue_config['sources'].keys(...
Create a pulse consumer. Call listen() to start listening.
Below is the the instruction that describes the task: ### Input: Create a pulse consumer. Call listen() to start listening. ### Response: def create_consumer(user, password, config_file_path, process_message, *args, **kwargs): '''Create a pulse consumer. Call listen() to start listening.''' queue_config = ...
def deleteMapping(self, name, vpName, verbose=None): """ Deletes the Visual Property mapping specified by the `vpName` and `name` parameters. :param name: Name of the Visual Style containing the Visual Mapping :param vpName: Name of the Visual Property that the Visual Mapping controls ...
Deletes the Visual Property mapping specified by the `vpName` and `name` parameters. :param name: Name of the Visual Style containing the Visual Mapping :param vpName: Name of the Visual Property that the Visual Mapping controls :param verbose: print more :returns: default: successful ...
Below is the the instruction that describes the task: ### Input: Deletes the Visual Property mapping specified by the `vpName` and `name` parameters. :param name: Name of the Visual Style containing the Visual Mapping :param vpName: Name of the Visual Property that the Visual Mapping controls ...
def _do_update_packet(self, packet, ip, port): """ React to update packet - people/person on a device have changed :param packet: Packet from client with changes :type packet: paps.si.app.message.APPUpdateMessage :param ip: Client ip address :type ip: unicode :pa...
React to update packet - people/person on a device have changed :param packet: Packet from client with changes :type packet: paps.si.app.message.APPUpdateMessage :param ip: Client ip address :type ip: unicode :param port: Client port :type port: int :rtype: None
Below is the the instruction that describes the task: ### Input: React to update packet - people/person on a device have changed :param packet: Packet from client with changes :type packet: paps.si.app.message.APPUpdateMessage :param ip: Client ip address :type ip: unicode :...
def _get_roles(self, username): """ Get roles of a user @str username: name of the user @rtype: dict, format { 'roles': [<list of roles>], 'unusedgroups': [<list of groups not matching roles>] } """ groups = self._get_groups(username) user_roles = self.roles.g...
Get roles of a user @str username: name of the user @rtype: dict, format { 'roles': [<list of roles>], 'unusedgroups': [<list of groups not matching roles>] }
Below is the the instruction that describes the task: ### Input: Get roles of a user @str username: name of the user @rtype: dict, format { 'roles': [<list of roles>], 'unusedgroups': [<list of groups not matching roles>] } ### Response: def _get_roles(self, username): """ Get r...
def factory(cls, config, db): """ Given a configuration and database, select and return an appropriate instance of a subclass of GetBucketKey. This will ensure that both client and server support are available for the Lua script feature of Redis, and if not, a lock will be ...
Given a configuration and database, select and return an appropriate instance of a subclass of GetBucketKey. This will ensure that both client and server support are available for the Lua script feature of Redis, and if not, a lock will be used. :param config: A dictionary of c...
Below is the the instruction that describes the task: ### Input: Given a configuration and database, select and return an appropriate instance of a subclass of GetBucketKey. This will ensure that both client and server support are available for the Lua script feature of Redis, and if not, a...
def tasks(self, from_date=DEFAULT_DATETIME): """Retrieve tasks. :param from_date: retrieve tasks that where updated from that date; dates are converted epoch time. """ # Convert 'from_date' to epoch timestamp. # Zero value (1970-01-01 00:00:00) is not allowed for ...
Retrieve tasks. :param from_date: retrieve tasks that where updated from that date; dates are converted epoch time.
Below is the the instruction that describes the task: ### Input: Retrieve tasks. :param from_date: retrieve tasks that where updated from that date; dates are converted epoch time. ### Response: def tasks(self, from_date=DEFAULT_DATETIME): """Retrieve tasks. :param from_date: ...
def create(*units): """create this unit within the game as specified""" ret = [] for unit in units: # implemented using sc2simulator.ScenarioUnit x, y = unit.position[:2] pt = Point2D(x=x, y=y) unit.tag = 0 # forget any tag because a new unit will be created new = DebugComman...
create this unit within the game as specified
Below is the the instruction that describes the task: ### Input: create this unit within the game as specified ### Response: def create(*units): """create this unit within the game as specified""" ret = [] for unit in units: # implemented using sc2simulator.ScenarioUnit x, y = unit.position[:2]...
def which(x): ''' Same as which command on Linux ''' for p in os.environ.get('PATH').split(os.pathsep): p = os.path.join(p, x) if os.path.exists(p): return os.path.abspath(p) return None
Same as which command on Linux
Below is the the instruction that describes the task: ### Input: Same as which command on Linux ### Response: def which(x): ''' Same as which command on Linux ''' for p in os.environ.get('PATH').split(os.pathsep): p = os.path.join(p, x) if os.path.exists(p): return os.pa...
def get_terrain_height(self, pos: Union[Point2, Point3, Unit]) -> int: """ Returns terrain height at a position. Caution: terrain height is not anywhere near a unit's z-coordinate. """ assert isinstance(pos, (Point2, Point3, Unit)) pos = pos.position.to2.rounded return self._game_info.te...
Returns terrain height at a position. Caution: terrain height is not anywhere near a unit's z-coordinate.
Below is the the instruction that describes the task: ### Input: Returns terrain height at a position. Caution: terrain height is not anywhere near a unit's z-coordinate. ### Response: def get_terrain_height(self, pos: Union[Point2, Point3, Unit]) -> int: """ Returns terrain height at a position. Caution: ...
def add_ihex_file(self, filename, overwrite=False): """Open given Intel HEX file and add its records. Set `overwrite` to ``True`` to allow already added data to be overwritten. """ with open(filename, 'r') as fin: self.add_ihex(fin.read(), overwrite)
Open given Intel HEX file and add its records. Set `overwrite` to ``True`` to allow already added data to be overwritten.
Below is the the instruction that describes the task: ### Input: Open given Intel HEX file and add its records. Set `overwrite` to ``True`` to allow already added data to be overwritten. ### Response: def add_ihex_file(self, filename, overwrite=False): """Open given Intel HEX file and add its recor...
def _get_edge_set(self, tol=0.1): """ Retrieve set of top edges from all of the individual surfaces, downsampling the upper edge based on the specified tolerance """ edges = [] for surface in self.surfaces: if isinstance(surface, GriddedSurface): ...
Retrieve set of top edges from all of the individual surfaces, downsampling the upper edge based on the specified tolerance
Below is the the instruction that describes the task: ### Input: Retrieve set of top edges from all of the individual surfaces, downsampling the upper edge based on the specified tolerance ### Response: def _get_edge_set(self, tol=0.1): """ Retrieve set of top edges from all of the individu...
def boolean(self): """A mapping of this `StateVector` to a 2-D array containing all binary bits as booleans, for each time point. """ try: return self._boolean except AttributeError: nbits = len(self.bits) boolean = numpy.zeros((self.size, nbit...
A mapping of this `StateVector` to a 2-D array containing all binary bits as booleans, for each time point.
Below is the the instruction that describes the task: ### Input: A mapping of this `StateVector` to a 2-D array containing all binary bits as booleans, for each time point. ### Response: def boolean(self): """A mapping of this `StateVector` to a 2-D array containing all binary bits as boole...
def build_wxsfile_default_gui(root): """ This function adds a default GUI to the wxs file """ factory = Document() Product = root.getElementsByTagName('Product')[0] UIRef = factory.createElement('UIRef') UIRef.attributes['Id'] = 'WixUI_Mondo' Product.childNodes.append(UIRef) UIRef ...
This function adds a default GUI to the wxs file
Below is the the instruction that describes the task: ### Input: This function adds a default GUI to the wxs file ### Response: def build_wxsfile_default_gui(root): """ This function adds a default GUI to the wxs file """ factory = Document() Product = root.getElementsByTagName('Product')[0] U...
def from_cryptography(cls, crypto_req): """ Construct based on a ``cryptography`` *crypto_req*. :param crypto_req: A ``cryptography`` X.509 certificate signing request :type crypto_req: ``cryptography.x509.CertificateSigningRequest`` :rtype: X509Req .. versionadded:: 1...
Construct based on a ``cryptography`` *crypto_req*. :param crypto_req: A ``cryptography`` X.509 certificate signing request :type crypto_req: ``cryptography.x509.CertificateSigningRequest`` :rtype: X509Req .. versionadded:: 17.1.0
Below is the the instruction that describes the task: ### Input: Construct based on a ``cryptography`` *crypto_req*. :param crypto_req: A ``cryptography`` X.509 certificate signing request :type crypto_req: ``cryptography.x509.CertificateSigningRequest`` :rtype: X509Req .. version...
def find_gsc_offset(image, input_catalog='GSC1', output_catalog='GAIA'): """Find the GSC to GAIA offset based on guide star coordinates Parameters ---------- image : str Filename of image to be processed. Returns ------- delta_ra, delta_dec : tuple of floats Offset in decim...
Find the GSC to GAIA offset based on guide star coordinates Parameters ---------- image : str Filename of image to be processed. Returns ------- delta_ra, delta_dec : tuple of floats Offset in decimal degrees of image based on correction to guide star coordinates relati...
Below is the the instruction that describes the task: ### Input: Find the GSC to GAIA offset based on guide star coordinates Parameters ---------- image : str Filename of image to be processed. Returns ------- delta_ra, delta_dec : tuple of floats Offset in decimal degrees ...
def transform(self, X, perplexity=5, initialization="median", k=25, learning_rate=1, n_iter=100, exaggeration=2, momentum=0): """Embed new points into the existing embedding. This procedure optimizes each point only with respect to the existing embedding i.e. it ignores any in...
Embed new points into the existing embedding. This procedure optimizes each point only with respect to the existing embedding i.e. it ignores any interactions between the points in ``X`` among themselves. Please see the :ref:`parameter-guide` for more information. Parameters ...
Below is the the instruction that describes the task: ### Input: Embed new points into the existing embedding. This procedure optimizes each point only with respect to the existing embedding i.e. it ignores any interactions between the points in ``X`` among themselves. Please see t...
def process_answer(self, user, item, asked, answered, time, answer, response_time, guess, **kwargs): """ This method is used during the answer streaming and is called after the predictive model for each answer. Args: user (int): identifier of ther user answer...
This method is used during the answer streaming and is called after the predictive model for each answer. Args: user (int): identifier of ther user answering the question asked (int): identifier of the asked item answered (int): ...
Below is the the instruction that describes the task: ### Input: This method is used during the answer streaming and is called after the predictive model for each answer. Args: user (int): identifier of ther user answering the question asked (int): ...
def link(self, x,y,w,h,link): "Put a link on the page" if not self.page in self.page_links: self.page_links[self.page] = [] self.page_links[self.page] += [(x*self.k,self.h_pt-y*self.k,w*self.k,h*self.k,link),]
Put a link on the page
Below is the the instruction that describes the task: ### Input: Put a link on the page ### Response: def link(self, x,y,w,h,link): "Put a link on the page" if not self.page in self.page_links: self.page_links[self.page] = [] self.page_links[self.page] += [(x*self.k,self.h_pt-y*...
def p_Callable(p): ''' Callable : NsContentName LPARENT | NsContentName SCOPEOP INDENTIFIER LPARENT | Expression LPARENT | STATIC SCOPEOP INDENTIFIER LPARENT ''' if len(p) <= 3: p[0] = Callable(p[1], None) else: p[0] = Callable(p[1], p[3])
Callable : NsContentName LPARENT | NsContentName SCOPEOP INDENTIFIER LPARENT | Expression LPARENT | STATIC SCOPEOP INDENTIFIER LPARENT
Below is the the instruction that describes the task: ### Input: Callable : NsContentName LPARENT | NsContentName SCOPEOP INDENTIFIER LPARENT | Expression LPARENT | STATIC SCOPEOP INDENTIFIER LPARENT ### Response: def p_Callable(p): ''' Callable : NsContentName LPAREN...
def _evalFunction(individual, name_values, X, y, scorer, cv, iid, fit_params, verbose=0, error_score='raise', score_cache={}): """ Developer Note: -------------------- score_cache was purposefully moved to parameters, and given a dict reference. It will be modified in-place...
Developer Note: -------------------- score_cache was purposefully moved to parameters, and given a dict reference. It will be modified in-place by _evalFunction based on it's reference. This is to allow for a managed, paralell memoization dict, and also for different memoization ...
Below is the the instruction that describes the task: ### Input: Developer Note: -------------------- score_cache was purposefully moved to parameters, and given a dict reference. It will be modified in-place by _evalFunction based on it's reference. This is to allow for a managed, p...
def unregister_provider(self, provider): """ Unregister a provider. Blocks until this RpcConsumer is unregistered from its QueueConsumer, which only happens when all providers have asked to unregister. """ self._unregistering_providers.add(provider) remaining_providers =...
Unregister a provider. Blocks until this RpcConsumer is unregistered from its QueueConsumer, which only happens when all providers have asked to unregister.
Below is the the instruction that describes the task: ### Input: Unregister a provider. Blocks until this RpcConsumer is unregistered from its QueueConsumer, which only happens when all providers have asked to unregister. ### Response: def unregister_provider(self, provider): """ Unregiste...
def get_header(results): '''Extracts the headers, using the first value in the dict as the template''' ret = ['name', ] values = next(iter(results.values())) for k, v in values.items(): if isinstance(v, dict): for metric in v.keys(): ret.append('%s:%s' % (k, metric)) ...
Extracts the headers, using the first value in the dict as the template
Below is the the instruction that describes the task: ### Input: Extracts the headers, using the first value in the dict as the template ### Response: def get_header(results): '''Extracts the headers, using the first value in the dict as the template''' ret = ['name', ] values = next(iter(results.value...
def sse_event(event=None, data=None, id=None, retry=None, comment=None, encoding='utf-8'): """Encode a Server-Sent Event (SSE). At least one field must be present. All fields are strings, except retry, which must be an integer. The event and id fields can not contain newlines. """ if all(x ...
Encode a Server-Sent Event (SSE). At least one field must be present. All fields are strings, except retry, which must be an integer. The event and id fields can not contain newlines.
Below is the the instruction that describes the task: ### Input: Encode a Server-Sent Event (SSE). At least one field must be present. All fields are strings, except retry, which must be an integer. The event and id fields can not contain newlines. ### Response: def sse_event(event=None, data=None, id=Non...
def raise_error(name=None, args=None, message=''): ''' Raise an exception with __name__ from name, args from args If args is None Otherwise message from message\ If name is empty then use "Exception" ''' name = name or 'Exception' if hasattr(salt.exceptions, name): ex = getattr(salt....
Raise an exception with __name__ from name, args from args If args is None Otherwise message from message\ If name is empty then use "Exception"
Below is the the instruction that describes the task: ### Input: Raise an exception with __name__ from name, args from args If args is None Otherwise message from message\ If name is empty then use "Exception" ### Response: def raise_error(name=None, args=None, message=''): ''' Raise an exception w...
def detect_change_mode(text,change): "returns 'add' 'delete' or 'internal'. see comments to update_changes for more details." # warning: some wacky diff logic (in python, probably in JS too) is making some adds / deletes look like replacements (see notes at bottom of diff.py) if len(change.deltas)>1: return 'i...
returns 'add' 'delete' or 'internal'. see comments to update_changes for more details.
Below is the the instruction that describes the task: ### Input: returns 'add' 'delete' or 'internal'. see comments to update_changes for more details. ### Response: def detect_change_mode(text,change): "returns 'add' 'delete' or 'internal'. see comments to update_changes for more details." # warning: some w...
def list_cmd(only_active, only_aliases, verbose): """List indices.""" def _tree_print(d, rec_list=None, verbose=False, indent=2): # Note that on every recursion rec_list is copied, # which might not be very effective for very deep dictionaries. rec_list = rec_list or [] for idx, ...
List indices.
Below is the the instruction that describes the task: ### Input: List indices. ### Response: def list_cmd(only_active, only_aliases, verbose): """List indices.""" def _tree_print(d, rec_list=None, verbose=False, indent=2): # Note that on every recursion rec_list is copied, # which might not...
def execute(commands, serial=None): """ Sends the command to the connected micro:bit via serial and returns the result. If no serial connection is provided, attempts to autodetect the device. For this to work correctly, a particular sequence of commands needs to be sent to put the device into a...
Sends the command to the connected micro:bit via serial and returns the result. If no serial connection is provided, attempts to autodetect the device. For this to work correctly, a particular sequence of commands needs to be sent to put the device into a good state to process the incoming command. ...
Below is the the instruction that describes the task: ### Input: Sends the command to the connected micro:bit via serial and returns the result. If no serial connection is provided, attempts to autodetect the device. For this to work correctly, a particular sequence of commands needs to be sent to ...
def pad_rem(pv, size=None): """ Removes linear padding from array This is a convenience function that does the opposite of `pad_add`. Parameters ---------- pv : 1D or 2D ndarray The array from which the padding will be removed. size : tuple of length 1 (1D) or 2 (2D), optional ...
Removes linear padding from array This is a convenience function that does the opposite of `pad_add`. Parameters ---------- pv : 1D or 2D ndarray The array from which the padding will be removed. size : tuple of length 1 (1D) or 2 (2D), optional The final size of the un-padded ...
Below is the the instruction that describes the task: ### Input: Removes linear padding from array This is a convenience function that does the opposite of `pad_add`. Parameters ---------- pv : 1D or 2D ndarray The array from which the padding will be removed. size : tuple of lengt...
def getISOSetupList(self): """ Get individual ISO transfer's setup. Returns a list of dicts, each containing an individual ISO transfer parameters: - length - actual_length - status (see libusb1's API documentation for their signification) Returned...
Get individual ISO transfer's setup. Returns a list of dicts, each containing an individual ISO transfer parameters: - length - actual_length - status (see libusb1's API documentation for their signification) Returned list is consistent with getISOBufferList retur...
Below is the the instruction that describes the task: ### Input: Get individual ISO transfer's setup. Returns a list of dicts, each containing an individual ISO transfer parameters: - length - actual_length - status (see libusb1's API documentation for their significa...
def sizes(self): """Provides block_size and transfer_size through a list of dict, for instance: [{'transfer': '1M 4M', 'block': '8M'}] """ if self.attributes.get('sizes'): for settings in self.attributes.get('sizes'): for pair in itertools.product( ...
Provides block_size and transfer_size through a list of dict, for instance: [{'transfer': '1M 4M', 'block': '8M'}]
Below is the the instruction that describes the task: ### Input: Provides block_size and transfer_size through a list of dict, for instance: [{'transfer': '1M 4M', 'block': '8M'}] ### Response: def sizes(self): """Provides block_size and transfer_size through a list of dict, for instance: [...
def get_kapur_threshold(image, mask=None): """The Kapur, Sahoo, & Wong method of thresholding, adapted to log-space.""" cropped_image = np.array(image.flat) if mask is None else image[mask] if np.product(cropped_image.shape)<3: return 0 if np.min(cropped_image) == np.max(cropped_image): ...
The Kapur, Sahoo, & Wong method of thresholding, adapted to log-space.
Below is the the instruction that describes the task: ### Input: The Kapur, Sahoo, & Wong method of thresholding, adapted to log-space. ### Response: def get_kapur_threshold(image, mask=None): """The Kapur, Sahoo, & Wong method of thresholding, adapted to log-space.""" cropped_image = np.array(image.flat) ...
def _represent_arguments(*arguments, **keyword_arguments): """Represent the aruments in a form suitable as a key (hashable) And which will be recognisable to user in error messages >>> print(_represent_arguments([1, 2], **{'fred':'here'})) [1, 2], fred='here' """ argument_strings = [repr(a) for...
Represent the aruments in a form suitable as a key (hashable) And which will be recognisable to user in error messages >>> print(_represent_arguments([1, 2], **{'fred':'here'})) [1, 2], fred='here'
Below is the the instruction that describes the task: ### Input: Represent the aruments in a form suitable as a key (hashable) And which will be recognisable to user in error messages >>> print(_represent_arguments([1, 2], **{'fred':'here'})) [1, 2], fred='here' ### Response: def _represent_arguments(...
def decode_value(value, client): """Converts a Firestore protobuf ``Value`` to a native Python value. Args: value (google.cloud.firestore_v1beta1.types.Value): A Firestore protobuf to be decoded / parsed / converted. client (~.firestore_v1beta1.client.Client): A client that has ...
Converts a Firestore protobuf ``Value`` to a native Python value. Args: value (google.cloud.firestore_v1beta1.types.Value): A Firestore protobuf to be decoded / parsed / converted. client (~.firestore_v1beta1.client.Client): A client that has a document factory. Returns...
Below is the the instruction that describes the task: ### Input: Converts a Firestore protobuf ``Value`` to a native Python value. Args: value (google.cloud.firestore_v1beta1.types.Value): A Firestore protobuf to be decoded / parsed / converted. client (~.firestore_v1beta1.client.Cl...
def handle(self, sock, read_data, path, headers): "Sends back a static error page." for i in range(self.attempts): try: server_sock = eventlet.connect( tuple(random.choice(self.backends)), ) except socket.error: ...
Sends back a static error page.
Below is the the instruction that describes the task: ### Input: Sends back a static error page. ### Response: def handle(self, sock, read_data, path, headers): "Sends back a static error page." for i in range(self.attempts): try: server_sock = eventlet.connect( ...
def __embed_branch(dfs_data): """Builds the combinatorial embedding of the graph. Returns whether the graph is planar.""" u = dfs_data['ordering'][0] dfs_data['LF'] = [] dfs_data['RF'] = [] dfs_data['FG'] = {} n = dfs_data['graph'].num_nodes() f0 = (0, n) g0 = (0, n) L0 = {'u': 0, 'v...
Builds the combinatorial embedding of the graph. Returns whether the graph is planar.
Below is the the instruction that describes the task: ### Input: Builds the combinatorial embedding of the graph. Returns whether the graph is planar. ### Response: def __embed_branch(dfs_data): """Builds the combinatorial embedding of the graph. Returns whether the graph is planar.""" u = dfs_data['orderi...
def import_generators(self, session, debug=False): """ Imports renewable (res) and conventional (conv) generators Args: session : sqlalchemy.orm.session.Session Database session debug: If True, information is printed during process Notes: ...
Imports renewable (res) and conventional (conv) generators Args: session : sqlalchemy.orm.session.Session Database session debug: If True, information is printed during process Notes: Connection of generators is done later on in NetworkDing0's method ...
Below is the the instruction that describes the task: ### Input: Imports renewable (res) and conventional (conv) generators Args: session : sqlalchemy.orm.session.Session Database session debug: If True, information is printed during process Notes: ...
def _private_packages_allowed(): """ Checks if the current user is allowed to create private packages. In the public cloud, the user needs to be on a paid plan. There are no restrictions in other deployments. """ if not HAVE_PAYMENTS or TEAM_ID: return True customer = _get_or_creat...
Checks if the current user is allowed to create private packages. In the public cloud, the user needs to be on a paid plan. There are no restrictions in other deployments.
Below is the the instruction that describes the task: ### Input: Checks if the current user is allowed to create private packages. In the public cloud, the user needs to be on a paid plan. There are no restrictions in other deployments. ### Response: def _private_packages_allowed(): """ Checks if ...
def _lte(field, value, document): """ Returns True if the value of a document field is less than or equal to a given value """ try: return document.get(field, None) <= value except TypeError: # pragma: no cover Python < 3.0 return False
Returns True if the value of a document field is less than or equal to a given value
Below is the the instruction that describes the task: ### Input: Returns True if the value of a document field is less than or equal to a given value ### Response: def _lte(field, value, document): """ Returns True if the value of a document field is less than or equal to a given value """ ...
def color( self, name, colorGroup = None ): """ Returns the color for the given name at the inputed group. If no \ group is specified, the first group in the list is used. :param name | <str> colorGroup | <str> || None :retu...
Returns the color for the given name at the inputed group. If no \ group is specified, the first group in the list is used. :param name | <str> colorGroup | <str> || None :return <QColor>
Below is the the instruction that describes the task: ### Input: Returns the color for the given name at the inputed group. If no \ group is specified, the first group in the list is used. :param name | <str> colorGroup | <str> || None ...
def __get_stock_row(self, stock: Stock, depth: int) -> str: """ formats stock row """ assert isinstance(stock, Stock) view_model = AssetAllocationViewModel() view_model.depth = depth # Symbol view_model.name = stock.symbol # Current allocation view_mod...
formats stock row
Below is the the instruction that describes the task: ### Input: formats stock row ### Response: def __get_stock_row(self, stock: Stock, depth: int) -> str: """ formats stock row """ assert isinstance(stock, Stock) view_model = AssetAllocationViewModel() view_model.depth = depth ...
def alchemyencoder(obj): """JSON encoder function for SQLAlchemy special classes.""" if isinstance(obj, datetime.date): return obj.isoformat() elif isinstance(obj, decimal.Decimal): return float(obj)
JSON encoder function for SQLAlchemy special classes.
Below is the the instruction that describes the task: ### Input: JSON encoder function for SQLAlchemy special classes. ### Response: def alchemyencoder(obj): """JSON encoder function for SQLAlchemy special classes.""" if isinstance(obj, datetime.date): return obj.isoformat() elif isinstance(obj...
def require_option(current_ctx: click.Context, param_name: str) -> None: """Throw an exception if an option wasn't required. This is useful when its optional in some contexts but required for a subcommand""" ctx = current_ctx param_definition = None while ctx is not None: # ctx.command.para...
Throw an exception if an option wasn't required. This is useful when its optional in some contexts but required for a subcommand
Below is the the instruction that describes the task: ### Input: Throw an exception if an option wasn't required. This is useful when its optional in some contexts but required for a subcommand ### Response: def require_option(current_ctx: click.Context, param_name: str) -> None: """Throw an exception if a...
def DumpMany(objs): """Stringifies a sequence of Python objects to a multi-document YAML. Args: objs: An iterable of Python objects to convert to YAML. Returns: A multi-document YAML representation of the given objects. """ precondition.AssertIterableType(objs, object) text = yaml.safe_dump_all(o...
Stringifies a sequence of Python objects to a multi-document YAML. Args: objs: An iterable of Python objects to convert to YAML. Returns: A multi-document YAML representation of the given objects.
Below is the the instruction that describes the task: ### Input: Stringifies a sequence of Python objects to a multi-document YAML. Args: objs: An iterable of Python objects to convert to YAML. Returns: A multi-document YAML representation of the given objects. ### Response: def DumpMany(objs): """...
def execute(self, sql_statement, parameters=None): """ Execute the specified Structured Query Language (SQL) parameterized statement. @note: each result column MUST be named with distinct names. @param sql_statement: a string representation of a Structured Query L...
Execute the specified Structured Query Language (SQL) parameterized statement. @note: each result column MUST be named with distinct names. @param sql_statement: a string representation of a Structured Query Language (SQL) expression including Python extended format codes, ...
Below is the the instruction that describes the task: ### Input: Execute the specified Structured Query Language (SQL) parameterized statement. @note: each result column MUST be named with distinct names. @param sql_statement: a string representation of a Structured Query Lan...
def quantity_from_hdf5(dset): """ Return an Astropy Quantity object from a key in an HDF5 file, group, or dataset. This checks to see if the input file/group/dataset contains a ``'unit'`` attribute (e.g., in `f.attrs`). Parameters ---------- dset : :class:`h5py.DataSet` Returns ---...
Return an Astropy Quantity object from a key in an HDF5 file, group, or dataset. This checks to see if the input file/group/dataset contains a ``'unit'`` attribute (e.g., in `f.attrs`). Parameters ---------- dset : :class:`h5py.DataSet` Returns ------- q : `astropy.units.Quantity`, `nu...
Below is the the instruction that describes the task: ### Input: Return an Astropy Quantity object from a key in an HDF5 file, group, or dataset. This checks to see if the input file/group/dataset contains a ``'unit'`` attribute (e.g., in `f.attrs`). Parameters ---------- dset : :class:`h5py.Da...
def desaturate(self, level): """Create a new instance based on this one but less saturated. Parameters: :level: The amount by which the color should be desaturated to produce the new one [0...1]. Returns: A grapefruit.Color instance. >>> Color.from_hsl(30, 0.5, 0.5).desatu...
Create a new instance based on this one but less saturated. Parameters: :level: The amount by which the color should be desaturated to produce the new one [0...1]. Returns: A grapefruit.Color instance. >>> Color.from_hsl(30, 0.5, 0.5).desaturate(0.25) Color(0.625, 0.5, 0.3...
Below is the the instruction that describes the task: ### Input: Create a new instance based on this one but less saturated. Parameters: :level: The amount by which the color should be desaturated to produce the new one [0...1]. Returns: A grapefruit.Color instance. >>> Co...
def listCount(l): """returns len() of each item in a list, as a list.""" for i in range(len(l)): l[i]=len(l[i]) return l
returns len() of each item in a list, as a list.
Below is the the instruction that describes the task: ### Input: returns len() of each item in a list, as a list. ### Response: def listCount(l): """returns len() of each item in a list, as a list.""" for i in range(len(l)): l[i]=len(l[i]) return l
def _exclusively_used(self, context, hosting_device, tenant_id): """Checks if only <tenant_id>'s resources use <hosting_device>.""" return (context.session.query(hd_models.SlotAllocation).filter( hd_models.SlotAllocation.hosting_device_id == hosting_device['id'], hd_models.SlotAl...
Checks if only <tenant_id>'s resources use <hosting_device>.
Below is the the instruction that describes the task: ### Input: Checks if only <tenant_id>'s resources use <hosting_device>. ### Response: def _exclusively_used(self, context, hosting_device, tenant_id): """Checks if only <tenant_id>'s resources use <hosting_device>.""" return (context.session.que...
def show(self, app_path, browser=None, new='tab'): ''' Opens an app in a browser window or tab. This method is useful for testing or running Bokeh server applications on a local machine but should not call when running Bokeh server for an actual deployment. Args: ap...
Opens an app in a browser window or tab. This method is useful for testing or running Bokeh server applications on a local machine but should not call when running Bokeh server for an actual deployment. Args: app_path (str) : the app path to open The part of...
Below is the the instruction that describes the task: ### Input: Opens an app in a browser window or tab. This method is useful for testing or running Bokeh server applications on a local machine but should not call when running Bokeh server for an actual deployment. Args: ...
def fetch(self): """ Fetch a BalanceInstance :returns: Fetched BalanceInstance :rtype: twilio.rest.api.v2010.account.balance.BalanceInstance """ params = values.of({}) payload = self._version.fetch( 'GET', self._uri, params=pa...
Fetch a BalanceInstance :returns: Fetched BalanceInstance :rtype: twilio.rest.api.v2010.account.balance.BalanceInstance
Below is the the instruction that describes the task: ### Input: Fetch a BalanceInstance :returns: Fetched BalanceInstance :rtype: twilio.rest.api.v2010.account.balance.BalanceInstance ### Response: def fetch(self): """ Fetch a BalanceInstance :returns: Fetched BalanceInst...
def battery_charge_current(self): """ Returns current in mA """ msb = self.bus.read_byte_data(AXP209_ADDRESS, BATTERY_CHARGE_CURRENT_MSB_REG) lsb = self.bus.read_byte_data(AXP209_ADDRESS, BATTERY_CHARGE_CURRENT_LSB_REG) # (12 bits) charge_bin = msb << 4 | lsb & 0x0f # 0 m...
Returns current in mA
Below is the the instruction that describes the task: ### Input: Returns current in mA ### Response: def battery_charge_current(self): """ Returns current in mA """ msb = self.bus.read_byte_data(AXP209_ADDRESS, BATTERY_CHARGE_CURRENT_MSB_REG) lsb = self.bus.read_byte_data(AXP209_ADDRESS, BA...
def _initialize(self, provide_data: List[mx.io.DataDesc], provide_label: List[mx.io.DataDesc], default_bucket_key: Tuple[int, int]) -> None: """ Initializes model components, creates scoring symbol and module, and binds it. :param prov...
Initializes model components, creates scoring symbol and module, and binds it. :param provide_data: List of data descriptors. :param provide_label: List of label descriptors. :param default_bucket_key: The default maximum (source, target) lengths.
Below is the the instruction that describes the task: ### Input: Initializes model components, creates scoring symbol and module, and binds it. :param provide_data: List of data descriptors. :param provide_label: List of label descriptors. :param default_bucket_key: The default maximum (sou...
def wrap_message(self, message): """ Cryptographically signs and optionally encrypts the supplied message. The message is only encrypted if 'confidentiality' was negotiated, otherwise the message is left untouched. :return: A tuple containing the message signature and the optionally encr...
Cryptographically signs and optionally encrypts the supplied message. The message is only encrypted if 'confidentiality' was negotiated, otherwise the message is left untouched. :return: A tuple containing the message signature and the optionally encrypted message
Below is the the instruction that describes the task: ### Input: Cryptographically signs and optionally encrypts the supplied message. The message is only encrypted if 'confidentiality' was negotiated, otherwise the message is left untouched. :return: A tuple containing the message signature and the...
def declare_type(self, type_): """ Declares a type. Checks its name is not already used in the current scope, and that it's not a basic type. Returns the given type_ Symbol, or None on error. """ assert isinstance(type_, symbols.TYPE) # Checks it's not a basic ty...
Declares a type. Checks its name is not already used in the current scope, and that it's not a basic type. Returns the given type_ Symbol, or None on error.
Below is the the instruction that describes the task: ### Input: Declares a type. Checks its name is not already used in the current scope, and that it's not a basic type. Returns the given type_ Symbol, or None on error. ### Response: def declare_type(self, type_): """ Declares a ...
def do_bm(self, arg): """ [~process] bm <address-address> - set memory breakpoint """ pid = self.get_process_id_from_prefix() if not self.debug.is_debugee(pid): raise CmdError("target process is not being debugged") process = self.get_process(pid) ...
[~process] bm <address-address> - set memory breakpoint
Below is the the instruction that describes the task: ### Input: [~process] bm <address-address> - set memory breakpoint ### Response: def do_bm(self, arg): """ [~process] bm <address-address> - set memory breakpoint """ pid = self.get_process_id_from_prefix() if not self.de...
def destroy_elb(app='', env='dev', region='us-east-1', **_): """Destroy ELB Resources. Args: app (str): Spinnaker Application name. env (str): Deployment environment. region (str): AWS region. Returns: True upon successful completion. """ task_json = get_template( ...
Destroy ELB Resources. Args: app (str): Spinnaker Application name. env (str): Deployment environment. region (str): AWS region. Returns: True upon successful completion.
Below is the the instruction that describes the task: ### Input: Destroy ELB Resources. Args: app (str): Spinnaker Application name. env (str): Deployment environment. region (str): AWS region. Returns: True upon successful completion. ### Response: def destroy_elb(app='',...
def make_parse_err(self, err, reformat=True, include_ln=True): """Make a CoconutParseError from a ParseBaseException.""" err_line = err.line err_index = err.col - 1 err_lineno = err.lineno if include_ln else None if reformat: err_line, err_index = self.reformat(err_li...
Make a CoconutParseError from a ParseBaseException.
Below is the the instruction that describes the task: ### Input: Make a CoconutParseError from a ParseBaseException. ### Response: def make_parse_err(self, err, reformat=True, include_ln=True): """Make a CoconutParseError from a ParseBaseException.""" err_line = err.line err_index = err.col...
def process_resource(self, req, resp, resource): """ Process the request after routing. The resource is required to determine if a model based resource is being used for validations so skip processing if no `resource.model` attribute is present. """ try: mod...
Process the request after routing. The resource is required to determine if a model based resource is being used for validations so skip processing if no `resource.model` attribute is present.
Below is the the instruction that describes the task: ### Input: Process the request after routing. The resource is required to determine if a model based resource is being used for validations so skip processing if no `resource.model` attribute is present. ### Response: def process_resour...
def get_project_files(): """Retrieve a list of project files, ignoring hidden files. :return: sorted list of project files :rtype: :class:`list` """ if is_git_project(): return get_git_project_files() project_files = [] for top, subdirs, files in os.walk('.'): for subdir in...
Retrieve a list of project files, ignoring hidden files. :return: sorted list of project files :rtype: :class:`list`
Below is the the instruction that describes the task: ### Input: Retrieve a list of project files, ignoring hidden files. :return: sorted list of project files :rtype: :class:`list` ### Response: def get_project_files(): """Retrieve a list of project files, ignoring hidden files. :return: sorted ...
def _propagated_record(self, rdtype, name, content, nameservers=None): """ If the publicly propagation check should be done, waits until the domain nameservers responses with the propagated record type, name & content and returns a boolean, if the publicly propagation was successful or n...
If the publicly propagation check should be done, waits until the domain nameservers responses with the propagated record type, name & content and returns a boolean, if the publicly propagation was successful or not.
Below is the the instruction that describes the task: ### Input: If the publicly propagation check should be done, waits until the domain nameservers responses with the propagated record type, name & content and returns a boolean, if the publicly propagation was successful or not. ### Response: def...
def atoms_order(self): """ Morgan like algorithm for graph nodes ordering :return: dict of atom-weight pairs """ if not len(self): # for empty containers return {} elif len(self) == 1: # optimize single atom containers return dict.fromkeys(self,...
Morgan like algorithm for graph nodes ordering :return: dict of atom-weight pairs
Below is the the instruction that describes the task: ### Input: Morgan like algorithm for graph nodes ordering :return: dict of atom-weight pairs ### Response: def atoms_order(self): """ Morgan like algorithm for graph nodes ordering :return: dict of atom-weight pairs """...
def eaSimpleConverge(population, toolbox, cxpb, mutpb, ngen, stats=None, halloffame=None, callback=None, verbose=True): """This algorithm reproduce the simplest evolutionary algorithm as presented in chapter 7 of [Back2000]_. Modified to allow checking if there is no change for ngen, a...
This algorithm reproduce the simplest evolutionary algorithm as presented in chapter 7 of [Back2000]_. Modified to allow checking if there is no change for ngen, as a simple rule for convergence. Interface is similar to eaSimple(). However, in eaSimple, ngen is total number of iterations; in eaSimpleCo...
Below is the the instruction that describes the task: ### Input: This algorithm reproduce the simplest evolutionary algorithm as presented in chapter 7 of [Back2000]_. Modified to allow checking if there is no change for ngen, as a simple rule for convergence. Interface is similar to eaSimple(). Howeve...
def rotateAboutVectorMatrix(vec, theta_deg): """Construct the matrix that rotates vector a about vector vec by an angle of theta_deg degrees Taken from http://en.wikipedia.org/wiki/Rotation_matrix#Rotation_matrix_from_axis_and_angle Input: theta_deg (float) Angle through which vectors should...
Construct the matrix that rotates vector a about vector vec by an angle of theta_deg degrees Taken from http://en.wikipedia.org/wiki/Rotation_matrix#Rotation_matrix_from_axis_and_angle Input: theta_deg (float) Angle through which vectors should be rotated in degrees Returns:...
Below is the the instruction that describes the task: ### Input: Construct the matrix that rotates vector a about vector vec by an angle of theta_deg degrees Taken from http://en.wikipedia.org/wiki/Rotation_matrix#Rotation_matrix_from_axis_and_angle Input: theta_deg (float) Angle through whi...