code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def great_circle_dist(lat1, lon1, lat2, lon2): """ Get the distance (in meters) between two lat/lon points via the Haversine formula. Parameters ---------- lat1, lon1, lat2, lon2 : float Latitude and longitude in degrees. Returns ------- dist : float Distance in met...
Get the distance (in meters) between two lat/lon points via the Haversine formula. Parameters ---------- lat1, lon1, lat2, lon2 : float Latitude and longitude in degrees. Returns ------- dist : float Distance in meters.
Below is the the instruction that describes the task: ### Input: Get the distance (in meters) between two lat/lon points via the Haversine formula. Parameters ---------- lat1, lon1, lat2, lon2 : float Latitude and longitude in degrees. Returns ------- dist : float Dista...
def parse_agi_result(line): """Parse AGI results using Regular expression. AGI Result examples:: 100 result=0 Trying... 200 result=0 200 result=-1 200 result=132456 200 result= (timeout) 510 Invalid or unknown command 520-Invalid command syntax. Pr...
Parse AGI results using Regular expression. AGI Result examples:: 100 result=0 Trying... 200 result=0 200 result=-1 200 result=132456 200 result= (timeout) 510 Invalid or unknown command 520-Invalid command syntax. Proper usage follows: int() a...
Below is the the instruction that describes the task: ### Input: Parse AGI results using Regular expression. AGI Result examples:: 100 result=0 Trying... 200 result=0 200 result=-1 200 result=132456 200 result= (timeout) 510 Invalid or unknown command ...
def addhash(frame,**kw): ''' helper function to add hashes to the given frame given in the dictionary d returned from firsthash. Parameters: ----------- frame : frame to hash. Keywords: --------- same as genhash Returns frame with added hashes, although it will be add...
helper function to add hashes to the given frame given in the dictionary d returned from firsthash. Parameters: ----------- frame : frame to hash. Keywords: --------- same as genhash Returns frame with added hashes, although it will be added in place.
Below is the the instruction that describes the task: ### Input: helper function to add hashes to the given frame given in the dictionary d returned from firsthash. Parameters: ----------- frame : frame to hash. Keywords: --------- same as genhash Returns frame with added...
def should_execute(self, workload): """ If we have been suspended by i3bar, only execute those modules that set the keep_alive flag to a truthy value. See the docs on the suspend_signal_handler method of the io module for more information. """ if not self._suspended.is_set(): ...
If we have been suspended by i3bar, only execute those modules that set the keep_alive flag to a truthy value. See the docs on the suspend_signal_handler method of the io module for more information.
Below is the the instruction that describes the task: ### Input: If we have been suspended by i3bar, only execute those modules that set the keep_alive flag to a truthy value. See the docs on the suspend_signal_handler method of the io module for more information. ### Response: def should_execute(self, wor...
def add_store(name, store, saltenv='base'): ''' Store a certificate to the given store name The certificate to store, this can use local paths or salt:// paths store The store to add the certificate to saltenv The salt environment to use, this is ignored if a local...
Store a certificate to the given store name The certificate to store, this can use local paths or salt:// paths store The store to add the certificate to saltenv The salt environment to use, this is ignored if a local path is specified
Below is the the instruction that describes the task: ### Input: Store a certificate to the given store name The certificate to store, this can use local paths or salt:// paths store The store to add the certificate to saltenv The salt environment to use, this is ignor...
def _data_frame(content): """ Helper funcation that converts text-based get response to a pandas dataframe for additional manipulation. """ response = loads(content) key = [x for x in response.keys() if x in c.response_data][0] frame = DataFrame(response[key]) final_frame = _convert(fram...
Helper funcation that converts text-based get response to a pandas dataframe for additional manipulation.
Below is the the instruction that describes the task: ### Input: Helper funcation that converts text-based get response to a pandas dataframe for additional manipulation. ### Response: def _data_frame(content): """ Helper funcation that converts text-based get response to a pandas dataframe for add...
def from_spec(spec, kwargs=None): """ Creates a baseline from a specification dict. """ baseline = util.get_object( obj=spec, predefined_objects=tensorforce.core.baselines.baselines, kwargs=kwargs ) assert isinstance(baseline, Baseline)...
Creates a baseline from a specification dict.
Below is the the instruction that describes the task: ### Input: Creates a baseline from a specification dict. ### Response: def from_spec(spec, kwargs=None): """ Creates a baseline from a specification dict. """ baseline = util.get_object( obj=spec, predefin...
def get_payment_token_by_id(cls, payment_token_id, **kwargs): """Find PaymentToken Return single instance of PaymentToken by its ID. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_payment...
Find PaymentToken Return single instance of PaymentToken by its ID. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_payment_token_by_id(payment_token_id, async=True) >>> result = thread.ge...
Below is the the instruction that describes the task: ### Input: Find PaymentToken Return single instance of PaymentToken by its ID. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_payment_tok...
def from_edges(edges, source_key='source', target_key='target', weight_key='weight', directed=True): """ Given a List of Dictionaries with source, target, and weight attributes, return a weighted, directed graph. """ raw = list(map(lambda x: [x[source_key], x[target_key], int(x[weight_key])], edges)) ...
Given a List of Dictionaries with source, target, and weight attributes, return a weighted, directed graph.
Below is the the instruction that describes the task: ### Input: Given a List of Dictionaries with source, target, and weight attributes, return a weighted, directed graph. ### Response: def from_edges(edges, source_key='source', target_key='target', weight_key='weight', directed=True): """ Given a List of...
def create_volume(self, volume_name: str, driver_spec: str = None): """Create new docker volumes. Only the manager nodes can create a volume Args: volume_name (string): Name for the new docker volume driver_spec (string): Driver for the docker volume """ ...
Create new docker volumes. Only the manager nodes can create a volume Args: volume_name (string): Name for the new docker volume driver_spec (string): Driver for the docker volume
Below is the the instruction that describes the task: ### Input: Create new docker volumes. Only the manager nodes can create a volume Args: volume_name (string): Name for the new docker volume driver_spec (string): Driver for the docker volume ### Response: def create_vol...
def password_set(username=None, password=None): """ Stores a password in a keychain for a particular environment and configuration parameter pair. """ result = keyring.set_password('supernova', username, password) # NOTE: keyring returns None when the storage is successful. That's weird. i...
Stores a password in a keychain for a particular environment and configuration parameter pair.
Below is the the instruction that describes the task: ### Input: Stores a password in a keychain for a particular environment and configuration parameter pair. ### Response: def password_set(username=None, password=None): """ Stores a password in a keychain for a particular environment and configur...
def _apply_worksheet_template_duplicate_analyses(self, wst): """Add duplicate analyses to worksheet according to the worksheet template layout passed in w/o overwrite slots that are already filled. If the slot where the duplicate must be located is available, but the slot where the rout...
Add duplicate analyses to worksheet according to the worksheet template layout passed in w/o overwrite slots that are already filled. If the slot where the duplicate must be located is available, but the slot where the routine analysis should be found is empty, no duplicate will be gene...
Below is the the instruction that describes the task: ### Input: Add duplicate analyses to worksheet according to the worksheet template layout passed in w/o overwrite slots that are already filled. If the slot where the duplicate must be located is available, but the slot where the routine...
def orderedclasses(self, set_uri_or_id=None, nestedhierarchy=False): """Higher-order generator function that yields class information in the right order, combines calls to :meth:`SetDefinition.classes` and :meth:`SetDefinition.classorder`""" classes = self.classes(set_uri_or_id, nestedhierarchy) ...
Higher-order generator function that yields class information in the right order, combines calls to :meth:`SetDefinition.classes` and :meth:`SetDefinition.classorder`
Below is the the instruction that describes the task: ### Input: Higher-order generator function that yields class information in the right order, combines calls to :meth:`SetDefinition.classes` and :meth:`SetDefinition.classorder` ### Response: def orderedclasses(self, set_uri_or_id=None, nestedhierarchy=False): ...
def onscroll(self, event): """Action to be taken when an event is triggered. Event is scroll of the mouse's wheel. This leads to changing the temporal frame displayed. :param event: Scroll of mouse wheel """ if event.button == 'up': self.ind = (self.ind + 1)...
Action to be taken when an event is triggered. Event is scroll of the mouse's wheel. This leads to changing the temporal frame displayed. :param event: Scroll of mouse wheel
Below is the the instruction that describes the task: ### Input: Action to be taken when an event is triggered. Event is scroll of the mouse's wheel. This leads to changing the temporal frame displayed. :param event: Scroll of mouse wheel ### Response: def onscroll(self, event): """A...
def get_verified_jwt( providers, audiences, check_authorization_header=True, check_query_arg=True, request=None, cache=memcache): """ This function will extract, verify, and parse a JWT token from the Authorization header or access_token query argument. The JWT is assumed to contain an issuer and a...
This function will extract, verify, and parse a JWT token from the Authorization header or access_token query argument. The JWT is assumed to contain an issuer and audience claim, as well as issued-at and expiration timestamps. The signature will be cryptographically verified, the claims and timestamps will be...
Below is the the instruction that describes the task: ### Input: This function will extract, verify, and parse a JWT token from the Authorization header or access_token query argument. The JWT is assumed to contain an issuer and audience claim, as well as issued-at and expiration timestamps. The signature wi...
def find_tags_from_xml( self, xml_name, tag_name, **attribute_filter ): """ Return a list of all the matched tags in a specific xml w :param str xml_name: specify from which xml to pick the tag from :param str tag_name: specify the tag name """ xml = s...
Return a list of all the matched tags in a specific xml w :param str xml_name: specify from which xml to pick the tag from :param str tag_name: specify the tag name
Below is the the instruction that describes the task: ### Input: Return a list of all the matched tags in a specific xml w :param str xml_name: specify from which xml to pick the tag from :param str tag_name: specify the tag name ### Response: def find_tags_from_xml( self, xml_name,...
def get_versions(name, default_string=DEFAULT_STRING_NOT_FOUND, default_tuple=DEFAULT_TUPLE_NOT_FOUND, allow_ambiguous=True): """ Get string and tuple versions from installed package information It will return :attr:`default_string` and :attr:`default_tupl...
Get string and tuple versions from installed package information It will return :attr:`default_string` and :attr:`default_tuple` values when the named package is not installed. Parameters ----------- name : string An application name used to install via setuptools. default : string ...
Below is the the instruction that describes the task: ### Input: Get string and tuple versions from installed package information It will return :attr:`default_string` and :attr:`default_tuple` values when the named package is not installed. Parameters ----------- name : string An appl...
def reference_preprocessing(job, samples, config): """ Spawn the jobs that create index and dict file for reference :param JobFunctionWrappingJob job: passed automatically by Toil :param Namespace config: Argparse Namespace object containing argument inputs :param list[list] samples: A nested list ...
Spawn the jobs that create index and dict file for reference :param JobFunctionWrappingJob job: passed automatically by Toil :param Namespace config: Argparse Namespace object containing argument inputs :param list[list] samples: A nested list of samples containing sample information
Below is the the instruction that describes the task: ### Input: Spawn the jobs that create index and dict file for reference :param JobFunctionWrappingJob job: passed automatically by Toil :param Namespace config: Argparse Namespace object containing argument inputs :param list[list] samples: A nested...
def get_state_variable_from_storage( self, address: str, params: Optional[List[str]] = None ) -> str: """ Get variables from the storage :param address: The contract address :param params: The list of parameters param types: [position, length] or ["map...
Get variables from the storage :param address: The contract address :param params: The list of parameters param types: [position, length] or ["mapping", position, key1, key2, ... ] or [position, length, array] :return: The corresponding storage sl...
Below is the the instruction that describes the task: ### Input: Get variables from the storage :param address: The contract address :param params: The list of parameters param types: [position, length] or ["mapping", position, key1, key2, ... ] or [p...
def set_irc_targets(self, bot, *targets): """Add a irc Handler using bot and log to targets (can be nicks or channels: .. >>> bot = None .. code-block:: python >>> log = logging.getLogger('irc.mymodule') >>> log.set_irc_targets(bot, '#chan', 'admin'...
Add a irc Handler using bot and log to targets (can be nicks or channels: .. >>> bot = None .. code-block:: python >>> log = logging.getLogger('irc.mymodule') >>> log.set_irc_targets(bot, '#chan', 'admin')
Below is the the instruction that describes the task: ### Input: Add a irc Handler using bot and log to targets (can be nicks or channels: .. >>> bot = None .. code-block:: python >>> log = logging.getLogger('irc.mymodule') >>> log.set_irc_targets(bot, ...
def load(self, client, webpy_app, course_factory, task_factory, database, user_manager, submission_manager, config): """ Loads the plugin manager. Must be done after the initialisation of the client """ self._app = webpy_app self._task_factory = task_factory self._database = database ...
Loads the plugin manager. Must be done after the initialisation of the client
Below is the the instruction that describes the task: ### Input: Loads the plugin manager. Must be done after the initialisation of the client ### Response: def load(self, client, webpy_app, course_factory, task_factory, database, user_manager, submission_manager, config): """ Loads the plugin manager. Mus...
def temperature_effectiveness_TEMA_J(R1, NTU1, Ntp): r'''Returns temperature effectiveness `P1` of a TEMA J type heat exchanger with a specified heat capacity ratio, number of transfer units `NTU1`, and of number of tube passes `Ntp`. The supported cases are as follows: * One tube pass (shell...
r'''Returns temperature effectiveness `P1` of a TEMA J type heat exchanger with a specified heat capacity ratio, number of transfer units `NTU1`, and of number of tube passes `Ntp`. The supported cases are as follows: * One tube pass (shell fluid mixed) * Two tube passes (shell fluid mixed, t...
Below is the the instruction that describes the task: ### Input: r'''Returns temperature effectiveness `P1` of a TEMA J type heat exchanger with a specified heat capacity ratio, number of transfer units `NTU1`, and of number of tube passes `Ntp`. The supported cases are as follows: * One tube...
def associated_parts(self, *args, **kwargs): """Retrieve models and instances belonging to this activity. This is a convenience method for the :func:`Activity.parts()` method, which is used to retrieve both the `Category.MODEL` as well as the `Category.INSTANCE` in a tuple. This call o...
Retrieve models and instances belonging to this activity. This is a convenience method for the :func:`Activity.parts()` method, which is used to retrieve both the `Category.MODEL` as well as the `Category.INSTANCE` in a tuple. This call only returns the configured properties in an activity. So...
Below is the the instruction that describes the task: ### Input: Retrieve models and instances belonging to this activity. This is a convenience method for the :func:`Activity.parts()` method, which is used to retrieve both the `Category.MODEL` as well as the `Category.INSTANCE` in a tuple. ...
def find(self, sub, start=0, end=None): """Test if elements contain substring. Parameters ---------- sub : str start : int, optional Index to start searching from. end : int, optional Index to stop searching from. Returns ------- ...
Test if elements contain substring. Parameters ---------- sub : str start : int, optional Index to start searching from. end : int, optional Index to stop searching from. Returns ------- Series
Below is the the instruction that describes the task: ### Input: Test if elements contain substring. Parameters ---------- sub : str start : int, optional Index to start searching from. end : int, optional Index to stop searching from. Return...
def _read(self, directory, filename, session, path, name, extension, spatial, spatialReferenceID, replaceParamFile): """ Read HMET WES from File Method """ # Set file extension property self.fileExtension = extension # Open file and parse into HmetRecords with op...
Read HMET WES from File Method
Below is the the instruction that describes the task: ### Input: Read HMET WES from File Method ### Response: def _read(self, directory, filename, session, path, name, extension, spatial, spatialReferenceID, replaceParamFile): """ Read HMET WES from File Method """ # Set file extens...
def is_endpoint(G, node, strict=True): """ Return True if the node is a "real" endpoint of an edge in the network, \ otherwise False. OSM data includes lots of nodes that exist only as points \ to help streets bend around curves. An end point is a node that either: \ 1) is its own neighbor, ie, it s...
Return True if the node is a "real" endpoint of an edge in the network, \ otherwise False. OSM data includes lots of nodes that exist only as points \ to help streets bend around curves. An end point is a node that either: \ 1) is its own neighbor, ie, it self-loops. \ 2) or, has no incoming edges or no...
Below is the the instruction that describes the task: ### Input: Return True if the node is a "real" endpoint of an edge in the network, \ otherwise False. OSM data includes lots of nodes that exist only as points \ to help streets bend around curves. An end point is a node that either: \ 1) is its own ...
def get_version(cls, name): """ Checks a string for a possible version of an object (no prefix, no suffix). Assumes only up to 4 digit padding :param name: str, string that represents a possible name of an object :return: (float, int, list(str), None), gets the version number then t...
Checks a string for a possible version of an object (no prefix, no suffix). Assumes only up to 4 digit padding :param name: str, string that represents a possible name of an object :return: (float, int, list(str), None), gets the version number then the string matches
Below is the the instruction that describes the task: ### Input: Checks a string for a possible version of an object (no prefix, no suffix). Assumes only up to 4 digit padding :param name: str, string that represents a possible name of an object :return: (float, int, list(str), None), g...
def load(): """Load the active experiment.""" initialize_experiment_package(os.getcwd()) try: try: from dallinger_experiment import experiment except ImportError: from dallinger_experiment import dallinger_experiment as experiment classes = inspect.getmembers...
Load the active experiment.
Below is the the instruction that describes the task: ### Input: Load the active experiment. ### Response: def load(): """Load the active experiment.""" initialize_experiment_package(os.getcwd()) try: try: from dallinger_experiment import experiment except ImportError: ...
def prop_budget(self, budget): """ Set limit on the number of propagations. """ if self.glucose: pysolvers.glucose3_pbudget(self.glucose, budget)
Set limit on the number of propagations.
Below is the the instruction that describes the task: ### Input: Set limit on the number of propagations. ### Response: def prop_budget(self, budget): """ Set limit on the number of propagations. """ if self.glucose: pysolvers.glucose3_pbudget(self.glucose, budget)
def get_recipes_in_node(node): """Gets the name of all recipes present in the run_list of a node""" recipes = [] for elem in node.get('run_list', []): if elem.startswith("recipe"): recipe = elem.split('[')[1].split(']')[0] recipes.append(recipe) return recipes
Gets the name of all recipes present in the run_list of a node
Below is the the instruction that describes the task: ### Input: Gets the name of all recipes present in the run_list of a node ### Response: def get_recipes_in_node(node): """Gets the name of all recipes present in the run_list of a node""" recipes = [] for elem in node.get('run_list', []): if...
def createcommittee(ctx, url, account): """ Setup a committee account for your account """ print_tx(ctx.bitshares.create_committee_member(url, account=account))
Setup a committee account for your account
Below is the the instruction that describes the task: ### Input: Setup a committee account for your account ### Response: def createcommittee(ctx, url, account): """ Setup a committee account for your account """ print_tx(ctx.bitshares.create_committee_member(url, account=account))
def do_heavy_work(self, block): """ Expects Compressor Block like objects """ cipher_key = self.gen_key(32) in_file_path = block.latest_file_info.path dst_file_path = block.processed_data_file_info.path + self.get_extension() self.log.debug("Encrypting file '%s' w...
Expects Compressor Block like objects
Below is the the instruction that describes the task: ### Input: Expects Compressor Block like objects ### Response: def do_heavy_work(self, block): """ Expects Compressor Block like objects """ cipher_key = self.gen_key(32) in_file_path = block.latest_file_info.path ...
def expand(self, short): """Expand short URL or keyword to long URL. Parameters: short: Short URL (``http://example.com/abc``) or keyword (abc). :return: Expanded/long URL, e.g. ``https://www.youtube.com/watch?v=dQw4w9WgXcQ`` Raises: ~yourls.ex...
Expand short URL or keyword to long URL. Parameters: short: Short URL (``http://example.com/abc``) or keyword (abc). :return: Expanded/long URL, e.g. ``https://www.youtube.com/watch?v=dQw4w9WgXcQ`` Raises: ~yourls.exceptions.YOURLSHTTPError: HTTP error...
Below is the the instruction that describes the task: ### Input: Expand short URL or keyword to long URL. Parameters: short: Short URL (``http://example.com/abc``) or keyword (abc). :return: Expanded/long URL, e.g. ``https://www.youtube.com/watch?v=dQw4w9WgXcQ`` ...
def _listen(sockets): """Main server loop. Listens for incoming events and dispatches them to appropriate chatroom""" while True: (i , o, e) = select.select(sockets.keys(),[],[],1) for socket in i: if isinstance(sockets[socket], Chatroom): data_len = sockets[socket].c...
Main server loop. Listens for incoming events and dispatches them to appropriate chatroom
Below is the the instruction that describes the task: ### Input: Main server loop. Listens for incoming events and dispatches them to appropriate chatroom ### Response: def _listen(sockets): """Main server loop. Listens for incoming events and dispatches them to appropriate chatroom""" while True: ...
def install_deb(pkgname, url): """Install package from custom deb hosted on S3. Return true if package was installed by this invocation.""" status = run("dpkg-query -W -f='${{Status}}' {p}; true".format(p=pkgname)) if ('installed' not in status) or ('not-installed' in status): deb = url.rpartiti...
Install package from custom deb hosted on S3. Return true if package was installed by this invocation.
Below is the the instruction that describes the task: ### Input: Install package from custom deb hosted on S3. Return true if package was installed by this invocation. ### Response: def install_deb(pkgname, url): """Install package from custom deb hosted on S3. Return true if package was installed by t...
def _shift_cells(self, get_cells, get_deltas): """Handles cell shifting.""" # Don't do anything when there is an overlay. if self.lost or self.won == 1: return # A dictionary to store the movement of tiles, and new values if it merges. tile_moved = {} for y, ...
Handles cell shifting.
Below is the the instruction that describes the task: ### Input: Handles cell shifting. ### Response: def _shift_cells(self, get_cells, get_deltas): """Handles cell shifting.""" # Don't do anything when there is an overlay. if self.lost or self.won == 1: return # A dict...
def get_current_future_chain(self, continuous_future, dt): """ Retrieves the future chain for the contract at the given `dt` according the `continuous_future` specification. Returns ------- future_chain : list[Future] A list of active futures, where the firs...
Retrieves the future chain for the contract at the given `dt` according the `continuous_future` specification. Returns ------- future_chain : list[Future] A list of active futures, where the first index is the current contract specified by the continuous future ...
Below is the the instruction that describes the task: ### Input: Retrieves the future chain for the contract at the given `dt` according the `continuous_future` specification. Returns ------- future_chain : list[Future] A list of active futures, where the first index is...
def choice(self, obj): """ Overloads the choice method to add the position of the object in the tree for future sorting. """ tree_id = getattr(obj, self.queryset.model._mptt_meta.tree_id_attr, 0) left = getattr(obj, self.queryset.model._mptt_meta.left_attr, 0) ret...
Overloads the choice method to add the position of the object in the tree for future sorting.
Below is the the instruction that describes the task: ### Input: Overloads the choice method to add the position of the object in the tree for future sorting. ### Response: def choice(self, obj): """ Overloads the choice method to add the position of the object in the tree for futur...
def override(base=ABSENT): """Mark a method as overriding a corresponding method from superclass. :param base: Optional base class from which this method is being overridden. If provided, it can be a class itself, or its (qualified) name. .. note:: When overriding a :class:`class...
Mark a method as overriding a corresponding method from superclass. :param base: Optional base class from which this method is being overridden. If provided, it can be a class itself, or its (qualified) name. .. note:: When overriding a :class:`classmethod`, remember to place ``@over...
Below is the the instruction that describes the task: ### Input: Mark a method as overriding a corresponding method from superclass. :param base: Optional base class from which this method is being overridden. If provided, it can be a class itself, or its (qualified) name. .. note:: ...
def lr_find(learn:Learner, start_lr:Floats=1e-7, end_lr:Floats=10, num_it:int=100, stop_div:bool=True, wd:float=None): "Explore lr from `start_lr` to `end_lr` over `num_it` iterations in `learn`. If `stop_div`, stops when loss diverges." start_lr = learn.lr_range(start_lr) start_lr = np.array(start_lr) if i...
Explore lr from `start_lr` to `end_lr` over `num_it` iterations in `learn`. If `stop_div`, stops when loss diverges.
Below is the the instruction that describes the task: ### Input: Explore lr from `start_lr` to `end_lr` over `num_it` iterations in `learn`. If `stop_div`, stops when loss diverges. ### Response: def lr_find(learn:Learner, start_lr:Floats=1e-7, end_lr:Floats=10, num_it:int=100, stop_div:bool=True, wd:float=None): ...
def ask_captcha(length=4): """Prompts the user for a random string.""" captcha = "".join(random.choice(string.ascii_lowercase) for _ in range(length)) ask_str('Enter the following letters, "%s"' % (captcha), vld=[captcha, captcha.upper()], blk=False)
Prompts the user for a random string.
Below is the the instruction that describes the task: ### Input: Prompts the user for a random string. ### Response: def ask_captcha(length=4): """Prompts the user for a random string.""" captcha = "".join(random.choice(string.ascii_lowercase) for _ in range(length)) ask_str('Enter the following letter...
def star(n, alpha='faced', center=(1, 1)): """ Create the star points of various design matrices Parameters ---------- n : int The number of variables in the design Optional -------- alpha : str Available values are 'faced' (default), 'orthogonal', o...
Create the star points of various design matrices Parameters ---------- n : int The number of variables in the design Optional -------- alpha : str Available values are 'faced' (default), 'orthogonal', or 'rotatable' center : array A 1-by-2 array...
Below is the the instruction that describes the task: ### Input: Create the star points of various design matrices Parameters ---------- n : int The number of variables in the design Optional -------- alpha : str Available values are 'faced' (default), 'or...
def fit(model, data, n_epochs, opt, crit, metrics=None, callbacks=None, stepper=Stepper, swa_model=None, swa_start=None, swa_eval_freq=None, visualize=False, **kwargs): """ Fits a model Arguments: model (model): any pytorch module net = to_gpu(net) data (ModelData): see ModelDa...
Fits a model Arguments: model (model): any pytorch module net = to_gpu(net) data (ModelData): see ModelData class and subclasses (can be a list) opts: an optimizer. Example: optim.Adam. If n_epochs is a list, it needs to be the layer_optimizer to get the optimizer as it chan...
Below is the the instruction that describes the task: ### Input: Fits a model Arguments: model (model): any pytorch module net = to_gpu(net) data (ModelData): see ModelData class and subclasses (can be a list) opts: an optimizer. Example: optim.Adam. If n_epochs is a lis...
def save_protein_pickles_and_reset_protein(self): """Save all Proteins as pickle files -- currently development code for parallelization purposes. Also clears the protein attribute in all genes!""" self.gene_protein_pickles = {} for g in tqdm(self.genes): if g.protein.represe...
Save all Proteins as pickle files -- currently development code for parallelization purposes. Also clears the protein attribute in all genes!
Below is the the instruction that describes the task: ### Input: Save all Proteins as pickle files -- currently development code for parallelization purposes. Also clears the protein attribute in all genes! ### Response: def save_protein_pickles_and_reset_protein(self): """Save all Proteins as pick...
def takewhile(self, func=None): """ Return a new Collection with the last few items removed. Parameters: func : function(Node) -> Node Returns: A new Collection, discarding all items at and after the first item where bool(func(item)) == False ...
Return a new Collection with the last few items removed. Parameters: func : function(Node) -> Node Returns: A new Collection, discarding all items at and after the first item where bool(func(item)) == False Examples: node.find_all('tr').takew...
Below is the the instruction that describes the task: ### Input: Return a new Collection with the last few items removed. Parameters: func : function(Node) -> Node Returns: A new Collection, discarding all items at and after the first item where bool(func(item...
def hide_routemap_holder_route_map_content_set_metric_type_external(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") hide_routemap_holder = ET.SubElement(config, "hide-routemap-holder", xmlns="urn:brocade.com:mgmt:brocade-ip-policy") route_map = ET.SubEle...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def hide_routemap_holder_route_map_content_set_metric_type_external(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") hide_routemap_holder = ET.SubElement(confi...
def newround(number, ndigits=None): """ See Python 3 documentation: uses Banker's Rounding. Delegates to the __round__ method if for some reason this exists. If not, rounds a number to a given precision in decimal digits (default 0 digits). This returns an int when called with one argument, ot...
See Python 3 documentation: uses Banker's Rounding. Delegates to the __round__ method if for some reason this exists. If not, rounds a number to a given precision in decimal digits (default 0 digits). This returns an int when called with one argument, otherwise the same type as the number. ndigits may...
Below is the the instruction that describes the task: ### Input: See Python 3 documentation: uses Banker's Rounding. Delegates to the __round__ method if for some reason this exists. If not, rounds a number to a given precision in decimal digits (default 0 digits). This returns an int when called with...
def dict(self): '''Returns a dictionary representing this query.''' d = dict() d['key'] = str(self.key) if self.limit is not None: d['limit'] = self.limit if self.offset > 0: d['offset'] = self.offset if self.offset_key: d['offset_key'] = str(self.offset_key) if len(self.f...
Returns a dictionary representing this query.
Below is the the instruction that describes the task: ### Input: Returns a dictionary representing this query. ### Response: def dict(self): '''Returns a dictionary representing this query.''' d = dict() d['key'] = str(self.key) if self.limit is not None: d['limit'] = self.limit if self....
def toPIL(self, **attribs): """ Convert canvas to a PIL image """ import PIL.Image bytes = self.convert("png") sfile = io.BytesIO(bytes) pil = PIL.Image.open(sfile) return pil
Convert canvas to a PIL image
Below is the the instruction that describes the task: ### Input: Convert canvas to a PIL image ### Response: def toPIL(self, **attribs): """ Convert canvas to a PIL image """ import PIL.Image bytes = self.convert("png") sfile = io.BytesIO(bytes) pil = PIL.Ima...
def save(variable, filename): """Save variable on given path using Pickle Args: variable: what to save path (str): path of the output """ fileObj = open(filename, 'wb') pickle.dump(variable, fileObj) fileObj.close()
Save variable on given path using Pickle Args: variable: what to save path (str): path of the output
Below is the the instruction that describes the task: ### Input: Save variable on given path using Pickle Args: variable: what to save path (str): path of the output ### Response: def save(variable, filename): """Save variable on given path using Pickle Args: variable:...
def _send_with_auth(values, secret_key, url): """Send dictionary of JSON serializable `values` as a POST body to `url` along with `auth_token` that's generated from `secret_key` and `values` scheduler.auth.create_token expects a JSON serializable payload, so we send a dictionary. On the receiving end of the...
Send dictionary of JSON serializable `values` as a POST body to `url` along with `auth_token` that's generated from `secret_key` and `values` scheduler.auth.create_token expects a JSON serializable payload, so we send a dictionary. On the receiving end of the POST request, the Flask view will have access to...
Below is the the instruction that describes the task: ### Input: Send dictionary of JSON serializable `values` as a POST body to `url` along with `auth_token` that's generated from `secret_key` and `values` scheduler.auth.create_token expects a JSON serializable payload, so we send a dictionary. On the re...
def resume_writing(self, exc=None): '''Resume writing. Successive calls to this method will fails unless :meth:`pause_writing` is called first. ''' assert self._paused self._paused = False waiter = self._waiter if waiter is not None: self._wai...
Resume writing. Successive calls to this method will fails unless :meth:`pause_writing` is called first.
Below is the the instruction that describes the task: ### Input: Resume writing. Successive calls to this method will fails unless :meth:`pause_writing` is called first. ### Response: def resume_writing(self, exc=None): '''Resume writing. Successive calls to this method will fails...
def get_atoms(self, inc_alt_states=False): """Returns all atoms in the `Monomer`. Parameters ---------- inc_alt_states : bool, optional If `True`, will return `Atoms` for alternate states. """ if inc_alt_states: return itertools.chain(*[x[1].value...
Returns all atoms in the `Monomer`. Parameters ---------- inc_alt_states : bool, optional If `True`, will return `Atoms` for alternate states.
Below is the the instruction that describes the task: ### Input: Returns all atoms in the `Monomer`. Parameters ---------- inc_alt_states : bool, optional If `True`, will return `Atoms` for alternate states. ### Response: def get_atoms(self, inc_alt_states=False): """Re...
def from_spec(spec): """ Creates an exploration object from a specification dict. """ exploration = util.get_object( obj=spec, predefined_objects=tensorforce.core.explorations.explorations ) assert isinstance(exploration, Exploration) retur...
Creates an exploration object from a specification dict.
Below is the the instruction that describes the task: ### Input: Creates an exploration object from a specification dict. ### Response: def from_spec(spec): """ Creates an exploration object from a specification dict. """ exploration = util.get_object( obj=spec, ...
def AstroDrizzle(input=None, mdriztab=False, editpars=False, configobj=None, wcsmap=None, **input_dict): """ AstroDrizzle command-line interface """ # Support input of filenames from command-line without a parameter name # then copy this into input_dict for merging with TEAL ConfigObj #...
AstroDrizzle command-line interface
Below is the the instruction that describes the task: ### Input: AstroDrizzle command-line interface ### Response: def AstroDrizzle(input=None, mdriztab=False, editpars=False, configobj=None, wcsmap=None, **input_dict): """ AstroDrizzle command-line interface """ # Support input of filenam...
def activate_cython(self): """ Activate Cython support. We need to run this here because if the support is active, we don't to run the UMR at all. """ run_cython = os.environ.get("SPY_RUN_CYTHON") == "True" if run_cython: try: __impor...
Activate Cython support. We need to run this here because if the support is active, we don't to run the UMR at all.
Below is the the instruction that describes the task: ### Input: Activate Cython support. We need to run this here because if the support is active, we don't to run the UMR at all. ### Response: def activate_cython(self): """ Activate Cython support. We need to run this he...
def gather_from_ingredients(wrapped, instance=None, args=None, kwargs=None): """ Decorator that calls `_gather` on the instance the wrapped function is bound to (should be an `Ingredient`) and yields from the returned generator. This function is necessary, because `Ingredient._gather` cannot direct...
Decorator that calls `_gather` on the instance the wrapped function is bound to (should be an `Ingredient`) and yields from the returned generator. This function is necessary, because `Ingredient._gather` cannot directly be used as a decorator inside of `Ingredient`.
Below is the the instruction that describes the task: ### Input: Decorator that calls `_gather` on the instance the wrapped function is bound to (should be an `Ingredient`) and yields from the returned generator. This function is necessary, because `Ingredient._gather` cannot directly be used as a ...
async def AddUnits(self, application, num_units, placement): ''' application : str num_units : int placement : typing.Sequence[~Placement] Returns -> typing.Sequence[str] ''' # map input types to rpc msg _params = dict() msg = dict(type='Applicatio...
application : str num_units : int placement : typing.Sequence[~Placement] Returns -> typing.Sequence[str]
Below is the the instruction that describes the task: ### Input: application : str num_units : int placement : typing.Sequence[~Placement] Returns -> typing.Sequence[str] ### Response: async def AddUnits(self, application, num_units, placement): ''' application : str ...
def ToJson(self): """ Convert object members to a dictionary that can be parsed as JSON. Returns: dict: """ name = 'Contract' try: name = self.Name.decode('utf-8') except Exception as e: pass jsn = {'version': self.S...
Convert object members to a dictionary that can be parsed as JSON. Returns: dict:
Below is the the instruction that describes the task: ### Input: Convert object members to a dictionary that can be parsed as JSON. Returns: dict: ### Response: def ToJson(self): """ Convert object members to a dictionary that can be parsed as JSON. Returns: ...
def clean_all(G, settings): """ Removes all the output files from all targets. Takes the graph as the only argument Args: The networkx graph object The settings dictionary Returns: 0 if successful 1 if removing even one file failed """ quiet = settings["quie...
Removes all the output files from all targets. Takes the graph as the only argument Args: The networkx graph object The settings dictionary Returns: 0 if successful 1 if removing even one file failed
Below is the the instruction that describes the task: ### Input: Removes all the output files from all targets. Takes the graph as the only argument Args: The networkx graph object The settings dictionary Returns: 0 if successful 1 if removing even one file failed ### R...
def disable_constant(parameterized): """ Temporarily set parameters on Parameterized object to constant=False. """ params = parameterized.params().values() constants = [p.constant for p in params] for p in params: p.constant = False try: yield except: raise ...
Temporarily set parameters on Parameterized object to constant=False.
Below is the the instruction that describes the task: ### Input: Temporarily set parameters on Parameterized object to constant=False. ### Response: def disable_constant(parameterized): """ Temporarily set parameters on Parameterized object to constant=False. """ params = parameterized.para...
def add_description(method): """Decorator adding the description to the output of a visitor method.""" @wraps(method) def wrapped(self, node, *args): return join([node.description, method(self, node, *args)], "\n") return wrapped
Decorator adding the description to the output of a visitor method.
Below is the the instruction that describes the task: ### Input: Decorator adding the description to the output of a visitor method. ### Response: def add_description(method): """Decorator adding the description to the output of a visitor method.""" @wraps(method) def wrapped(self, node, *args): ...
def reset_to_bootloader1(self, cpu_id): """ Reset to the bootloader The parameter cpuid shall correspond to the device to reset. Return true if the reset has been done and the contact with the bootloader is established. """ # Send an echo request and wait for the answer ...
Reset to the bootloader The parameter cpuid shall correspond to the device to reset. Return true if the reset has been done and the contact with the bootloader is established.
Below is the the instruction that describes the task: ### Input: Reset to the bootloader The parameter cpuid shall correspond to the device to reset. Return true if the reset has been done and the contact with the bootloader is established. ### Response: def reset_to_bootloader1(self, cpu_...
def dump_key(engine, obj): """dump the hash (and range, if there is one) key(s) of an object into a dynamo-friendly format. returns {dynamo_name: {type: value} for dynamo_name in hash/range keys} """ key = {} for key_column in obj.Meta.keys: key_value = getattr(obj, key_column.name, mis...
dump the hash (and range, if there is one) key(s) of an object into a dynamo-friendly format. returns {dynamo_name: {type: value} for dynamo_name in hash/range keys}
Below is the the instruction that describes the task: ### Input: dump the hash (and range, if there is one) key(s) of an object into a dynamo-friendly format. returns {dynamo_name: {type: value} for dynamo_name in hash/range keys} ### Response: def dump_key(engine, obj): """dump the hash (and range, i...
def parse_card_transfer_metainfo(protobuf: bytes, deck_version: int) -> dict: '''decode card_spawn protobuf message and validate it against deck.version :protobuf - bytes from op_return message :deck_version - integer ''' card = CardTransferProto() card.ParseFromString(protobuf) if not car...
decode card_spawn protobuf message and validate it against deck.version :protobuf - bytes from op_return message :deck_version - integer
Below is the the instruction that describes the task: ### Input: decode card_spawn protobuf message and validate it against deck.version :protobuf - bytes from op_return message :deck_version - integer ### Response: def parse_card_transfer_metainfo(protobuf: bytes, deck_version: int) -> dict: '''decode...
def posterior_to_xarray(self): """Convert the posterior to an xarray dataset.""" data = {} for idx, var_name in enumerate(self.var_names): # Use emcee3 syntax, else use emcee2 data[var_name] = ( self.sampler.get_chain()[(..., idx)].T if has...
Convert the posterior to an xarray dataset.
Below is the the instruction that describes the task: ### Input: Convert the posterior to an xarray dataset. ### Response: def posterior_to_xarray(self): """Convert the posterior to an xarray dataset.""" data = {} for idx, var_name in enumerate(self.var_names): # Use emcee3 synt...
def rename(self, name): """ Rename the element. @param name: A new name for the element. @type name: basestring """ if name is None: raise Exception("name (%s) not-valid" % (name,)) self.prefix, self.name = splitPrefix(name)
Rename the element. @param name: A new name for the element. @type name: basestring
Below is the the instruction that describes the task: ### Input: Rename the element. @param name: A new name for the element. @type name: basestring ### Response: def rename(self, name): """ Rename the element. @param name: A new name for the element. @type name: b...
def instantiate(self, value_of_n): """Instantiates the template""" template = Cheetah.Template.Template( self.content, searchList={'n': value_of_n} ) template.random_string = random_string return str(template)
Instantiates the template
Below is the the instruction that describes the task: ### Input: Instantiates the template ### Response: def instantiate(self, value_of_n): """Instantiates the template""" template = Cheetah.Template.Template( self.content, searchList={'n': value_of_n} ) temp...
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'sentence') and self.sentence is not None: _dict['sentence'] = self.sentence if hasattr(self, 'subject') and self.subject is not None: _dict['subject'] = self.s...
Return a json dictionary representing this model.
Below is the the instruction that describes the task: ### Input: Return a json dictionary representing this model. ### Response: def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'sentence') and self.sentence is not None: _di...
def assess_fitting_results(basename, cormap_alpha=0.01): """Assess the results of a fit based on the .fit and .fir files created by various programs from the ATSAS suite.""" plt.figure(figsize=(12, 4)) plt.subplot2grid((1, 4), (0, 0), colspan=2) fir = np.loadtxt(basename + '.fir', skiprows=1) # q, ...
Assess the results of a fit based on the .fit and .fir files created by various programs from the ATSAS suite.
Below is the the instruction that describes the task: ### Input: Assess the results of a fit based on the .fit and .fir files created by various programs from the ATSAS suite. ### Response: def assess_fitting_results(basename, cormap_alpha=0.01): """Assess the results of a fit based on the .fit and .fir fi...
def bot_config(player_config_path: Path, team: Team) -> 'PlayerConfig': """ A function to cover the common case of creating a config for a bot. """ bot_config = PlayerConfig() bot_config.bot = True bot_config.rlbot_controlled = True bot_config.team = team.value ...
A function to cover the common case of creating a config for a bot.
Below is the the instruction that describes the task: ### Input: A function to cover the common case of creating a config for a bot. ### Response: def bot_config(player_config_path: Path, team: Team) -> 'PlayerConfig': """ A function to cover the common case of creating a config for a bot. ...
def openXmlDocument(path=None, file_=None, data=None, url=None, mime_type=None): """**Factory function** Will guess what document type is best suited and return the appropriate document type. User must provide either ``path``, ``file_``, ``data`` or ``url`` parameter. :param path: file path in the...
**Factory function** Will guess what document type is best suited and return the appropriate document type. User must provide either ``path``, ``file_``, ``data`` or ``url`` parameter. :param path: file path in the local filesystem to a document. :param file_: a file (like) object to a document (m...
Below is the the instruction that describes the task: ### Input: **Factory function** Will guess what document type is best suited and return the appropriate document type. User must provide either ``path``, ``file_``, ``data`` or ``url`` parameter. :param path: file path in the local filesystem t...
def get_input_shape(self): """ Return a list of shape tuples if there are multiple inputs. Return one shape tuple otherwise. """ input = callBigDlFunc(self.bigdl_type, "getInputShape", self.value) return self.__process_shape(input)
Return a list of shape tuples if there are multiple inputs. Return one shape tuple otherwise.
Below is the the instruction that describes the task: ### Input: Return a list of shape tuples if there are multiple inputs. Return one shape tuple otherwise. ### Response: def get_input_shape(self): """ Return a list of shape tuples if there are multiple inputs. Return one shape tu...
def write_end_of_directory(fp, dir_size, dir_offset, count): """ Write zip file end of directory header at the current file position :param fp: the file point to which to write the header :param dir_size: the total size of the directory :param dir_offset: the start of the first dire...
Write zip file end of directory header at the current file position :param fp: the file point to which to write the header :param dir_size: the total size of the directory :param dir_offset: the start of the first directory header :param count: the count of files
Below is the the instruction that describes the task: ### Input: Write zip file end of directory header at the current file position :param fp: the file point to which to write the header :param dir_size: the total size of the directory :param dir_offset: the start of the first directory he...
def all_sharded_cluster_links(cluster_id, shard_id=None, router_id=None, rel_to=None): """Get a list of all links to be included with ShardedClusters.""" return [ sharded_cluster_link(rel, cluster_id, shard_id, router_id, self_rel=(rel == rel_to...
Get a list of all links to be included with ShardedClusters.
Below is the the instruction that describes the task: ### Input: Get a list of all links to be included with ShardedClusters. ### Response: def all_sharded_cluster_links(cluster_id, shard_id=None, router_id=None, rel_to=None): """Get a list of all links to be included with Sharded...
def on_open(self, callback, timeout): """ Initialize a new timeout. :param callback: The callback to execute when the timeout reaches the end of its life. May be a coroutine function. :param timeout: The maximum time to wait for, in seconds. """ super().on_o...
Initialize a new timeout. :param callback: The callback to execute when the timeout reaches the end of its life. May be a coroutine function. :param timeout: The maximum time to wait for, in seconds.
Below is the the instruction that describes the task: ### Input: Initialize a new timeout. :param callback: The callback to execute when the timeout reaches the end of its life. May be a coroutine function. :param timeout: The maximum time to wait for, in seconds. ### Response: def on...
def check_imts(self, imts): """ Make sure the IMTs are recognized by all GSIMs in the logic tree """ for trt in self.values: for gsim in self.values[trt]: for attr in dir(gsim): coeffs = getattr(gsim, attr) if not isinst...
Make sure the IMTs are recognized by all GSIMs in the logic tree
Below is the the instruction that describes the task: ### Input: Make sure the IMTs are recognized by all GSIMs in the logic tree ### Response: def check_imts(self, imts): """ Make sure the IMTs are recognized by all GSIMs in the logic tree """ for trt in self.values: fo...
def assert_requirements(self): """"Asserts PEP 508 specifiers.""" # Support for 508's implementation_version. if hasattr(sys, 'implementation'): implementation_version = format_full_version(sys.implementation.version) else: implementation_version = "0" #...
Asserts PEP 508 specifiers.
Below is the the instruction that describes the task: ### Input: Asserts PEP 508 specifiers. ### Response: def assert_requirements(self): """"Asserts PEP 508 specifiers.""" # Support for 508's implementation_version. if hasattr(sys, 'implementation'): implementation_version = f...
def isroutine(object): """Return true if the object is any kind of function or method.""" return (isbuiltin(object) or isfunction(object) or ismethod(object) or ismethoddescriptor(object))
Return true if the object is any kind of function or method.
Below is the the instruction that describes the task: ### Input: Return true if the object is any kind of function or method. ### Response: def isroutine(object): """Return true if the object is any kind of function or method.""" return (isbuiltin(object) or isfunction(object) or is...
def OnCellBorderColor(self, event): """Cell border color event handler""" with undo.group(_("Border color")): self.grid.actions.set_border_attr("bordercolor", event.color, event.borders) self.grid.ForceRefresh() self.grid.updat...
Cell border color event handler
Below is the the instruction that describes the task: ### Input: Cell border color event handler ### Response: def OnCellBorderColor(self, event): """Cell border color event handler""" with undo.group(_("Border color")): self.grid.actions.set_border_attr("bordercolor", ...
def dumps(self, blob): """ Call json.dumps with the attributes of this instance as arguments. """ return json.dumps( blob, indent=self.indent, sort_keys=True, separators=self.separators, )
Call json.dumps with the attributes of this instance as arguments.
Below is the the instruction that describes the task: ### Input: Call json.dumps with the attributes of this instance as arguments. ### Response: def dumps(self, blob): """ Call json.dumps with the attributes of this instance as arguments. """ return json.dumps( ...
def authorize_guest(self, guest_mac, minutes, up_bandwidth=None, down_bandwidth=None, byte_quota=None, ap_mac=None): """ Authorize a guest based on his MAC address. Arguments: guest_mac -- the guest MAC address : aa:bb:cc:dd:ee:ff minutes -- duration of the aut...
Authorize a guest based on his MAC address. Arguments: guest_mac -- the guest MAC address : aa:bb:cc:dd:ee:ff minutes -- duration of the authorization in minutes up_bandwith -- up speed allowed in kbps (optional) down_bandwith -- down speed allowed in...
Below is the the instruction that describes the task: ### Input: Authorize a guest based on his MAC address. Arguments: guest_mac -- the guest MAC address : aa:bb:cc:dd:ee:ff minutes -- duration of the authorization in minutes up_bandwith -- up speed allowed ...
def update(self, language=values.unset, tagged_text=values.unset, source_channel=values.unset): """ Update the SampleInstance :param unicode language: The ISO language-country string that specifies the language used for the sample :param unicode tagged_text: The text exam...
Update the SampleInstance :param unicode language: The ISO language-country string that specifies the language used for the sample :param unicode tagged_text: The text example of how end users might express the task :param unicode source_channel: The communication channel from which the sample ...
Below is the the instruction that describes the task: ### Input: Update the SampleInstance :param unicode language: The ISO language-country string that specifies the language used for the sample :param unicode tagged_text: The text example of how end users might express the task :param uni...
def toArray(self): """ Return an numpy.ndarray """ A = np.zeros((self.numRows, self.numCols), dtype=np.float64, order='F') for k in xrange(self.colPtrs.size - 1): startptr = self.colPtrs[k] endptr = self.colPtrs[k + 1] if self.isTransposed: ...
Return an numpy.ndarray
Below is the the instruction that describes the task: ### Input: Return an numpy.ndarray ### Response: def toArray(self): """ Return an numpy.ndarray """ A = np.zeros((self.numRows, self.numCols), dtype=np.float64, order='F') for k in xrange(self.colPtrs.size - 1): ...
def append_annotation(self, annotation: str, values: Set[str]) -> 'Seeding': """Add a seed induction method for single annotation's values. :param annotation: The annotation to filter by :param values: The values of the annotation to keep :returns: self for fluid API """ ...
Add a seed induction method for single annotation's values. :param annotation: The annotation to filter by :param values: The values of the annotation to keep :returns: self for fluid API
Below is the the instruction that describes the task: ### Input: Add a seed induction method for single annotation's values. :param annotation: The annotation to filter by :param values: The values of the annotation to keep :returns: self for fluid API ### Response: def append_annotation(s...
def install_deps(self, virtualenv, skip_cached=True, always_exit=False, exit_if_failed=True, stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr): """ :type virtualenv: VirtualEnv """ config = self.registered_venvs[virtualenv.venv_name] configed_deps = conf...
:type virtualenv: VirtualEnv
Below is the the instruction that describes the task: ### Input: :type virtualenv: VirtualEnv ### Response: def install_deps(self, virtualenv, skip_cached=True, always_exit=False, exit_if_failed=True, stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr): """ :type virtualenv:...
def samba(): '''Install smb server samba and create a share (common read-write-access). More infos: * https://wiki.ubuntuusers.de/Samba%20Server/ ''' username = env.user install_packages(['samba']) run(flo('sudo smbpasswd -a {username}')) path = '$HOME/shared' sharename = 'shared'...
Install smb server samba and create a share (common read-write-access). More infos: * https://wiki.ubuntuusers.de/Samba%20Server/
Below is the the instruction that describes the task: ### Input: Install smb server samba and create a share (common read-write-access). More infos: * https://wiki.ubuntuusers.de/Samba%20Server/ ### Response: def samba(): '''Install smb server samba and create a share (common read-write-access). ...
def _get_forums_for_user(self, user, perm_codenames, use_tree_hierarchy=False): """ Returns all the forums that satisfy the given list of permission codenames. User and group forum permissions are used. If the ``use_tree_hierarchy`` keyword argument is set the granted forums will be filtered s...
Returns all the forums that satisfy the given list of permission codenames. User and group forum permissions are used. If the ``use_tree_hierarchy`` keyword argument is set the granted forums will be filtered so that a forum which has an ancestor which is not in the granted forums set will not...
Below is the the instruction that describes the task: ### Input: Returns all the forums that satisfy the given list of permission codenames. User and group forum permissions are used. If the ``use_tree_hierarchy`` keyword argument is set the granted forums will be filtered so that a forum ...
def uninstall(pkgs=None, requirements=None, bin_env=None, log=None, proxy=None, timeout=None, user=None, cwd=None, saltenv='base', use_vt=False): ''' Uninstall packages individually or f...
Uninstall packages individually or from a pip requirements file pkgs comma separated list of packages to install requirements Path to requirements file bin_env Path to pip (or to a virtualenv). This can be used to specify the path to the pip to use when more than one Pytho...
Below is the the instruction that describes the task: ### Input: Uninstall packages individually or from a pip requirements file pkgs comma separated list of packages to install requirements Path to requirements file bin_env Path to pip (or to a virtualenv). This can be used t...
def save(self, commit=True): """ When saving a super model form, the nested forms and formsets will be saved as well. The implementation of ``.save()`` looks like this: .. code:: python saved_obj = self.save_form() self.save_forms() self.sav...
When saving a super model form, the nested forms and formsets will be saved as well. The implementation of ``.save()`` looks like this: .. code:: python saved_obj = self.save_form() self.save_forms() self.save_formsets() return saved_obj ...
Below is the the instruction that describes the task: ### Input: When saving a super model form, the nested forms and formsets will be saved as well. The implementation of ``.save()`` looks like this: .. code:: python saved_obj = self.save_form() self.save_forms() ...
def list(cls, vrf=None): """ List VRFs. Maps to the function :py:func:`nipap.backend.Nipap.list_vrf` in the backend. Please see the documentation for the backend function for information regarding input arguments and return values. """ if vrf is None: ...
List VRFs. Maps to the function :py:func:`nipap.backend.Nipap.list_vrf` in the backend. Please see the documentation for the backend function for information regarding input arguments and return values.
Below is the the instruction that describes the task: ### Input: List VRFs. Maps to the function :py:func:`nipap.backend.Nipap.list_vrf` in the backend. Please see the documentation for the backend function for information regarding input arguments and return values. ### Respons...
def _equally_weight_samples(samples, weights): """ Convert samples to be equally weighted. Samples are trimmed by discarding samples in accordance with a probability determined by the corresponding weight. This function has assumed you have normalised the weights properly. If in doubt, convert wei...
Convert samples to be equally weighted. Samples are trimmed by discarding samples in accordance with a probability determined by the corresponding weight. This function has assumed you have normalised the weights properly. If in doubt, convert weights via: `weights /= weights.max()` Parameters ...
Below is the the instruction that describes the task: ### Input: Convert samples to be equally weighted. Samples are trimmed by discarding samples in accordance with a probability determined by the corresponding weight. This function has assumed you have normalised the weights properly. If in doub...
def request_pdu(self): """ Build request PDU to write single coil. :return: Byte array of 5 bytes with PDU. """ if None in [self.address, self.value]: # TODO Raise proper exception. raise Exception return struct.pack('>BHH', self.function_code, self.addr...
Build request PDU to write single coil. :return: Byte array of 5 bytes with PDU.
Below is the the instruction that describes the task: ### Input: Build request PDU to write single coil. :return: Byte array of 5 bytes with PDU. ### Response: def request_pdu(self): """ Build request PDU to write single coil. :return: Byte array of 5 bytes with PDU. """ i...
def get_alternative_full_names(cls, entry): """ get list of models.AlternativeFullName objects from XML node entry :param entry: XML node entry :return: list of :class:`pyuniprot.manager.models.AlternativeFullName` objects """ names = [] query = "./protein/altern...
get list of models.AlternativeFullName objects from XML node entry :param entry: XML node entry :return: list of :class:`pyuniprot.manager.models.AlternativeFullName` objects
Below is the the instruction that describes the task: ### Input: get list of models.AlternativeFullName objects from XML node entry :param entry: XML node entry :return: list of :class:`pyuniprot.manager.models.AlternativeFullName` objects ### Response: def get_alternative_full_names(cls, entry): ...
def create(state, host, ctid, template=None): ''' Create OpenVZ containers. + ctid: CTID of the container to create ''' # Check we don't already have a container with this CTID current_containers = host.fact.openvz_containers if ctid in current_containers: raise OperationError( ...
Create OpenVZ containers. + ctid: CTID of the container to create
Below is the the instruction that describes the task: ### Input: Create OpenVZ containers. + ctid: CTID of the container to create ### Response: def create(state, host, ctid, template=None): ''' Create OpenVZ containers. + ctid: CTID of the container to create ''' # Check we don't alread...
def unembed_sampleset(target_sampleset, embedding, source_bqm, chain_break_method=None, chain_break_fraction=False): """Unembed the samples set. Construct a sample set for the source binary quadratic model (BQM) by unembedding the given samples from the target BQM. Args: ...
Unembed the samples set. Construct a sample set for the source binary quadratic model (BQM) by unembedding the given samples from the target BQM. Args: target_sampleset (:obj:`dimod.SampleSet`): SampleSet from the target BQM. embedding (dict): Mapping from source g...
Below is the the instruction that describes the task: ### Input: Unembed the samples set. Construct a sample set for the source binary quadratic model (BQM) by unembedding the given samples from the target BQM. Args: target_sampleset (:obj:`dimod.SampleSet`): SampleSet from the tar...
def _get_def_class(self, class_obj, member_name): """ Return the class object in MRO order that defines a member. class_obj: Class object that exposes (but not necessarily defines) the member. I.e. starting point of the search. member_name: Name of the member (method or attri...
Return the class object in MRO order that defines a member. class_obj: Class object that exposes (but not necessarily defines) the member. I.e. starting point of the search. member_name: Name of the member (method or attribute). Returns: Class object that defines the membe...
Below is the the instruction that describes the task: ### Input: Return the class object in MRO order that defines a member. class_obj: Class object that exposes (but not necessarily defines) the member. I.e. starting point of the search. member_name: Name of the member (method or attrib...
def get_enterprise_customer_for_running_pipeline(request, pipeline): # pylint: disable=invalid-name """ Get the EnterpriseCustomer associated with a running pipeline. """ sso_provider_id = request.GET.get('tpa_hint') if pipeline: sso_provider_id = Registry.get_from_pipeline(pipeline).provid...
Get the EnterpriseCustomer associated with a running pipeline.
Below is the the instruction that describes the task: ### Input: Get the EnterpriseCustomer associated with a running pipeline. ### Response: def get_enterprise_customer_for_running_pipeline(request, pipeline): # pylint: disable=invalid-name """ Get the EnterpriseCustomer associated with a running pipelin...
def per_from_id_except(s, flavors=chat_flavors+inline_flavors): """ :param s: a list or set of from id :param flavors: ``all`` or a list of flavors :return: a seeder function that returns the from id only if the from id is *not* in ``s`` and message flavor is in ``flavo...
:param s: a list or set of from id :param flavors: ``all`` or a list of flavors :return: a seeder function that returns the from id only if the from id is *not* in ``s`` and message flavor is in ``flavors``.
Below is the the instruction that describes the task: ### Input: :param s: a list or set of from id :param flavors: ``all`` or a list of flavors :return: a seeder function that returns the from id only if the from id is *not* in ``s`` and message flavor is in ``flavors``. #...
def get_by_path(path, first=False): """ Search for resources using colon-separated path notation. E.g.:: path = 'deployments:production:servers:haproxy' haproxies = get_by_path(path) :param bool first: Always use the first returned match for all intermediate searches along the...
Search for resources using colon-separated path notation. E.g.:: path = 'deployments:production:servers:haproxy' haproxies = get_by_path(path) :param bool first: Always use the first returned match for all intermediate searches along the path. If this is ``False`` and an intermediate...
Below is the the instruction that describes the task: ### Input: Search for resources using colon-separated path notation. E.g.:: path = 'deployments:production:servers:haproxy' haproxies = get_by_path(path) :param bool first: Always use the first returned match for all intermediate ...