code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def process_typedef(self, line): """处理类型申明""" content = line.split(' ') type_ = self.type_dict[content[1]] if type_ == 'c_char' and '[' in line: # type_ = 'string' type_ = '%s*%s' % (type_, line[line.index('[') + 1:line.index(']')]) keyword = content[2] ...
处理类型申明
Below is the the instruction that describes the task: ### Input: 处理类型申明 ### Response: def process_typedef(self, line): """处理类型申明""" content = line.split(' ') type_ = self.type_dict[content[1]] if type_ == 'c_char' and '[' in line: # type_ = 'string' type_ = ...
def getOutputDevice(self, textureType): """ * Returns platform- and texture-type specific adapter identification so that applications and the compositor are creating textures and swap chains on the same GPU. If an error occurs the device will be set to 0. pInstance is an optional...
* Returns platform- and texture-type specific adapter identification so that applications and the compositor are creating textures and swap chains on the same GPU. If an error occurs the device will be set to 0. pInstance is an optional parameter that is required only when textureType is Texture...
Below is the the instruction that describes the task: ### Input: * Returns platform- and texture-type specific adapter identification so that applications and the compositor are creating textures and swap chains on the same GPU. If an error occurs the device will be set to 0. pInstance is an...
def initial_data(cls, product_quantities): ''' Prepares initial data for an instance of this form. product_quantities is a sequence of (product,quantity) tuples ''' f = [ { _ItemQuantityProductsForm.CHOICE_FIELD: product.id, _ItemQuantityProductsForm....
Prepares initial data for an instance of this form. product_quantities is a sequence of (product,quantity) tuples
Below is the the instruction that describes the task: ### Input: Prepares initial data for an instance of this form. product_quantities is a sequence of (product,quantity) tuples ### Response: def initial_data(cls, product_quantities): ''' Prepares initial data for an instance of this form. ...
def set_lacp_timeout(self, name, value=None): """Configures the Port-Channel LACP fallback timeout The fallback timeout configures the period an interface in fallback mode remains in LACP mode without receiving a PDU. Args: name(str): The Port-Channel interface name ...
Configures the Port-Channel LACP fallback timeout The fallback timeout configures the period an interface in fallback mode remains in LACP mode without receiving a PDU. Args: name(str): The Port-Channel interface name value(int): port-channel lacp fallback timeout...
Below is the the instruction that describes the task: ### Input: Configures the Port-Channel LACP fallback timeout The fallback timeout configures the period an interface in fallback mode remains in LACP mode without receiving a PDU. Args: name(str): The Port-Channel inter...
def update_user_pool_client(UserPoolId=None, ClientId=None, ClientName=None, RefreshTokenValidity=None, ReadAttributes=None, WriteAttributes=None, ExplicitAuthFlows=None, SupportedIdentityProviders=None, CallbackURLs=None, LogoutURLs=None, DefaultRedirectURI=None, AllowedOAuthFlows=None, AllowedOAuthScopes=None, Allowe...
Allows the developer to update the specified user pool client and password policy. See also: AWS API Documentation :example: response = client.update_user_pool_client( UserPoolId='string', ClientId='string', ClientName='string', RefreshTokenValidity=123, ReadAtt...
Below is the the instruction that describes the task: ### Input: Allows the developer to update the specified user pool client and password policy. See also: AWS API Documentation :example: response = client.update_user_pool_client( UserPoolId='string', ClientId='string', C...
def flight_id(self) -> Optional[str]: """Returns the unique flight_id value(s) of the DataFrame. If you know how to split flights, you may want to append such a column in the DataFrame. """ if "flight_id" not in self.data.columns: return None tmp = set(self.d...
Returns the unique flight_id value(s) of the DataFrame. If you know how to split flights, you may want to append such a column in the DataFrame.
Below is the the instruction that describes the task: ### Input: Returns the unique flight_id value(s) of the DataFrame. If you know how to split flights, you may want to append such a column in the DataFrame. ### Response: def flight_id(self) -> Optional[str]: """Returns the unique flight...
def _get_app_config(self, app_name): """ Returns an app config for the given name, not by label. """ matches = [app_config for app_config in apps.get_app_configs() if app_config.name == app_name] if not matches: return return matches[0]
Returns an app config for the given name, not by label.
Below is the the instruction that describes the task: ### Input: Returns an app config for the given name, not by label. ### Response: def _get_app_config(self, app_name): """ Returns an app config for the given name, not by label. """ matches = [app_config for app_config in apps.g...
def calc_requiredremotesupply_v1(self): """Calculate the required maximum supply from another location that can be discharged into the dam. Required control parameters: |HighestRemoteSupply| |WaterLevelSupplyThreshold| Required derived parameter: |WaterLevelSupplySmoothPar| Requ...
Calculate the required maximum supply from another location that can be discharged into the dam. Required control parameters: |HighestRemoteSupply| |WaterLevelSupplyThreshold| Required derived parameter: |WaterLevelSupplySmoothPar| Required aide sequence: |WaterLevel| Cal...
Below is the the instruction that describes the task: ### Input: Calculate the required maximum supply from another location that can be discharged into the dam. Required control parameters: |HighestRemoteSupply| |WaterLevelSupplyThreshold| Required derived parameter: |WaterLevelSupp...
def avoid_dead_links(root, machine, wrap_around=False): """Modify a RoutingTree to route-around dead links in a Machine. Uses A* to reconnect disconnected branches of the tree (due to dead links in the machine). Parameters ---------- root : :py:class:`~rig.place_and_route.routing_tree.RoutingT...
Modify a RoutingTree to route-around dead links in a Machine. Uses A* to reconnect disconnected branches of the tree (due to dead links in the machine). Parameters ---------- root : :py:class:`~rig.place_and_route.routing_tree.RoutingTree` The root of the RoutingTree which contains nothing...
Below is the the instruction that describes the task: ### Input: Modify a RoutingTree to route-around dead links in a Machine. Uses A* to reconnect disconnected branches of the tree (due to dead links in the machine). Parameters ---------- root : :py:class:`~rig.place_and_route.routing_tree.Ro...
def new_request(sender, request=None, notify=True, **kwargs): """New request for inclusion.""" if current_app.config['COMMUNITIES_MAIL_ENABLED'] and notify: send_community_request_email(request)
New request for inclusion.
Below is the the instruction that describes the task: ### Input: New request for inclusion. ### Response: def new_request(sender, request=None, notify=True, **kwargs): """New request for inclusion.""" if current_app.config['COMMUNITIES_MAIL_ENABLED'] and notify: send_community_request_email(request...
def get_weekly_charts(self, chart_kind, from_date=None, to_date=None): """ Returns the weekly charts for the week starting from the from_date value to the to_date value. chart_kind should be one of "album", "artist" or "track" """ method = ".getWeekly" + chart_kind.title(...
Returns the weekly charts for the week starting from the from_date value to the to_date value. chart_kind should be one of "album", "artist" or "track"
Below is the the instruction that describes the task: ### Input: Returns the weekly charts for the week starting from the from_date value to the to_date value. chart_kind should be one of "album", "artist" or "track" ### Response: def get_weekly_charts(self, chart_kind, from_date=None, to_date=None...
def _discrete_colorize(categorical, hue, scheme, k, cmap, vmin, vmax): """ Creates a discrete colormap, either using an already-categorical data variable or by bucketing a non-categorical ordinal one. If a scheme is provided we compute a distribution for the given data. If one is not provided we assume ...
Creates a discrete colormap, either using an already-categorical data variable or by bucketing a non-categorical ordinal one. If a scheme is provided we compute a distribution for the given data. If one is not provided we assume that the input data is categorical. This code makes extensive use of ``geopand...
Below is the the instruction that describes the task: ### Input: Creates a discrete colormap, either using an already-categorical data variable or by bucketing a non-categorical ordinal one. If a scheme is provided we compute a distribution for the given data. If one is not provided we assume that the input...
async def sleep(self, duration: float=0.0) -> None: '''Simple wrapper around `asyncio.sleep()`.''' duration = max(0, duration) if duration > 0: Log.debug('sleeping task %s for %.1f seconds', self.name, duration) await asyncio.sleep(duration)
Simple wrapper around `asyncio.sleep()`.
Below is the the instruction that describes the task: ### Input: Simple wrapper around `asyncio.sleep()`. ### Response: async def sleep(self, duration: float=0.0) -> None: '''Simple wrapper around `asyncio.sleep()`.''' duration = max(0, duration) if duration > 0: Log.debug('sle...
def cli(env, **kwargs): """host order options for a given dedicated host. To get a list of available backend routers see example: slcli dh create-options --datacenter dal05 --flavor 56_CORES_X_242_RAM_X_1_4_TB """ mgr = SoftLayer.DedicatedHostManager(env.client) tables = [] if not kwargs[...
host order options for a given dedicated host. To get a list of available backend routers see example: slcli dh create-options --datacenter dal05 --flavor 56_CORES_X_242_RAM_X_1_4_TB
Below is the the instruction that describes the task: ### Input: host order options for a given dedicated host. To get a list of available backend routers see example: slcli dh create-options --datacenter dal05 --flavor 56_CORES_X_242_RAM_X_1_4_TB ### Response: def cli(env, **kwargs): """host order op...
def objects_to_td64ns(data, unit="ns", errors="raise"): """ Convert a object-dtyped or string-dtyped array into an timedelta64[ns]-dtyped array. Parameters ---------- data : ndarray or Index unit : str, default "ns" The timedelta unit to treat integers as multiples of. errors : ...
Convert a object-dtyped or string-dtyped array into an timedelta64[ns]-dtyped array. Parameters ---------- data : ndarray or Index unit : str, default "ns" The timedelta unit to treat integers as multiples of. errors : {"raise", "coerce", "ignore"}, default "raise" How to handle...
Below is the the instruction that describes the task: ### Input: Convert a object-dtyped or string-dtyped array into an timedelta64[ns]-dtyped array. Parameters ---------- data : ndarray or Index unit : str, default "ns" The timedelta unit to treat integers as multiples of. errors :...
def get_tile_images_by_rect(self, rect): """ Speed up data access More efficient because data is accessed and cached locally """ def rev(seq, start, stop): if start < 0: start = 0 return enumerate(seq[start:stop + 1], start) x1, y1, x2, ...
Speed up data access More efficient because data is accessed and cached locally
Below is the the instruction that describes the task: ### Input: Speed up data access More efficient because data is accessed and cached locally ### Response: def get_tile_images_by_rect(self, rect): """ Speed up data access More efficient because data is accessed and cached locally ...
def as_set(self, preserve_casing=False): """Return the set as real python set type. When calling this, all the items are converted to lowercase and the ordering is lost. :param preserve_casing: if set to `True` the items in the set returned will have the origina...
Return the set as real python set type. When calling this, all the items are converted to lowercase and the ordering is lost. :param preserve_casing: if set to `True` the items in the set returned will have the original case like in the :...
Below is the the instruction that describes the task: ### Input: Return the set as real python set type. When calling this, all the items are converted to lowercase and the ordering is lost. :param preserve_casing: if set to `True` the items in the set returned will...
def danke(client, event, channel, nick, rest): 'Danke schön!' if rest: rest = rest.strip() Karma.store.change(rest, 1) rcpt = rest else: rcpt = channel return f'Danke schön, {rcpt}! Danke schön!'
Danke schön!
Below is the the instruction that describes the task: ### Input: Danke schön! ### Response: def danke(client, event, channel, nick, rest): 'Danke schön!' if rest: rest = rest.strip() Karma.store.change(rest, 1) rcpt = rest else: rcpt = channel return f'Danke schön, {...
def get_page_content(id): """Return XHTML content of a page. Parameters: - id: id of a Confluence page. """ data = _json.loads(_api.rest("/" + str(id) + "?expand=body.storage")) return data["body"]["storage"]["value"]
Return XHTML content of a page. Parameters: - id: id of a Confluence page.
Below is the the instruction that describes the task: ### Input: Return XHTML content of a page. Parameters: - id: id of a Confluence page. ### Response: def get_page_content(id): """Return XHTML content of a page. Parameters: - id: id of a Confluence page. """ data = _json.loads(_api.r...
def select(data, trial=None, invert=False, **axes_to_select): """Define the selection of trials, using ranges or actual values. Parameters ---------- data : instance of Data data to select from. trial : list of int or ndarray (dtype='i'), optional index of trials of interest **a...
Define the selection of trials, using ranges or actual values. Parameters ---------- data : instance of Data data to select from. trial : list of int or ndarray (dtype='i'), optional index of trials of interest **axes_to_select, optional Values need to be tuple or list. If t...
Below is the the instruction that describes the task: ### Input: Define the selection of trials, using ranges or actual values. Parameters ---------- data : instance of Data data to select from. trial : list of int or ndarray (dtype='i'), optional index of trials of interest **a...
def add_permission(self, permitted_object, include_members=False, view_only=True): """ Add permission for the specified permitted object(s) to this User Role, thereby granting that permission to all users that have this User Role. The granted permission depends on...
Add permission for the specified permitted object(s) to this User Role, thereby granting that permission to all users that have this User Role. The granted permission depends on the resource class of the permitted object(s): * For Task resources, the granted permission is task permissi...
Below is the the instruction that describes the task: ### Input: Add permission for the specified permitted object(s) to this User Role, thereby granting that permission to all users that have this User Role. The granted permission depends on the resource class of the permitted object(s): ...
async def select(self, db): """Changes db index for all free connections. All previously acquired connections will be closed when released. """ res = True async with self._cond: for i in range(self.freesize): res = res and (await self._pool[i].select(...
Changes db index for all free connections. All previously acquired connections will be closed when released.
Below is the the instruction that describes the task: ### Input: Changes db index for all free connections. All previously acquired connections will be closed when released. ### Response: async def select(self, db): """Changes db index for all free connections. All previously acquired con...
def night_mode(self): """bool: The speaker's night mode. True if on, False if off, None if not supported. """ if not self.is_soundbar: return None response = self.renderingControl.GetEQ([ ('InstanceID', 0), ('EQType', 'NightMode') ]) ...
bool: The speaker's night mode. True if on, False if off, None if not supported.
Below is the the instruction that describes the task: ### Input: bool: The speaker's night mode. True if on, False if off, None if not supported. ### Response: def night_mode(self): """bool: The speaker's night mode. True if on, False if off, None if not supported. """ if ...
def name(function): """ Retrieve a pretty name for the function :param function: function to get name from :return: pretty name """ if isinstance(function, types.FunctionType): return function.__name__ else: return str(function)
Retrieve a pretty name for the function :param function: function to get name from :return: pretty name
Below is the the instruction that describes the task: ### Input: Retrieve a pretty name for the function :param function: function to get name from :return: pretty name ### Response: def name(function): """ Retrieve a pretty name for the function :param function: function to get name from :...
def add_string_label(self, str_): """ Maps ("folds") the given string, returning an unique label ID. This allows several constant labels to be initialized to the same address thus saving memory space. :param str_: the string to map :return: the unique label ID """ ...
Maps ("folds") the given string, returning an unique label ID. This allows several constant labels to be initialized to the same address thus saving memory space. :param str_: the string to map :return: the unique label ID
Below is the the instruction that describes the task: ### Input: Maps ("folds") the given string, returning an unique label ID. This allows several constant labels to be initialized to the same address thus saving memory space. :param str_: the string to map :return: the unique label...
def width(self): """ :return: The width of the data component in the buffer in number of pixels. """ try: if self._part: value = self._part.width else: value = self._buffer.width except InvalidParameterException: ...
:return: The width of the data component in the buffer in number of pixels.
Below is the the instruction that describes the task: ### Input: :return: The width of the data component in the buffer in number of pixels. ### Response: def width(self): """ :return: The width of the data component in the buffer in number of pixels. """ try: if self._p...
def jsonxs(data, expr, action=ACTION_GET, value=None, default=None): """ Get, set, delete values in a JSON structure. `expr` is a JSONpath-like expression pointing to the desired value. `action` determines the action to perform. See the module-level `ACTION_*` constants. `value` should be given if a...
Get, set, delete values in a JSON structure. `expr` is a JSONpath-like expression pointing to the desired value. `action` determines the action to perform. See the module-level `ACTION_*` constants. `value` should be given if action is `ACTION_SET`. If `default` is set and `expr` isn't found, return `de...
Below is the the instruction that describes the task: ### Input: Get, set, delete values in a JSON structure. `expr` is a JSONpath-like expression pointing to the desired value. `action` determines the action to perform. See the module-level `ACTION_*` constants. `value` should be given if action is `AC...
def resize_pty(self, width=80, height=24, width_pixels=0, height_pixels=0): """ Resize the pseudo-terminal. This can be used to change the width and height of the terminal emulation created in a previous `get_pty` call. :param int width: new width (in characters) of the terminal screen...
Resize the pseudo-terminal. This can be used to change the width and height of the terminal emulation created in a previous `get_pty` call. :param int width: new width (in characters) of the terminal screen :param int height: new height (in characters) of the terminal screen :param int...
Below is the the instruction that describes the task: ### Input: Resize the pseudo-terminal. This can be used to change the width and height of the terminal emulation created in a previous `get_pty` call. :param int width: new width (in characters) of the terminal screen :param int height:...
def _update_capacity(self, data): """ Update the consumed capacity metrics """ if 'ConsumedCapacity' in data: # This is all for backwards compatibility consumed = data['ConsumedCapacity'] if not isinstance(consumed, list): consumed = [consumed] ...
Update the consumed capacity metrics
Below is the the instruction that describes the task: ### Input: Update the consumed capacity metrics ### Response: def _update_capacity(self, data): """ Update the consumed capacity metrics """ if 'ConsumedCapacity' in data: # This is all for backwards compatibility consume...
def enrich(self, column): """ This enricher returns the same dataframe with a new column named 'domain'. That column is the result of splitting the email address of another column. If there is not a proper email address an 'unknown' domain is returned. :param col...
This enricher returns the same dataframe with a new column named 'domain'. That column is the result of splitting the email address of another column. If there is not a proper email address an 'unknown' domain is returned. :param column: column where the text to analyze ...
Below is the the instruction that describes the task: ### Input: This enricher returns the same dataframe with a new column named 'domain'. That column is the result of splitting the email address of another column. If there is not a proper email address an 'unknown' domain i...
def is_pinned(self, color: Color, square: Square) -> bool: """ Detects if the given square is pinned to the king of the given color. """ return self.pin_mask(color, square) != BB_ALL
Detects if the given square is pinned to the king of the given color.
Below is the the instruction that describes the task: ### Input: Detects if the given square is pinned to the king of the given color. ### Response: def is_pinned(self, color: Color, square: Square) -> bool: """ Detects if the given square is pinned to the king of the given color. """ ...
def append_var_uint32(self, value): """Appends an unsigned 32-bit integer to the internal buffer, encoded as a varint. """ if not 0 <= value <= wire_format.UINT32_MAX: raise errors.EncodeError('Value out of range: %d' % value) self.append_var_uint64(value)
Appends an unsigned 32-bit integer to the internal buffer, encoded as a varint.
Below is the the instruction that describes the task: ### Input: Appends an unsigned 32-bit integer to the internal buffer, encoded as a varint. ### Response: def append_var_uint32(self, value): """Appends an unsigned 32-bit integer to the internal buffer, encoded as a varint. """ ...
def _fuzzdb_get_strings(max_len=0): 'Helper to get all the strings from fuzzdb' ignored = ['integer-overflow'] for subdir in pkg_resources.resource_listdir('protofuzz', BASE_PATH): if subdir in ignored: continue path = '{}/{}'.format(BASE_PATH, subdir) listing = pkg_re...
Helper to get all the strings from fuzzdb
Below is the the instruction that describes the task: ### Input: Helper to get all the strings from fuzzdb ### Response: def _fuzzdb_get_strings(max_len=0): 'Helper to get all the strings from fuzzdb' ignored = ['integer-overflow'] for subdir in pkg_resources.resource_listdir('protofuzz', BASE_PATH):...
def runAsAdmin(cmdLine=None, target_dir='', wait=True): """ run [cmdLine] as admin specify the location from where the code is executed through [target_dir] """ if os.name != 'nt': raise RuntimeError("This function is only implemented on Windows.") # import win32api, import win32con ...
run [cmdLine] as admin specify the location from where the code is executed through [target_dir]
Below is the the instruction that describes the task: ### Input: run [cmdLine] as admin specify the location from where the code is executed through [target_dir] ### Response: def runAsAdmin(cmdLine=None, target_dir='', wait=True): """ run [cmdLine] as admin specify the location from where the code...
def has_gap_in_elf_shndx(self): """Return the has gap in elf shndx attribute of the BFD file being processed. """ if not self._ptr: raise BfdException("BFD not initialized") return _bfd.get_bfd_attribute( self._ptr, BfdAttributes.HAS_GAP_IN_ELF_SHNDX)
Return the has gap in elf shndx attribute of the BFD file being processed.
Below is the the instruction that describes the task: ### Input: Return the has gap in elf shndx attribute of the BFD file being processed. ### Response: def has_gap_in_elf_shndx(self): """Return the has gap in elf shndx attribute of the BFD file being processed. """ if not ...
def objects_copy(self, source_bucket, source_key, target_bucket, target_key): """Updates the metadata associated with an object. Args: source_bucket: the name of the bucket containing the source object. source_key: the key of the source object being copied. target_bucket: the name of the buck...
Updates the metadata associated with an object. Args: source_bucket: the name of the bucket containing the source object. source_key: the key of the source object being copied. target_bucket: the name of the bucket that will contain the copied object. target_key: the key of the copied objec...
Below is the the instruction that describes the task: ### Input: Updates the metadata associated with an object. Args: source_bucket: the name of the bucket containing the source object. source_key: the key of the source object being copied. target_bucket: the name of the bucket that will con...
def warn_quirks(message, recommend, pattern, index): """Warn quirks.""" import traceback import bs4 # noqa: F401 # Acquire source code line context paths = (MODULE, sys.modules['bs4'].__path__[0]) tb = traceback.extract_stack() previous = None filename = None lineno = None for...
Warn quirks.
Below is the the instruction that describes the task: ### Input: Warn quirks. ### Response: def warn_quirks(message, recommend, pattern, index): """Warn quirks.""" import traceback import bs4 # noqa: F401 # Acquire source code line context paths = (MODULE, sys.modules['bs4'].__path__[0]) ...
def setup_interval_coinc(workflow, hdfbank, trig_files, stat_files, veto_files, veto_names, out_dir, tags=None): """ This function sets up exact match coincidence and background estimation using a folded interval technique. """ if tags is None: tags = [] make_an...
This function sets up exact match coincidence and background estimation using a folded interval technique.
Below is the the instruction that describes the task: ### Input: This function sets up exact match coincidence and background estimation using a folded interval technique. ### Response: def setup_interval_coinc(workflow, hdfbank, trig_files, stat_files, veto_files, veto_names, out_dir...
def _handle_option_deprecations(options): """Issue appropriate warnings when deprecated options are present in the options dictionary. Removes deprecated option key, value pairs if the options dictionary is found to also have the renamed option.""" undeprecated_options = _CaseInsensitiveDictionary() ...
Issue appropriate warnings when deprecated options are present in the options dictionary. Removes deprecated option key, value pairs if the options dictionary is found to also have the renamed option.
Below is the the instruction that describes the task: ### Input: Issue appropriate warnings when deprecated options are present in the options dictionary. Removes deprecated option key, value pairs if the options dictionary is found to also have the renamed option. ### Response: def _handle_option_deprecat...
def get_image(vm_): ''' Return the image object to use ''' images = avail_images() vm_image = config.get_cloud_config_value( 'image', vm_, __opts__, search_global=False ) if not isinstance(vm_image, six.string_types): vm_image = six.text_type(vm_image) for image in image...
Return the image object to use
Below is the the instruction that describes the task: ### Input: Return the image object to use ### Response: def get_image(vm_): ''' Return the image object to use ''' images = avail_images() vm_image = config.get_cloud_config_value( 'image', vm_, __opts__, search_global=False ) ...
def get_alarms_list(self, num_items=100, params=None): """ Get alarms as list of dictionaries :param int num_items: Max items to retrieve :param dict params: Additional params dictionary according to: https://www.alienvault.com/documentation/api/usm-anywhere-api.htm#/alarms ...
Get alarms as list of dictionaries :param int num_items: Max items to retrieve :param dict params: Additional params dictionary according to: https://www.alienvault.com/documentation/api/usm-anywhere-api.htm#/alarms :returns list: list of alarms
Below is the the instruction that describes the task: ### Input: Get alarms as list of dictionaries :param int num_items: Max items to retrieve :param dict params: Additional params dictionary according to: https://www.alienvault.com/documentation/api/usm-anywhere-api.htm#/alarms ...
def validate_holdout_selfplay(): """Validate on held-out selfplay data.""" holdout_dirs = (os.path.join(fsdb.holdout_dir(), d) for d in reversed(gfile.ListDirectory(fsdb.holdout_dir())) if gfile.IsDirectory(os.path.join(fsdb.holdout_dir(), d)) for f in...
Validate on held-out selfplay data.
Below is the the instruction that describes the task: ### Input: Validate on held-out selfplay data. ### Response: def validate_holdout_selfplay(): """Validate on held-out selfplay data.""" holdout_dirs = (os.path.join(fsdb.holdout_dir(), d) for d in reversed(gfile.ListDirectory(fsdb.ho...
def deeper_conv_block(conv_layer, kernel_size, weighted=True): '''deeper conv layer. ''' n_dim = get_n_dim(conv_layer) filter_shape = (kernel_size,) * 2 n_filters = conv_layer.filters weight = np.zeros((n_filters, n_filters) + filter_shape) center = tuple(map(lambda x: int((x - 1) / 2), filt...
deeper conv layer.
Below is the the instruction that describes the task: ### Input: deeper conv layer. ### Response: def deeper_conv_block(conv_layer, kernel_size, weighted=True): '''deeper conv layer. ''' n_dim = get_n_dim(conv_layer) filter_shape = (kernel_size,) * 2 n_filters = conv_layer.filters weight = ...
def __create_chunk(self, frequency, play_time, sample_rate): ''' チャンクを生成する Args: frequency: 周波数 play_time: 再生時間(秒) sample_rate: サンプルレート Returns: チャンクのnumpy配列 ''' chunks = [] wave_form = se...
チャンクを生成する Args: frequency: 周波数 play_time: 再生時間(秒) sample_rate: サンプルレート Returns: チャンクのnumpy配列
Below is the the instruction that describes the task: ### Input: チャンクを生成する Args: frequency: 周波数 play_time: 再生時間(秒) sample_rate: サンプルレート Returns: チャンクのnumpy配列 ### Response: def __create_chunk(self, frequency, play_time, sample_ra...
def __get_max_date(self, reviews): """"Get the max date in unixtime format from reviews.""" max_ts = 0 for review in reviews: ts = str_to_datetime(review['timestamp']) ts = datetime_to_utc(ts) if ts.timestamp() > max_ts: max_ts = ts.timestamp()...
Get the max date in unixtime format from reviews.
Below is the the instruction that describes the task: ### Input: Get the max date in unixtime format from reviews. ### Response: def __get_max_date(self, reviews): """"Get the max date in unixtime format from reviews.""" max_ts = 0 for review in reviews: ts = str_to_datetime(rev...
def register(conf, conf_admin, **options): """ Register a new admin section. :param conf: A subclass of ``djconfig.admin.Config`` :param conf_admin: A subclass of ``djconfig.admin.ConfigAdmin`` :param options: Extra options passed to ``django.contrib.admin.site.register`` """ assert issubcl...
Register a new admin section. :param conf: A subclass of ``djconfig.admin.Config`` :param conf_admin: A subclass of ``djconfig.admin.ConfigAdmin`` :param options: Extra options passed to ``django.contrib.admin.site.register``
Below is the the instruction that describes the task: ### Input: Register a new admin section. :param conf: A subclass of ``djconfig.admin.Config`` :param conf_admin: A subclass of ``djconfig.admin.ConfigAdmin`` :param options: Extra options passed to ``django.contrib.admin.site.register`` ### Response...
def lock(self, atime=30, ltime=5, identifier=None): '''Context manager to acquire the namespace global lock. This is typically used for multi-step registry operations, such as a read-modify-write sequence:: with registry.lock() as session: d = session.get('dict', 'k...
Context manager to acquire the namespace global lock. This is typically used for multi-step registry operations, such as a read-modify-write sequence:: with registry.lock() as session: d = session.get('dict', 'key') del d['traceback'] session...
Below is the the instruction that describes the task: ### Input: Context manager to acquire the namespace global lock. This is typically used for multi-step registry operations, such as a read-modify-write sequence:: with registry.lock() as session: d = session.get('dic...
def find_package(name, installed, package=False): '''Finds a package in the installed list. If `package` is true, match package names, otherwise, match import paths. ''' if package: name = name.lower() tests = ( lambda x: x.user and name == x.name.lower(), lambda...
Finds a package in the installed list. If `package` is true, match package names, otherwise, match import paths.
Below is the the instruction that describes the task: ### Input: Finds a package in the installed list. If `package` is true, match package names, otherwise, match import paths. ### Response: def find_package(name, installed, package=False): '''Finds a package in the installed list. If `package` is t...
def regxy(pattern, response, supress_regex, custom): """Extract a string based on regex pattern supplied by user.""" try: matches = re.findall(r'%s' % pattern, response) for match in matches: verb('Custom regex', match) custom.add(match) except: supress_regex ...
Extract a string based on regex pattern supplied by user.
Below is the the instruction that describes the task: ### Input: Extract a string based on regex pattern supplied by user. ### Response: def regxy(pattern, response, supress_regex, custom): """Extract a string based on regex pattern supplied by user.""" try: matches = re.findall(r'%s' % pattern, re...
def squeezenet1_1(pretrained=False, **kwargs): r"""SqueezeNet 1.1 model from the `official SqueezeNet repo <https://github.com/DeepScale/SqueezeNet/tree/master/SqueezeNet_v1.1>`_. SqueezeNet 1.1 has 2.4x less computation and slightly fewer parameters than SqueezeNet 1.0, without sacrificing accuracy. ...
r"""SqueezeNet 1.1 model from the `official SqueezeNet repo <https://github.com/DeepScale/SqueezeNet/tree/master/SqueezeNet_v1.1>`_. SqueezeNet 1.1 has 2.4x less computation and slightly fewer parameters than SqueezeNet 1.0, without sacrificing accuracy. Args: pretrained (bool): If True, return...
Below is the the instruction that describes the task: ### Input: r"""SqueezeNet 1.1 model from the `official SqueezeNet repo <https://github.com/DeepScale/SqueezeNet/tree/master/SqueezeNet_v1.1>`_. SqueezeNet 1.1 has 2.4x less computation and slightly fewer parameters than SqueezeNet 1.0, without sacrif...
def main(args): """ Nibble's entry point. :param args: Command-line arguments, with the program in position 0. """ args = _parse_args(args) # sort out logging output and level level = util.log_level_from_vebosity(args.verbosity) root = logging.getLogger() root.setLevel(level) ...
Nibble's entry point. :param args: Command-line arguments, with the program in position 0.
Below is the the instruction that describes the task: ### Input: Nibble's entry point. :param args: Command-line arguments, with the program in position 0. ### Response: def main(args): """ Nibble's entry point. :param args: Command-line arguments, with the program in position 0. """ arg...
def handle(self, targetdir, app=None, **options): """ command execution """ translation.activate(settings.LANGUAGE_CODE) if app: unpack = app.split('.') if len(unpack) == 2: models = [get_model(unpack[0], unpack[1])] elif len(unpack) == 1: ...
command execution
Below is the the instruction that describes the task: ### Input: command execution ### Response: def handle(self, targetdir, app=None, **options): """ command execution """ translation.activate(settings.LANGUAGE_CODE) if app: unpack = app.split('.') if len(unpack) =...
def handle_input(self, input_str, place=True, check=False): '''Transfer user input to valid chess position''' user = self.get_player() pos = self.validate_input(input_str) if pos[0] == 'u': self.undo(pos[1]) return pos if place: result = self.s...
Transfer user input to valid chess position
Below is the the instruction that describes the task: ### Input: Transfer user input to valid chess position ### Response: def handle_input(self, input_str, place=True, check=False): '''Transfer user input to valid chess position''' user = self.get_player() pos = self.validate_input(input_s...
def predict(self, data): """ Predict new values by running data through the fit model. Parameters ---------- data : pandas.DataFrame Table with columns corresponding to the RHS of `model_expression`. Returns ------- predicted : ndarray ...
Predict new values by running data through the fit model. Parameters ---------- data : pandas.DataFrame Table with columns corresponding to the RHS of `model_expression`. Returns ------- predicted : ndarray Array of predicted values.
Below is the the instruction that describes the task: ### Input: Predict new values by running data through the fit model. Parameters ---------- data : pandas.DataFrame Table with columns corresponding to the RHS of `model_expression`. Returns ------- pr...
def iflag_unique_items(list_): """ Returns a list of flags corresponding to the first time an item is seen Args: list_ (list): list of items Returns: flag_iter """ seen = set() def unseen(item): if item in seen: return False seen.add(item) ...
Returns a list of flags corresponding to the first time an item is seen Args: list_ (list): list of items Returns: flag_iter
Below is the the instruction that describes the task: ### Input: Returns a list of flags corresponding to the first time an item is seen Args: list_ (list): list of items Returns: flag_iter ### Response: def iflag_unique_items(list_): """ Returns a list of flags corresponding to t...
def check_file_version(notebook, source_path, outputs_path): """Raise if file version in source file would override outputs""" if not insert_or_test_version_number(): return _, ext = os.path.splitext(source_path) if ext.endswith('.ipynb'): return version = notebook.metadata.get('jup...
Raise if file version in source file would override outputs
Below is the the instruction that describes the task: ### Input: Raise if file version in source file would override outputs ### Response: def check_file_version(notebook, source_path, outputs_path): """Raise if file version in source file would override outputs""" if not insert_or_test_version_number(): ...
def update(self): """Wrapper method to update the stats.""" # For standalone and server modes # For each plugins, call the update method for p in self._plugins: if self._plugins[p].is_disable(): # If current plugin is disable # then continue to...
Wrapper method to update the stats.
Below is the the instruction that describes the task: ### Input: Wrapper method to update the stats. ### Response: def update(self): """Wrapper method to update the stats.""" # For standalone and server modes # For each plugins, call the update method for p in self._plugins: ...
def get_themes(templates_path): """Returns available themes list.""" themes = os.listdir(templates_path) if '__common__' in themes: themes.remove('__common__') return themes
Returns available themes list.
Below is the the instruction that describes the task: ### Input: Returns available themes list. ### Response: def get_themes(templates_path): """Returns available themes list.""" themes = os.listdir(templates_path) if '__common__' in themes: themes.remove('__common__') return themes
def makeNodeTuple(citation, idVal, nodeInfo, fullInfo, nodeType, count, coreCitesDict, coreValues, detailedValues, addCR): """Makes a tuple of idVal and a dict of the selected attributes""" d = {} if nodeInfo: if nodeType == 'full': if coreValues: if citation in coreCites...
Makes a tuple of idVal and a dict of the selected attributes
Below is the the instruction that describes the task: ### Input: Makes a tuple of idVal and a dict of the selected attributes ### Response: def makeNodeTuple(citation, idVal, nodeInfo, fullInfo, nodeType, count, coreCitesDict, coreValues, detailedValues, addCR): """Makes a tuple of idVal and a dict of the sele...
def get_best_import_key(self, import_keys): """ Picks best RSA key for import from the import keys arrays. :param import_keys: :return: """ rsa2048 = None rsa1024 = None for c_key in import_keys: if c_key is None \ or 'type...
Picks best RSA key for import from the import keys arrays. :param import_keys: :return:
Below is the the instruction that describes the task: ### Input: Picks best RSA key for import from the import keys arrays. :param import_keys: :return: ### Response: def get_best_import_key(self, import_keys): """ Picks best RSA key for import from the import keys arrays. :...
def section(self, dept, course_number, sect_number): """Return a single section object for the given section. All arguments should be strings. Throws a `ValueError` if the section is not found. >>> lgst101_bfs = r.course('lgst', '101', '301') """ section_id = dept + course_numbe...
Return a single section object for the given section. All arguments should be strings. Throws a `ValueError` if the section is not found. >>> lgst101_bfs = r.course('lgst', '101', '301')
Below is the the instruction that describes the task: ### Input: Return a single section object for the given section. All arguments should be strings. Throws a `ValueError` if the section is not found. >>> lgst101_bfs = r.course('lgst', '101', '301') ### Response: def section(self, dept, course_n...
def get_next_page(self): """Returns the next page of results as a sequence of Album objects.""" master_node = self._retrieve_next_page() seq = [] for node in master_node.getElementsByTagName("album"): seq.append( Album( _extract(node, "ar...
Returns the next page of results as a sequence of Album objects.
Below is the the instruction that describes the task: ### Input: Returns the next page of results as a sequence of Album objects. ### Response: def get_next_page(self): """Returns the next page of results as a sequence of Album objects.""" master_node = self._retrieve_next_page() seq = []...
def stack(self, value): """The stack property. Args: value (string). the property value. """ if value == self._defaults['stack'] and 'stack' in self._values: del self._values['stack'] else: self._values['stack'] = value
The stack property. Args: value (string). the property value.
Below is the the instruction that describes the task: ### Input: The stack property. Args: value (string). the property value. ### Response: def stack(self, value): """The stack property. Args: value (string). the property value. """ ...
def Serialize(self, writer): """ Serialize full object. Args: writer (neo.IO.BinaryWriter): """ super(StorageItem, self).Serialize(writer) writer.WriteVarBytes(self.Value)
Serialize full object. Args: writer (neo.IO.BinaryWriter):
Below is the the instruction that describes the task: ### Input: Serialize full object. Args: writer (neo.IO.BinaryWriter): ### Response: def Serialize(self, writer): """ Serialize full object. Args: writer (neo.IO.BinaryWriter): """ super(S...
def handler(event, context): # pylint: disable=W0613 """ Historical security group event differ. Listens to the Historical current table and determines if there are differences that need to be persisted in the historical record. """ # De-serialize the records: records = deserialize_records...
Historical security group event differ. Listens to the Historical current table and determines if there are differences that need to be persisted in the historical record.
Below is the the instruction that describes the task: ### Input: Historical security group event differ. Listens to the Historical current table and determines if there are differences that need to be persisted in the historical record. ### Response: def handler(event, context): # pylint: disable=W0613 ...
def MD_restrained(dirname='MD_POSRES', **kwargs): """Set up MD with position restraints. Additional itp files should be in the same directory as the top file. Many of the keyword arguments below already have sensible values. Note that setting *mainselection* = ``None`` will disable many of the automat...
Set up MD with position restraints. Additional itp files should be in the same directory as the top file. Many of the keyword arguments below already have sensible values. Note that setting *mainselection* = ``None`` will disable many of the automated choices and is often recommended when using your o...
Below is the the instruction that describes the task: ### Input: Set up MD with position restraints. Additional itp files should be in the same directory as the top file. Many of the keyword arguments below already have sensible values. Note that setting *mainselection* = ``None`` will disable many of...
def create_simple_web_feature(o): """ Create an instance of SimpleWebFeature from a dict, o. If o does not match a Python feature object, simply return o. This function serves as a json decoder hook. See coding.load(). :param o: A dict to create the SimpleWebFeature from. :type o: dict :ret...
Create an instance of SimpleWebFeature from a dict, o. If o does not match a Python feature object, simply return o. This function serves as a json decoder hook. See coding.load(). :param o: A dict to create the SimpleWebFeature from. :type o: dict :return: A SimpleWebFeature from the dict provided...
Below is the the instruction that describes the task: ### Input: Create an instance of SimpleWebFeature from a dict, o. If o does not match a Python feature object, simply return o. This function serves as a json decoder hook. See coding.load(). :param o: A dict to create the SimpleWebFeature from. ...
def _query_systemstate(self): """Query the maximum number of connections supported by this adapter """ def status_filter_func(event): if event.command_class == 3 and event.command == 0: return True return False try: response = self._...
Query the maximum number of connections supported by this adapter
Below is the the instruction that describes the task: ### Input: Query the maximum number of connections supported by this adapter ### Response: def _query_systemstate(self): """Query the maximum number of connections supported by this adapter """ def status_filter_func(event): ...
def ensure_sphinx_astropy_installed(): """ Make sure that sphinx-astropy is available, installing it temporarily if not. This returns the available version of sphinx-astropy as well as any paths that should be added to sys.path for sphinx-astropy to be available. """ # We've split out the Sphin...
Make sure that sphinx-astropy is available, installing it temporarily if not. This returns the available version of sphinx-astropy as well as any paths that should be added to sys.path for sphinx-astropy to be available.
Below is the the instruction that describes the task: ### Input: Make sure that sphinx-astropy is available, installing it temporarily if not. This returns the available version of sphinx-astropy as well as any paths that should be added to sys.path for sphinx-astropy to be available. ### Response: def en...
def clear_cache(self): """Clear the raw packet cache for the field and all its subfields""" self.raw_packet_cache = None for _, fval in six.iteritems(self.fields): if isinstance(fval, Packet): fval.clear_cache() self.payload.clear_cache()
Clear the raw packet cache for the field and all its subfields
Below is the the instruction that describes the task: ### Input: Clear the raw packet cache for the field and all its subfields ### Response: def clear_cache(self): """Clear the raw packet cache for the field and all its subfields""" self.raw_packet_cache = None for _, fval in six.iteritems...
def buscar(self): """Faz a busca das informações do objeto no Postmon. Retorna um ``bool`` indicando se a busca foi bem sucedida. """ headers = {'User-Agent': self.user_agent} try: self._response = requests.get(self.url, headers=headers) except requests.Reque...
Faz a busca das informações do objeto no Postmon. Retorna um ``bool`` indicando se a busca foi bem sucedida.
Below is the the instruction that describes the task: ### Input: Faz a busca das informações do objeto no Postmon. Retorna um ``bool`` indicando se a busca foi bem sucedida. ### Response: def buscar(self): """Faz a busca das informações do objeto no Postmon. Retorna um ``bool`` indicando ...
def update_points(self): """ 椭圆的近似图形:72边形 """ n = max(8, min(72, int(2*sqrt(self.r_x+self.r_y)))) d = pi * 2 / n x, y, r_x, r_y = self.x, self.y, self.r_x, self.r_y ps = [] for i in range(n): ps += [(x + r_x * sin(d * i)), (y + r_y * cos(d * i))] self...
椭圆的近似图形:72边形
Below is the the instruction that describes the task: ### Input: 椭圆的近似图形:72边形 ### Response: def update_points(self): """ 椭圆的近似图形:72边形 """ n = max(8, min(72, int(2*sqrt(self.r_x+self.r_y)))) d = pi * 2 / n x, y, r_x, r_y = self.x, self.y, self.r_x, self.r_y ps = [] f...
def account_representative_set(self, wallet, account, representative, work=None): """ Sets the representative for **account** in **wallet** .. enable_control required :param wallet: Wallet to use for account :type wallet: str :param account: Account to set representati...
Sets the representative for **account** in **wallet** .. enable_control required :param wallet: Wallet to use for account :type wallet: str :param account: Account to set representative for :type account: str :param representative: Representative to set to :ty...
Below is the the instruction that describes the task: ### Input: Sets the representative for **account** in **wallet** .. enable_control required :param wallet: Wallet to use for account :type wallet: str :param account: Account to set representative for :type account: str...
def search_pattern(regex): """ Return a value check function which raises a ValueError if the supplied regular expression does not match anywhere in the value, see also `re.search`. """ prog = re.compile(regex) def checker(v): result = prog.search(v) if result is None: ...
Return a value check function which raises a ValueError if the supplied regular expression does not match anywhere in the value, see also `re.search`.
Below is the the instruction that describes the task: ### Input: Return a value check function which raises a ValueError if the supplied regular expression does not match anywhere in the value, see also `re.search`. ### Response: def search_pattern(regex): """ Return a value check function which ra...
def Brock_Bird(T, Tb, Tc, Pc): r'''Calculates air-water surface tension using the [1]_ emperical method. Old and tested. .. math:: \sigma = P_c^{2/3}T_c^{1/3}Q(1-T_r)^{11/9} Q = 0.1196 \left[ 1 + \frac{T_{br}\ln (P_c/1.01325)}{1-T_{br}}\right]-0.279 Parameters ---------- T : ...
r'''Calculates air-water surface tension using the [1]_ emperical method. Old and tested. .. math:: \sigma = P_c^{2/3}T_c^{1/3}Q(1-T_r)^{11/9} Q = 0.1196 \left[ 1 + \frac{T_{br}\ln (P_c/1.01325)}{1-T_{br}}\right]-0.279 Parameters ---------- T : float Temperature of fluid ...
Below is the the instruction that describes the task: ### Input: r'''Calculates air-water surface tension using the [1]_ emperical method. Old and tested. .. math:: \sigma = P_c^{2/3}T_c^{1/3}Q(1-T_r)^{11/9} Q = 0.1196 \left[ 1 + \frac{T_{br}\ln (P_c/1.01325)}{1-T_{br}}\right]-0.279 ...
def endswith_strip(s, endswith='.txt', ignorecase=True): """ Strip a suffix from the end of a string >>> endswith_strip('http://TotalGood.com', '.COM') 'http://TotalGood' >>> endswith_strip('http://TotalGood.com', endswith='.COM', ignorecase=False) 'http://TotalGood.com' """ if ignorecase: ...
Strip a suffix from the end of a string >>> endswith_strip('http://TotalGood.com', '.COM') 'http://TotalGood' >>> endswith_strip('http://TotalGood.com', endswith='.COM', ignorecase=False) 'http://TotalGood.com'
Below is the the instruction that describes the task: ### Input: Strip a suffix from the end of a string >>> endswith_strip('http://TotalGood.com', '.COM') 'http://TotalGood' >>> endswith_strip('http://TotalGood.com', endswith='.COM', ignorecase=False) 'http://TotalGood.com' ### Response: def ends...
def _getEventsByWeek(self, request, year, month): """Return my child events for the given month grouped by week.""" return getAllEventsByWeek(request, year, month, home=self)
Return my child events for the given month grouped by week.
Below is the the instruction that describes the task: ### Input: Return my child events for the given month grouped by week. ### Response: def _getEventsByWeek(self, request, year, month): """Return my child events for the given month grouped by week.""" return getAllEventsByWeek(request, year, mon...
def pv_present(name, **kwargs): ''' Set a Physical Device to be used as an LVM Physical Volume name The device name to initialize. kwargs Any supported options to pvcreate. See :mod:`linux_lvm <salt.modules.linux_lvm>` for more details. ''' ret = {'changes': {}, ...
Set a Physical Device to be used as an LVM Physical Volume name The device name to initialize. kwargs Any supported options to pvcreate. See :mod:`linux_lvm <salt.modules.linux_lvm>` for more details.
Below is the the instruction that describes the task: ### Input: Set a Physical Device to be used as an LVM Physical Volume name The device name to initialize. kwargs Any supported options to pvcreate. See :mod:`linux_lvm <salt.modules.linux_lvm>` for more details. ### Response: d...
def roc(series, window=14): """ compute rate of change """ res = (series - series.shift(window)) / series.shift(window) return pd.Series(index=series.index, data=res)
compute rate of change
Below is the the instruction that describes the task: ### Input: compute rate of change ### Response: def roc(series, window=14): """ compute rate of change """ res = (series - series.shift(window)) / series.shift(window) return pd.Series(index=series.index, data=res)
def get_origin(tp): """Get the unsubscripted version of a type. Supports generic types, Union, Callable, and Tuple. Returns None for unsupported types. Examples:: get_origin(int) == None get_origin(ClassVar[int]) == None get_origin(Generic) == Generic get_origin(Generic[T]) == G...
Get the unsubscripted version of a type. Supports generic types, Union, Callable, and Tuple. Returns None for unsupported types. Examples:: get_origin(int) == None get_origin(ClassVar[int]) == None get_origin(Generic) == Generic get_origin(Generic[T]) == Generic get_origin(U...
Below is the the instruction that describes the task: ### Input: Get the unsubscripted version of a type. Supports generic types, Union, Callable, and Tuple. Returns None for unsupported types. Examples:: get_origin(int) == None get_origin(ClassVar[int]) == None get_origin(Generic) == G...
def get_table_description(self, cursor, table_name): "Returns a description of the table, with the DB-API cursor.description interface." # pylint:disable=too-many-locals,unused-argument result = [] for field in self.table_description_cache(table_name)['fields']: params = Orde...
Returns a description of the table, with the DB-API cursor.description interface.
Below is the the instruction that describes the task: ### Input: Returns a description of the table, with the DB-API cursor.description interface. ### Response: def get_table_description(self, cursor, table_name): "Returns a description of the table, with the DB-API cursor.description interface." #...
def get_ancestor_hash(self, block_number: int) -> Hash32: """ Return the hash for the ancestor block with number ``block_number``. Return the empty bytestring ``b''`` if the block number is outside of the range of available block numbers (typically the last 255 blocks). """ ...
Return the hash for the ancestor block with number ``block_number``. Return the empty bytestring ``b''`` if the block number is outside of the range of available block numbers (typically the last 255 blocks).
Below is the the instruction that describes the task: ### Input: Return the hash for the ancestor block with number ``block_number``. Return the empty bytestring ``b''`` if the block number is outside of the range of available block numbers (typically the last 255 blocks). ### Response: def get_anc...
def differences_between(self, current_files, parent_files, changes, prefixes): """ yield (thing, changes, is_path) If is_path is true, changes is None and thing is the path as a tuple. If is_path is false, thing is the current_files and parent_files for that changed treeentry a...
yield (thing, changes, is_path) If is_path is true, changes is None and thing is the path as a tuple. If is_path is false, thing is the current_files and parent_files for that changed treeentry and changes is the difference between current_files and parent_files. The code here...
Below is the the instruction that describes the task: ### Input: yield (thing, changes, is_path) If is_path is true, changes is None and thing is the path as a tuple. If is_path is false, thing is the current_files and parent_files for that changed treeentry and changes is the difference b...
def warn_deprecated(message, stacklevel=2): # pragma: no cover """Warn deprecated.""" warnings.warn( message, category=DeprecationWarning, stacklevel=stacklevel )
Warn deprecated.
Below is the the instruction that describes the task: ### Input: Warn deprecated. ### Response: def warn_deprecated(message, stacklevel=2): # pragma: no cover """Warn deprecated.""" warnings.warn( message, category=DeprecationWarning, stacklevel=stacklevel )
def itake_column(list_, colx): """ iterator version of get_list_column """ if isinstance(colx, list): # multi select return ([row[colx_] for colx_ in colx] for row in list_) else: return (row[colx] for row in list_)
iterator version of get_list_column
Below is the the instruction that describes the task: ### Input: iterator version of get_list_column ### Response: def itake_column(list_, colx): """ iterator version of get_list_column """ if isinstance(colx, list): # multi select return ([row[colx_] for colx_ in colx] for row in list_) ...
def get_boolean(self, input_string): """ Return boolean type user input """ if input_string in ('--write_roc', '--plot', '--compare'): # was the flag set? try: index = self.args.index(input_string) + 1 except ValueError: # it wasn...
Return boolean type user input
Below is the the instruction that describes the task: ### Input: Return boolean type user input ### Response: def get_boolean(self, input_string): """ Return boolean type user input """ if input_string in ('--write_roc', '--plot', '--compare'): # was the flag set? try:...
def get_all(): ''' Return a list of all available services CLI Example: .. code-block:: bash salt '*' service.get_all ''' if not os.path.isdir(_GRAINMAP.get(__grains__.get('os'), '/etc/init.d')): return [] return sorted(os.listdir(_GRAINMAP.get(__grains__.get('os'), '/etc/...
Return a list of all available services CLI Example: .. code-block:: bash salt '*' service.get_all
Below is the the instruction that describes the task: ### Input: Return a list of all available services CLI Example: .. code-block:: bash salt '*' service.get_all ### Response: def get_all(): ''' Return a list of all available services CLI Example: .. code-block:: bash ...
def verify_docker_image_sha(chain, link): """Verify that built docker shas match the artifact. Args: chain (ChainOfTrust): the chain we're operating on. link (LinkOfTrust): the task link we're checking. Raises: CoTError: on failure. """ cot = link.cot task = link.task ...
Verify that built docker shas match the artifact. Args: chain (ChainOfTrust): the chain we're operating on. link (LinkOfTrust): the task link we're checking. Raises: CoTError: on failure.
Below is the the instruction that describes the task: ### Input: Verify that built docker shas match the artifact. Args: chain (ChainOfTrust): the chain we're operating on. link (LinkOfTrust): the task link we're checking. Raises: CoTError: on failure. ### Response: def verify_doc...
def get_workflows() -> dict: """Get dict of ALL known workflow definitions. Returns list[dict] """ keys = DB.get_keys("workflow_definitions:*") known_workflows = dict() for key in keys: values = key.split(':') if values[1] not in known_workflows: known_workf...
Get dict of ALL known workflow definitions. Returns list[dict]
Below is the the instruction that describes the task: ### Input: Get dict of ALL known workflow definitions. Returns list[dict] ### Response: def get_workflows() -> dict: """Get dict of ALL known workflow definitions. Returns list[dict] """ keys = DB.get_keys("workflow_defini...
def _get_ssh_public_key(self): """Generate SSH public key from private key.""" key = ipa_utils.generate_public_ssh_key(self.ssh_private_key_file) return '{user}:{key} {user}'.format( user=self.ssh_user, key=key.decode() )
Generate SSH public key from private key.
Below is the the instruction that describes the task: ### Input: Generate SSH public key from private key. ### Response: def _get_ssh_public_key(self): """Generate SSH public key from private key.""" key = ipa_utils.generate_public_ssh_key(self.ssh_private_key_file) return '{user}:{key} {us...
def general_stats_addcols(self, data, headers=None, namespace=None): """ Helper function to add to the General Statistics variable. Adds to report.general_stats and does not return anything. Fills in required config variables if not supplied. :param data: A dict with the data. First key ...
Helper function to add to the General Statistics variable. Adds to report.general_stats and does not return anything. Fills in required config variables if not supplied. :param data: A dict with the data. First key should be sample name, then the data key, then the data. ...
Below is the the instruction that describes the task: ### Input: Helper function to add to the General Statistics variable. Adds to report.general_stats and does not return anything. Fills in required config variables if not supplied. :param data: A dict with the data. First key should be sa...
def calculate_time_difference(startDate, endDate): """ *Return the time difference between two dates as a string* **Key Arguments:** - ``startDate`` -- the first date in YYYY-MM-DDTHH:MM:SS format - ``endDate`` -- the final date YYYY-MM-DDTHH:MM:SS format **Return:** - ``relTim...
*Return the time difference between two dates as a string* **Key Arguments:** - ``startDate`` -- the first date in YYYY-MM-DDTHH:MM:SS format - ``endDate`` -- the final date YYYY-MM-DDTHH:MM:SS format **Return:** - ``relTime`` -- the difference between the two dates in Y,M,D,h,m,s (str...
Below is the the instruction that describes the task: ### Input: *Return the time difference between two dates as a string* **Key Arguments:** - ``startDate`` -- the first date in YYYY-MM-DDTHH:MM:SS format - ``endDate`` -- the final date YYYY-MM-DDTHH:MM:SS format **Return:** - ``...
def selectedNodes( self ): """ Returns a list of the selected nodes in a scene. :return <list> [ <XNode>, .. ] """ output = [] for item in self.selectedItems(): if ( isinstance(item, XNode) ): output.append(item) return out...
Returns a list of the selected nodes in a scene. :return <list> [ <XNode>, .. ]
Below is the the instruction that describes the task: ### Input: Returns a list of the selected nodes in a scene. :return <list> [ <XNode>, .. ] ### Response: def selectedNodes( self ): """ Returns a list of the selected nodes in a scene. :return <list> [ <...
def make_Hs_implicit(original_mol, keep_stereo=True): """Return molecule that explicit hydrogens removed TODO: this query function should be renamed to "explicitHs_removed" """ mol = clone(original_mol) mol.descriptors.clear() # Reset descriptor to_remove = set() for i, nbrs in mol.neighbor...
Return molecule that explicit hydrogens removed TODO: this query function should be renamed to "explicitHs_removed"
Below is the the instruction that describes the task: ### Input: Return molecule that explicit hydrogens removed TODO: this query function should be renamed to "explicitHs_removed" ### Response: def make_Hs_implicit(original_mol, keep_stereo=True): """Return molecule that explicit hydrogens removed TOD...
def _extractAssociation(self, assoc_response, assoc_session): """Attempt to extract an association from the response, given the association response message and the established association session. @param assoc_response: The association response message from the server ...
Attempt to extract an association from the response, given the association response message and the established association session. @param assoc_response: The association response message from the server @type assoc_response: openid.message.Message @param assoc_ses...
Below is the the instruction that describes the task: ### Input: Attempt to extract an association from the response, given the association response message and the established association session. @param assoc_response: The association response message from the server @...
def op_at_code_loc(code, loc, opc): """Return the instruction name at code[loc] using opc to look up instruction names. Returns 'got IndexError' if code[loc] is invalid. `code` is instruction bytecode, `loc` is an offset (integer) and `opc` is an opcode module from `xdis`. """ try: ...
Return the instruction name at code[loc] using opc to look up instruction names. Returns 'got IndexError' if code[loc] is invalid. `code` is instruction bytecode, `loc` is an offset (integer) and `opc` is an opcode module from `xdis`.
Below is the the instruction that describes the task: ### Input: Return the instruction name at code[loc] using opc to look up instruction names. Returns 'got IndexError' if code[loc] is invalid. `code` is instruction bytecode, `loc` is an offset (integer) and `opc` is an opcode module from `xdis`....
def clean_intersections(G, tolerance=15, dead_ends=False): """ Clean-up intersections comprising clusters of nodes by merging them and returning their centroids. Divided roads are represented by separate centerline edges. The intersection of two divided roads thus creates 4 nodes, representing wher...
Clean-up intersections comprising clusters of nodes by merging them and returning their centroids. Divided roads are represented by separate centerline edges. The intersection of two divided roads thus creates 4 nodes, representing where each edge intersects a perpendicular edge. These 4 nodes represen...
Below is the the instruction that describes the task: ### Input: Clean-up intersections comprising clusters of nodes by merging them and returning their centroids. Divided roads are represented by separate centerline edges. The intersection of two divided roads thus creates 4 nodes, representing where ...
def plot_graph_route(G, route, bbox=None, fig_height=6, fig_width=None, margin=0.02, bgcolor='w', axis_off=True, show=True, save=False, close=True, file_format='png', filename='temp', dpi=300, annotate=False, node_color='#999999', node_...
Plot a route along a networkx spatial graph. Parameters ---------- G : networkx multidigraph route : list the route as a list of nodes bbox : tuple bounding box as north,south,east,west - if None will calculate from spatial extents of data. if passing a bbox, you probably al...
Below is the the instruction that describes the task: ### Input: Plot a route along a networkx spatial graph. Parameters ---------- G : networkx multidigraph route : list the route as a list of nodes bbox : tuple bounding box as north,south,east,west - if None will calculate fro...
def threadpooled( func: typing.Callable[..., typing.Union["typing.Awaitable[typing.Any]", typing.Any]], *, loop_getter: None = None, loop_getter_need_context: bool = False, ) -> typing.Callable[..., "concurrent.futures.Future[typing.Any]"]: """Overload: function callable, no loop getter."""
Overload: function callable, no loop getter.
Below is the the instruction that describes the task: ### Input: Overload: function callable, no loop getter. ### Response: def threadpooled( func: typing.Callable[..., typing.Union["typing.Awaitable[typing.Any]", typing.Any]], *, loop_getter: None = None, loop_getter_need_context: bool = False, ) ...
def histogram(self, data, bins=10, color='w', orientation='h'): """Calculate and show a histogram of data Parameters ---------- data : array-like Data to histogram. Currently only 1D data is supported. bins : int | array-like Number of bins, or bin edges....
Calculate and show a histogram of data Parameters ---------- data : array-like Data to histogram. Currently only 1D data is supported. bins : int | array-like Number of bins, or bin edges. color : instance of Color Color of the histogram. ...
Below is the the instruction that describes the task: ### Input: Calculate and show a histogram of data Parameters ---------- data : array-like Data to histogram. Currently only 1D data is supported. bins : int | array-like Number of bins, or bin edges. ...