code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def configure_profile(msg_type, profile_name, data, auth): """ Create the profile entry. Args: :msg_type: (str) message type to create config entry. :profile_name: (str) name of the profile entry :data: (dict) dict values for the 'settings' :auth: (dict) auth parameters ...
Create the profile entry. Args: :msg_type: (str) message type to create config entry. :profile_name: (str) name of the profile entry :data: (dict) dict values for the 'settings' :auth: (dict) auth parameters
Below is the the instruction that describes the task: ### Input: Create the profile entry. Args: :msg_type: (str) message type to create config entry. :profile_name: (str) name of the profile entry :data: (dict) dict values for the 'settings' :auth: (dict) auth parameters ### Re...
def _convert_soap_method_args(*args): """Convert arguments to be consumed by a SoapClient method Soap client required a list of named arguments: >>> _convert_soap_method_args('a', 1) [('arg0', 'a'), ('arg1', 1)] """ soap_args = [] for arg_n, arg in enumerate(args): soap_args.append...
Convert arguments to be consumed by a SoapClient method Soap client required a list of named arguments: >>> _convert_soap_method_args('a', 1) [('arg0', 'a'), ('arg1', 1)]
Below is the the instruction that describes the task: ### Input: Convert arguments to be consumed by a SoapClient method Soap client required a list of named arguments: >>> _convert_soap_method_args('a', 1) [('arg0', 'a'), ('arg1', 1)] ### Response: def _convert_soap_method_args(*args): """Convert...
def set_hybrid_parameters(self, s_C, s_WH, do_renorm=True): """Set the hybrid/renormalization control parameters. **Call signature** *s_C* The harmonic number above which the continuous approximation is used (with special behavior; see below). *s_WH* The h...
Set the hybrid/renormalization control parameters. **Call signature** *s_C* The harmonic number above which the continuous approximation is used (with special behavior; see below). *s_WH* The harmonic number above which the Wild-Hill BEssel function appr...
Below is the the instruction that describes the task: ### Input: Set the hybrid/renormalization control parameters. **Call signature** *s_C* The harmonic number above which the continuous approximation is used (with special behavior; see below). *s_WH* The har...
def send(self, *args, **kwargs): """Sends the envelope using a freshly created SMTP connection. *args* and *kwargs* are passed directly to :py:class:`envelopes.conn.SMTP` constructor. Returns a tuple of SMTP object and whatever its send method returns.""" conn = SMTP(*args, **kw...
Sends the envelope using a freshly created SMTP connection. *args* and *kwargs* are passed directly to :py:class:`envelopes.conn.SMTP` constructor. Returns a tuple of SMTP object and whatever its send method returns.
Below is the the instruction that describes the task: ### Input: Sends the envelope using a freshly created SMTP connection. *args* and *kwargs* are passed directly to :py:class:`envelopes.conn.SMTP` constructor. Returns a tuple of SMTP object and whatever its send method returns. ### Respo...
def value_validate(self, value): """ Validates value and throws ValidationError. Subclasses should override this to provide validation logic. """ if not isinstance(value, six.string_types): raise tldap.exceptions.ValidationError("should be a string")
Validates value and throws ValidationError. Subclasses should override this to provide validation logic.
Below is the the instruction that describes the task: ### Input: Validates value and throws ValidationError. Subclasses should override this to provide validation logic. ### Response: def value_validate(self, value): """ Validates value and throws ValidationError. Subclasses should override...
def get_grade_entry_admin_session_for_gradebook(self, gradebook_id, proxy): """Gets the ``OsidSession`` associated with the grade entry admin service for the given gradebook. arg: gradebook_id (osid.id.Id): the ``Id`` of the gradebook arg: proxy (osid.proxy.Proxy): a proxy return:...
Gets the ``OsidSession`` associated with the grade entry admin service for the given gradebook. arg: gradebook_id (osid.id.Id): the ``Id`` of the gradebook arg: proxy (osid.proxy.Proxy): a proxy return: (osid.grading.GradeEntryAdminSession) - ``a GradeEntryAdminSession`` ...
Below is the the instruction that describes the task: ### Input: Gets the ``OsidSession`` associated with the grade entry admin service for the given gradebook. arg: gradebook_id (osid.id.Id): the ``Id`` of the gradebook arg: proxy (osid.proxy.Proxy): a proxy return: (osid.grading.Gra...
def _create_related_chart(self, data, work, output_dir): """Generates and writes to a file in `output_dir` the data used to display a grouped bar chart. This data gives, for each "maybe" work, the percentage of it that is shared with `work`, and the percentage of `work` that is ...
Generates and writes to a file in `output_dir` the data used to display a grouped bar chart. This data gives, for each "maybe" work, the percentage of it that is shared with `work`, and the percentage of `work` that is shared with the "maybe" work. :param data: data to derive t...
Below is the the instruction that describes the task: ### Input: Generates and writes to a file in `output_dir` the data used to display a grouped bar chart. This data gives, for each "maybe" work, the percentage of it that is shared with `work`, and the percentage of `work` that is...
def filter_that(self, criteria, data): ''' this method just use the module 're' to check if the data contain the string to find ''' import re prog = re.compile(criteria) return True if prog.match(data) else False
this method just use the module 're' to check if the data contain the string to find
Below is the the instruction that describes the task: ### Input: this method just use the module 're' to check if the data contain the string to find ### Response: def filter_that(self, criteria, data): ''' this method just use the module 're' to check if the data contain ...
def get_form_kwargs(self): """ initialize default value that won't be displayed :return: """ kwargs = super(UserServiceUpdateView, self).get_form_kwargs() kwargs['initial']['user'] = self.request.user kwargs['initial']['name'] = self.object.name return kwa...
initialize default value that won't be displayed :return:
Below is the the instruction that describes the task: ### Input: initialize default value that won't be displayed :return: ### Response: def get_form_kwargs(self): """ initialize default value that won't be displayed :return: """ kwargs = super(UserServiceUpdateView,...
def id(self, id): """ Sets the id of this ServicePackageQuotaHistoryReservation. Reservation ID. :param id: The id of this ServicePackageQuotaHistoryReservation. :type: str """ if id is None: raise ValueError("Invalid value for `id`, must not be `None...
Sets the id of this ServicePackageQuotaHistoryReservation. Reservation ID. :param id: The id of this ServicePackageQuotaHistoryReservation. :type: str
Below is the the instruction that describes the task: ### Input: Sets the id of this ServicePackageQuotaHistoryReservation. Reservation ID. :param id: The id of this ServicePackageQuotaHistoryReservation. :type: str ### Response: def id(self, id): """ Sets the id of this Se...
def get_normalized_grid(self): """ Analyzes subcell structure """ log = logging.getLogger(__name__) # Resolve multirow mentions, TODO: validate against all PDFs # subcol_count = 0 mega_rows = [] for row_id, row in enumerate(self._grid): # maps...
Analyzes subcell structure
Below is the the instruction that describes the task: ### Input: Analyzes subcell structure ### Response: def get_normalized_grid(self): """ Analyzes subcell structure """ log = logging.getLogger(__name__) # Resolve multirow mentions, TODO: validate against all PDFs ...
def _aggregate(data, norm=True, sort_by='value', keys=None): ''' Counts the number of occurances of each item in 'data'. Inputs data: a list of values. norm: normalize the resulting counts (as percent) sort_by: how to sort the retured data. Options are 'value' and 'count'. Output a non...
Counts the number of occurances of each item in 'data'. Inputs data: a list of values. norm: normalize the resulting counts (as percent) sort_by: how to sort the retured data. Options are 'value' and 'count'. Output a non-redundant list of values (from 'data') and a list of counts.
Below is the the instruction that describes the task: ### Input: Counts the number of occurances of each item in 'data'. Inputs data: a list of values. norm: normalize the resulting counts (as percent) sort_by: how to sort the retured data. Options are 'value' and 'count'. Output a non-red...
def set_string(_bytearray, byte_index, value, max_size): """ Set string value :params value: string data :params max_size: max possible string size """ if six.PY2: assert isinstance(value, (str, unicode)) else: assert isinstance(value, str) size = len(value) # FAIL ...
Set string value :params value: string data :params max_size: max possible string size
Below is the the instruction that describes the task: ### Input: Set string value :params value: string data :params max_size: max possible string size ### Response: def set_string(_bytearray, byte_index, value, max_size): """ Set string value :params value: string data :params max_size: ...
def Checksum(params, ctxt, scope, stream, coord): """ Runs a simple checksum on a file and returns the result as a int64. The algorithm can be one of the following constants: CHECKSUM_BYTE - Treats the file as a set of unsigned bytes CHECKSUM_SHORT_LE - Treats the file as a set of unsigned little-e...
Runs a simple checksum on a file and returns the result as a int64. The algorithm can be one of the following constants: CHECKSUM_BYTE - Treats the file as a set of unsigned bytes CHECKSUM_SHORT_LE - Treats the file as a set of unsigned little-endian shorts CHECKSUM_SHORT_BE - Treats the file as a set ...
Below is the the instruction that describes the task: ### Input: Runs a simple checksum on a file and returns the result as a int64. The algorithm can be one of the following constants: CHECKSUM_BYTE - Treats the file as a set of unsigned bytes CHECKSUM_SHORT_LE - Treats the file as a set of unsigned l...
def _parse_args(self, args, known_only): """Helper function to do the main argument parsing. This function goes through args and does the bulk of the flag parsing. It will find the corresponding flag in our flag dictionary, and call its .parse() method on the flag value. Args: args: [str], a...
Helper function to do the main argument parsing. This function goes through args and does the bulk of the flag parsing. It will find the corresponding flag in our flag dictionary, and call its .parse() method on the flag value. Args: args: [str], a list of strings with the arguments to parse. ...
Below is the the instruction that describes the task: ### Input: Helper function to do the main argument parsing. This function goes through args and does the bulk of the flag parsing. It will find the corresponding flag in our flag dictionary, and call its .parse() method on the flag value. Args:...
def save(self, out_path): """Save an ascii representation of this simulation trace. Args: out_path (str): The output path to save this simulation trace. """ out = { 'selectors': [str(x) for x in self.selectors], 'trace': [{'stream': str(DataStream.Fr...
Save an ascii representation of this simulation trace. Args: out_path (str): The output path to save this simulation trace.
Below is the the instruction that describes the task: ### Input: Save an ascii representation of this simulation trace. Args: out_path (str): The output path to save this simulation trace. ### Response: def save(self, out_path): """Save an ascii representation of this simulation trace....
def update_templates(self, body): """Update enrollment and verification SMS templates. Useful to send custom messages on sms enrollment and verification Args: body (dict): Attributes to modify. See: https://auth0.com/docs/api/management/v2#!/Guardian/put_templates ...
Update enrollment and verification SMS templates. Useful to send custom messages on sms enrollment and verification Args: body (dict): Attributes to modify. See: https://auth0.com/docs/api/management/v2#!/Guardian/put_templates
Below is the the instruction that describes the task: ### Input: Update enrollment and verification SMS templates. Useful to send custom messages on sms enrollment and verification Args: body (dict): Attributes to modify. See: https://auth0.com/docs/api/management/v2#!/Guar...
def _process_oauth_response(self, response): "Extracts the fields from an oauth response" if response.status_code == 200: credentials = parse_qs(response.text) # Initialize the oauth credentials self._init_oauth( credentials.get('oauth_token')[0], ...
Extracts the fields from an oauth response
Below is the the instruction that describes the task: ### Input: Extracts the fields from an oauth response ### Response: def _process_oauth_response(self, response): "Extracts the fields from an oauth response" if response.status_code == 200: credentials = parse_qs(response.text) ...
def select_segment(self, segs, segs_tips, segs_undecided) -> Tuple[int, int]: """Out of a list of line segments, choose segment that has the most distant second data point. Assume the distance matrix Ddiff is sorted according to seg_idcs. Compute all the distances. Returns ...
Out of a list of line segments, choose segment that has the most distant second data point. Assume the distance matrix Ddiff is sorted according to seg_idcs. Compute all the distances. Returns ------- iseg : int Index identifying the position within the list...
Below is the the instruction that describes the task: ### Input: Out of a list of line segments, choose segment that has the most distant second data point. Assume the distance matrix Ddiff is sorted according to seg_idcs. Compute all the distances. Returns ------- ...
def rsh(self, num, cin=None): """Right shift the farray by *num* places. The *num* argument must be a non-negative ``int``. If the *cin* farray is provided, it will be shifted in. Otherwise, the carry-in is zero. Returns a two-tuple (farray fs, farray cout), where *fs*...
Right shift the farray by *num* places. The *num* argument must be a non-negative ``int``. If the *cin* farray is provided, it will be shifted in. Otherwise, the carry-in is zero. Returns a two-tuple (farray fs, farray cout), where *fs* is the shifted vector, and *cout* is the...
Below is the the instruction that describes the task: ### Input: Right shift the farray by *num* places. The *num* argument must be a non-negative ``int``. If the *cin* farray is provided, it will be shifted in. Otherwise, the carry-in is zero. Returns a two-tuple (farray fs, farr...
def getrepositorytree(self, project_id, **kwargs): """ Get a list of repository files and directories in a project. :param project_id: The ID of a project :param path: The path inside repository. Used to get contend of subdirectories :param ref_name: The name of a repository bra...
Get a list of repository files and directories in a project. :param project_id: The ID of a project :param path: The path inside repository. Used to get contend of subdirectories :param ref_name: The name of a repository branch or tag or if not given the default branch :return: dict wit...
Below is the the instruction that describes the task: ### Input: Get a list of repository files and directories in a project. :param project_id: The ID of a project :param path: The path inside repository. Used to get contend of subdirectories :param ref_name: The name of a repository branc...
def register_with_context(self, myname, context): """ registers this build target (exclusively) with a given context """ if self.context is not None: raise Exception("attempted to register BuildTarget with multiple " "BuildContexts") context.register_tas...
registers this build target (exclusively) with a given context
Below is the the instruction that describes the task: ### Input: registers this build target (exclusively) with a given context ### Response: def register_with_context(self, myname, context): """ registers this build target (exclusively) with a given context """ if self.context is not None: ...
def post(self, *args, **kwargs): """Handle creation of an item. :param args: :param kwargs: """ self.initialize_post() # Don't allow the post if the poster does not have permission if not self.has_create_permission(): LOGGER.debug('Does not have wri...
Handle creation of an item. :param args: :param kwargs:
Below is the the instruction that describes the task: ### Input: Handle creation of an item. :param args: :param kwargs: ### Response: def post(self, *args, **kwargs): """Handle creation of an item. :param args: :param kwargs: """ self.initialize_post() ...
def timeout_message(self, message): ''' Handle a message timeout by removing it from the sending queue and informing the caller :raises: SaltReqTimeoutError ''' future = self.send_future_map.pop(message, None) # In a race condition the message might have been sen...
Handle a message timeout by removing it from the sending queue and informing the caller :raises: SaltReqTimeoutError
Below is the the instruction that describes the task: ### Input: Handle a message timeout by removing it from the sending queue and informing the caller :raises: SaltReqTimeoutError ### Response: def timeout_message(self, message): ''' Handle a message timeout by removing it from t...
def expose(url="/", methods=("GET",)): """ Use this decorator to expose API endpoints on your API classes. :param url: Relative URL for the endpoint :param methods: Allowed HTTP methods. By default only GET is allowed. """ def wrap(f): if not hasattr...
Use this decorator to expose API endpoints on your API classes. :param url: Relative URL for the endpoint :param methods: Allowed HTTP methods. By default only GET is allowed.
Below is the the instruction that describes the task: ### Input: Use this decorator to expose API endpoints on your API classes. :param url: Relative URL for the endpoint :param methods: Allowed HTTP methods. By default only GET is allowed. ### Response: def expose(url="/",...
def organization_subscription_create(self, data, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/organization_subscriptions#create-organization-subscription" api_path = "/api/v2/organization_subscriptions.json" return self.call(api_path, method="POST", data=data, **kwargs)
https://developer.zendesk.com/rest_api/docs/core/organization_subscriptions#create-organization-subscription
Below is the the instruction that describes the task: ### Input: https://developer.zendesk.com/rest_api/docs/core/organization_subscriptions#create-organization-subscription ### Response: def organization_subscription_create(self, data, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/organizat...
def run(self): """Collects memory stats for specified Python program.""" existing_objects = _get_in_memory_objects() prof, result = self.profile() new_objects = _get_in_memory_objects() new_obj_count = _get_obj_count_difference(new_objects, existing_objects) result_obj_c...
Collects memory stats for specified Python program.
Below is the the instruction that describes the task: ### Input: Collects memory stats for specified Python program. ### Response: def run(self): """Collects memory stats for specified Python program.""" existing_objects = _get_in_memory_objects() prof, result = self.profile() new_o...
def disconnect(receiver, signal=Any, sender=Any, weak=True): """Disconnect receiver from sender for signal receiver -- the registered receiver to disconnect signal -- the registered signal to disconnect sender -- the registered sender to disconnect weak -- the weakref state to disconnect disco...
Disconnect receiver from sender for signal receiver -- the registered receiver to disconnect signal -- the registered signal to disconnect sender -- the registered sender to disconnect weak -- the weakref state to disconnect disconnect reverses the process of connect, the semantics for the ind...
Below is the the instruction that describes the task: ### Input: Disconnect receiver from sender for signal receiver -- the registered receiver to disconnect signal -- the registered signal to disconnect sender -- the registered sender to disconnect weak -- the weakref state to disconnect disc...
def brightness(sequence_number, brightness): """Create a brightness message""" return MessageWriter().string("brightness").uint64(sequence_number).uint8(int(brightness*255)).get()
Create a brightness message
Below is the the instruction that describes the task: ### Input: Create a brightness message ### Response: def brightness(sequence_number, brightness): """Create a brightness message""" return MessageWriter().string("brightness").uint64(sequence_number).uint8(int(brightness*255)).get()
def destroy(self): """ A reimplemented destructor. This destructor will clear the reference to the toolkit widget and set its parent to None. """ widget = self.widget if widget is not None: del self.widget super(UiKitToolkitObject, self).destroy()
A reimplemented destructor. This destructor will clear the reference to the toolkit widget and set its parent to None.
Below is the the instruction that describes the task: ### Input: A reimplemented destructor. This destructor will clear the reference to the toolkit widget and set its parent to None. ### Response: def destroy(self): """ A reimplemented destructor. This destructor will clear the r...
def length(self): """ :return: Length of the ``data``. :rtype: int """ if not self.__length: self.__length = self.__get_length() return self.__length
:return: Length of the ``data``. :rtype: int
Below is the the instruction that describes the task: ### Input: :return: Length of the ``data``. :rtype: int ### Response: def length(self): """ :return: Length of the ``data``. :rtype: int """ if not self.__length: self.__length = self.__get_length() ...
def normalize_weight(self, samples): """normalize weight Parameters ---------- samples: list a collection of sample, it's a (NUM_OF_INSTANCE * NUM_OF_FUNCTIONS) matrix, representing{{w11, w12, ..., w1k}, {w21, w22, ... w2k}, ...{wk1, wk2,..., wkk}} ...
normalize weight Parameters ---------- samples: list a collection of sample, it's a (NUM_OF_INSTANCE * NUM_OF_FUNCTIONS) matrix, representing{{w11, w12, ..., w1k}, {w21, w22, ... w2k}, ...{wk1, wk2,..., wkk}} Returns ------- list ...
Below is the the instruction that describes the task: ### Input: normalize weight Parameters ---------- samples: list a collection of sample, it's a (NUM_OF_INSTANCE * NUM_OF_FUNCTIONS) matrix, representing{{w11, w12, ..., w1k}, {w21, w22, ... w2k}, ...{wk1, ...
def add_cats(self, axis, cat_data): ''' Add categories to rows or columns using cat_data array of objects. Each object in cat_data is a dictionary with one key (category title) and value (rows/column names) that have this category. Categories will be added onto the existing categories and will be added in the o...
Add categories to rows or columns using cat_data array of objects. Each object in cat_data is a dictionary with one key (category title) and value (rows/column names) that have this category. Categories will be added onto the existing categories and will be added in the order of the objects in the array. Example `...
Below is the the instruction that describes the task: ### Input: Add categories to rows or columns using cat_data array of objects. Each object in cat_data is a dictionary with one key (category title) and value (rows/column names) that have this category. Categories will be added onto the existing categories and w...
def rewire_inputs(data_list): """Rewire inputs of provided data objects. Input parameter is a list of original and copied data object model instances: ``[{'original': original, 'copy': copy}]``. This function finds which objects reference other objects (in the list) on the input and replaces origin...
Rewire inputs of provided data objects. Input parameter is a list of original and copied data object model instances: ``[{'original': original, 'copy': copy}]``. This function finds which objects reference other objects (in the list) on the input and replaces original objects with the copies (mutates ...
Below is the the instruction that describes the task: ### Input: Rewire inputs of provided data objects. Input parameter is a list of original and copied data object model instances: ``[{'original': original, 'copy': copy}]``. This function finds which objects reference other objects (in the list) ...
def get_resources(domain, token): """ Returns a list of resources (data endpoints) on a Socrata domain. The catalog API and JSON endpoint both return useful information, but the information that they return is useful in slightly different ways. The JSON endpoint provides less information about the reso...
Returns a list of resources (data endpoints) on a Socrata domain. The catalog API and JSON endpoint both return useful information, but the information that they return is useful in slightly different ways. The JSON endpoint provides less information about the resource in question, including lacking a fiel...
Below is the the instruction that describes the task: ### Input: Returns a list of resources (data endpoints) on a Socrata domain. The catalog API and JSON endpoint both return useful information, but the information that they return is useful in slightly different ways. The JSON endpoint provides less inf...
def random_sparse(strategy, prob, obj_reaction, flux_threshold): """Find a random minimal network of model reactions. Given a reaction to optimize and a threshold, delete entities randomly until the flux of the reaction to optimize falls under the threshold. Keep deleting until no more entities can be ...
Find a random minimal network of model reactions. Given a reaction to optimize and a threshold, delete entities randomly until the flux of the reaction to optimize falls under the threshold. Keep deleting until no more entities can be deleted. It works with two strategies: deleting reactions or deletin...
Below is the the instruction that describes the task: ### Input: Find a random minimal network of model reactions. Given a reaction to optimize and a threshold, delete entities randomly until the flux of the reaction to optimize falls under the threshold. Keep deleting until no more entities can be del...
def make(self): """ turn fetched files into a local repo, make auxiliary files """ logger.debug("preparing to add all git files") num_added = self.local_repo.add_all_files() if num_added: self.local_repo.commit("Initial import from Project Gutenberg") file_ha...
turn fetched files into a local repo, make auxiliary files
Below is the the instruction that describes the task: ### Input: turn fetched files into a local repo, make auxiliary files ### Response: def make(self): """ turn fetched files into a local repo, make auxiliary files """ logger.debug("preparing to add all git files") num_added = sel...
def _copy_required(lib_path, copy_filt_func, copied_libs): """ Copy libraries required for files in `lib_path` to `lib_path` Augment `copied_libs` dictionary with any newly copied libraries, modifying `copied_libs` in-place - see Notes. This is one pass of ``copy_recurse`` Parameters --------...
Copy libraries required for files in `lib_path` to `lib_path` Augment `copied_libs` dictionary with any newly copied libraries, modifying `copied_libs` in-place - see Notes. This is one pass of ``copy_recurse`` Parameters ---------- lib_path : str Directory containing libraries co...
Below is the the instruction that describes the task: ### Input: Copy libraries required for files in `lib_path` to `lib_path` Augment `copied_libs` dictionary with any newly copied libraries, modifying `copied_libs` in-place - see Notes. This is one pass of ``copy_recurse`` Parameters ------...
def var(self): """Returns a symbol representing this parameter.""" if self._var is None: self._var = symbol.var(self.name, shape=self.shape, dtype=self.dtype, lr_mult=self.lr_mult, wd_mult=self.wd_mult, init=self.init, sty...
Returns a symbol representing this parameter.
Below is the the instruction that describes the task: ### Input: Returns a symbol representing this parameter. ### Response: def var(self): """Returns a symbol representing this parameter.""" if self._var is None: self._var = symbol.var(self.name, shape=self.shape, dtype=self.dtype, ...
def _fullqualname_function_py3(obj): """Fully qualified name for 'function' objects in Python 3. """ if hasattr(obj, "__wrapped__"): # Required for decorator.__version__ <= 4.0.0. qualname = obj.__wrapped__.__qualname__ else: qualname = obj.__qualname__ return obj.__module_...
Fully qualified name for 'function' objects in Python 3.
Below is the the instruction that describes the task: ### Input: Fully qualified name for 'function' objects in Python 3. ### Response: def _fullqualname_function_py3(obj): """Fully qualified name for 'function' objects in Python 3. """ if hasattr(obj, "__wrapped__"): # Required for decorator....
def _write(self, session, openFile, replaceParamFile): """ Channel Input File Write to File Method """ # Write lines openFile.write('GSSHA_CHAN\n') alpha = vwp(self.alpha, replaceParamFile) try: openFile.write('ALPHA%s%.6f\n' % (' ' * 7, alpha)) ...
Channel Input File Write to File Method
Below is the the instruction that describes the task: ### Input: Channel Input File Write to File Method ### Response: def _write(self, session, openFile, replaceParamFile): """ Channel Input File Write to File Method """ # Write lines openFile.write('GSSHA_CHAN\n') ...
def _send_email(name, email): "send a email to inform user of account creation" config = __salt__['config.option']('splunk') email_object = config.get('email') if email_object: cc = email_object.get('cc') subject = email_object.get('subject') message = email_object.get('message')...
send a email to inform user of account creation
Below is the the instruction that describes the task: ### Input: send a email to inform user of account creation ### Response: def _send_email(name, email): "send a email to inform user of account creation" config = __salt__['config.option']('splunk') email_object = config.get('email') if email_obj...
def congestionControl(Cause_presence=0): """CONGESTION CONTROL Section 9.3.4""" a = TpPd(pd=0x3) b = MessageType(mesType=0x39) # 00111001 c = CongestionLevelAndSpareHalfOctets() packet = a / b / c if Cause_presence is 1: e = CauseHdr(ieiC=0x08, eightBitC=0x0) packet = packet / e...
CONGESTION CONTROL Section 9.3.4
Below is the the instruction that describes the task: ### Input: CONGESTION CONTROL Section 9.3.4 ### Response: def congestionControl(Cause_presence=0): """CONGESTION CONTROL Section 9.3.4""" a = TpPd(pd=0x3) b = MessageType(mesType=0x39) # 00111001 c = CongestionLevelAndSpareHalfOctets() pack...
def ParseHeader(cls, script_data): """Parse a script integrity header. This function makes sure any integrity hashes are correctly parsed and returns a ScriptHeader structure containing the information that it was able to parse out. Args: script_data (bytearray): Th...
Parse a script integrity header. This function makes sure any integrity hashes are correctly parsed and returns a ScriptHeader structure containing the information that it was able to parse out. Args: script_data (bytearray): The script that we should parse. Raises...
Below is the the instruction that describes the task: ### Input: Parse a script integrity header. This function makes sure any integrity hashes are correctly parsed and returns a ScriptHeader structure containing the information that it was able to parse out. Args: scri...
def list_tags(self, image_name): # type: (str) -> Iterator[str] """ List all tags for the given image stored in the registry. Args: image_name (str): The name of the image to query. The image must be present on the registry for this call to return any...
List all tags for the given image stored in the registry. Args: image_name (str): The name of the image to query. The image must be present on the registry for this call to return any values. Returns: list[str]: List of tags for that image.
Below is the the instruction that describes the task: ### Input: List all tags for the given image stored in the registry. Args: image_name (str): The name of the image to query. The image must be present on the registry for this call to return any values. ...
def remove_provider(self, id): ''' Remove the provider with the given id or :term:`URI`. :param str id: The identifier for the provider. :returns: A :class:`skosprovider.providers.VocabularyProvider` or `False` if the id is unknown. ''' if id in self.provider...
Remove the provider with the given id or :term:`URI`. :param str id: The identifier for the provider. :returns: A :class:`skosprovider.providers.VocabularyProvider` or `False` if the id is unknown.
Below is the the instruction that describes the task: ### Input: Remove the provider with the given id or :term:`URI`. :param str id: The identifier for the provider. :returns: A :class:`skosprovider.providers.VocabularyProvider` or `False` if the id is unknown. ### Response: def remov...
def cpp_best_split_full_model(X, Uy, C, S, U, noderange, delta, save_memory=False): """wrappe calling cpp splitting function""" return CSP.best_split_full_model(X, Uy, C, S, U, noderange, delta)
wrappe calling cpp splitting function
Below is the the instruction that describes the task: ### Input: wrappe calling cpp splitting function ### Response: def cpp_best_split_full_model(X, Uy, C, S, U, noderange, delta, save_memory=False): """wrappe calling cpp splitting function""" return CSP.best_split_full_model...
def collectTriggers(self, rgx, code): """Return a dictionary of triggers and their corresponding matches from the code. """ return {m.group(0): m for m in re.finditer(rgx, code)}
Return a dictionary of triggers and their corresponding matches from the code.
Below is the the instruction that describes the task: ### Input: Return a dictionary of triggers and their corresponding matches from the code. ### Response: def collectTriggers(self, rgx, code): """Return a dictionary of triggers and their corresponding matches from the code. """ ...
def f_remove_child(self, name, recursive=False, predicate=None): """Removes a child of the group. Note that groups and leaves are only removed from the current trajectory in RAM. If the trajectory is stored to disk, this data is not affected. Thus, removing children can be only be used ...
Removes a child of the group. Note that groups and leaves are only removed from the current trajectory in RAM. If the trajectory is stored to disk, this data is not affected. Thus, removing children can be only be used to free RAM memory! If you want to free memory on disk via your sto...
Below is the the instruction that describes the task: ### Input: Removes a child of the group. Note that groups and leaves are only removed from the current trajectory in RAM. If the trajectory is stored to disk, this data is not affected. Thus, removing children can be only be used to free...
def clean_restructuredtext(form_instance, content): """ RST syntax validation """ if content: errors = SourceReporter(content) if errors: raise ValidationError(map(map_parsing_errors, errors)) return content
RST syntax validation
Below is the the instruction that describes the task: ### Input: RST syntax validation ### Response: def clean_restructuredtext(form_instance, content): """ RST syntax validation """ if content: errors = SourceReporter(content) if errors: raise ValidationError(map(map_pa...
def _get_new_alive_state(self, new_seq, new_log_probs, new_cache): """Gather the top k sequences that are still alive. Args: new_seq: New sequences generated by growing the current alive sequences int32 tensor with shape [batch_size, 2 * beam_size, cur_index + 1] new_log_probs: Log probabil...
Gather the top k sequences that are still alive. Args: new_seq: New sequences generated by growing the current alive sequences int32 tensor with shape [batch_size, 2 * beam_size, cur_index + 1] new_log_probs: Log probabilities of new sequences float32 tensor with shape [batch_size, beam...
Below is the the instruction that describes the task: ### Input: Gather the top k sequences that are still alive. Args: new_seq: New sequences generated by growing the current alive sequences int32 tensor with shape [batch_size, 2 * beam_size, cur_index + 1] new_log_probs: Log probabilities...
def load_plugins(self, plugin_dirs=None, quiet=True): """ Load plugins in `sys.path` and :attr:`plugin_dirs` Parameters ---------- plugin_dirs : list or tuple of string, optional A list or tuple of plugin directory path quiet : bool, optional If T...
Load plugins in `sys.path` and :attr:`plugin_dirs` Parameters ---------- plugin_dirs : list or tuple of string, optional A list or tuple of plugin directory path quiet : bool, optional If True, print all error message
Below is the the instruction that describes the task: ### Input: Load plugins in `sys.path` and :attr:`plugin_dirs` Parameters ---------- plugin_dirs : list or tuple of string, optional A list or tuple of plugin directory path quiet : bool, optional If True, ...
def set_state_from_file(self, filename): """Sets the state of the sampler back to the instance saved in a file. """ with self.io(filename, 'r') as fp: rstate = fp.read_random_state() # set the numpy random state numpy.random.set_state(rstate) # set emcee's gen...
Sets the state of the sampler back to the instance saved in a file.
Below is the the instruction that describes the task: ### Input: Sets the state of the sampler back to the instance saved in a file. ### Response: def set_state_from_file(self, filename): """Sets the state of the sampler back to the instance saved in a file. """ with self.io(filename, 'r') ...
def getOutput(self): """ Returns the combined output of stdout and stderr """ output = self.stdout if self.stdout: output += '\r\n' output += self.stderr return output
Returns the combined output of stdout and stderr
Below is the the instruction that describes the task: ### Input: Returns the combined output of stdout and stderr ### Response: def getOutput(self): """ Returns the combined output of stdout and stderr """ output = self.stdout if self.stdout: output += '\r\n' ...
def get(self, request, *args, **kwargs): """ method called on GET request on this view :param django.http.HttpRequest request: The current request object """ logger.info("logout requested") # initialize the class attributes self.init_get(request) ...
method called on GET request on this view :param django.http.HttpRequest request: The current request object
Below is the the instruction that describes the task: ### Input: method called on GET request on this view :param django.http.HttpRequest request: The current request object ### Response: def get(self, request, *args, **kwargs): """ method called on GET request on this view ...
def get_app(system_version_file: str = None, config_file_override: str = None, name_override: str = None, loop: asyncio.AbstractEventLoop = None) -> web.Application: """ Build and return the aiohttp.web.Application that runs the server The params can be overloaded for testin...
Build and return the aiohttp.web.Application that runs the server The params can be overloaded for testing.
Below is the the instruction that describes the task: ### Input: Build and return the aiohttp.web.Application that runs the server The params can be overloaded for testing. ### Response: def get_app(system_version_file: str = None, config_file_override: str = None, name_override: str =...
def sign(self): """Generates a signature""" payload = self._payload() sigin = b'.'.join([self.protected.encode('utf-8'), payload]) signature = self.engine.sign(self.key, sigin) return {'protected': self.protected, 'payload': payload, 'signature': b...
Generates a signature
Below is the the instruction that describes the task: ### Input: Generates a signature ### Response: def sign(self): """Generates a signature""" payload = self._payload() sigin = b'.'.join([self.protected.encode('utf-8'), payload]) signature = self.engine.sign(self.key, sigin) ...
def main(argv=None): '''Command line options.''' program_name = os.path.basename(sys.argv[0]) program_version = version program_build_date = "%s" % __updated__ program_version_string = '%%prog %s (%s)' % (program_version, program_build_date) #program_usage = '''usage: spam two eggs''' # option...
Command line options.
Below is the the instruction that describes the task: ### Input: Command line options. ### Response: def main(argv=None): '''Command line options.''' program_name = os.path.basename(sys.argv[0]) program_version = version program_build_date = "%s" % __updated__ program_version_string = '%%prog...
def _init_edges(p2cs, c2ps): """Get the directed edges from GO term to GO term.""" edge_from_to = [] for parent, children in p2cs.items(): for child in children: # if child in goids_present and parent in goids_present: edge_from_to.append((child, paren...
Get the directed edges from GO term to GO term.
Below is the the instruction that describes the task: ### Input: Get the directed edges from GO term to GO term. ### Response: def _init_edges(p2cs, c2ps): """Get the directed edges from GO term to GO term.""" edge_from_to = [] for parent, children in p2cs.items(): for child in ...
def bresenham_circle_octant(radius): """ Uses Bresenham's algorithm to draw a single octant of a circle with thickness 1, centered on the origin and with the given radius. :param radius: The radius of the circle to draw :return: A list of integer coordinates representing pixels. Starts at (radiu...
Uses Bresenham's algorithm to draw a single octant of a circle with thickness 1, centered on the origin and with the given radius. :param radius: The radius of the circle to draw :return: A list of integer coordinates representing pixels. Starts at (radius, 0) and end with a pixel (x, y) where x == y.
Below is the the instruction that describes the task: ### Input: Uses Bresenham's algorithm to draw a single octant of a circle with thickness 1, centered on the origin and with the given radius. :param radius: The radius of the circle to draw :return: A list of integer coordinates representing pixels. ...
def load_go_graph(go_fname): """Load the GO data from an OWL file and parse into an RDF graph. Parameters ---------- go_fname : str Path to the GO OWL file. Can be downloaded from http://geneontology.org/ontology/go.owl. Returns ------- rdflib.Graph RDF graph contai...
Load the GO data from an OWL file and parse into an RDF graph. Parameters ---------- go_fname : str Path to the GO OWL file. Can be downloaded from http://geneontology.org/ontology/go.owl. Returns ------- rdflib.Graph RDF graph containing GO data.
Below is the the instruction that describes the task: ### Input: Load the GO data from an OWL file and parse into an RDF graph. Parameters ---------- go_fname : str Path to the GO OWL file. Can be downloaded from http://geneontology.org/ontology/go.owl. Returns ------- rdfl...
def _parse_response(self, response): """Parses the API response and raises appropriate errors if raise_errors was set to True """ if not self._raise_errors: return response is_4xx_error = str(response.status_code)[0] == '4' is_5xx_error = str(response.status_...
Parses the API response and raises appropriate errors if raise_errors was set to True
Below is the the instruction that describes the task: ### Input: Parses the API response and raises appropriate errors if raise_errors was set to True ### Response: def _parse_response(self, response): """Parses the API response and raises appropriate errors if raise_errors was set to True ...
def dict_to_unicode(raw_dict): """ Ensure all keys and values in a dict are unicode. The passed dict is assumed to have lists for all values. """ decoded = {} for key, value in raw_dict.items(): decoded[to_unicode(key)] = map( to_unicode, value) return decoded
Ensure all keys and values in a dict are unicode. The passed dict is assumed to have lists for all values.
Below is the the instruction that describes the task: ### Input: Ensure all keys and values in a dict are unicode. The passed dict is assumed to have lists for all values. ### Response: def dict_to_unicode(raw_dict): """ Ensure all keys and values in a dict are unicode. The passed dict is assumed...
def model_summary(model, solution=None, threshold=0.01, fva=None, names=False, floatfmt='.3g'): """ Print a summary of the input and output fluxes of the model. Parameters ---------- solution: cobra.Solution, optional A previously solved model solution to use for generatin...
Print a summary of the input and output fluxes of the model. Parameters ---------- solution: cobra.Solution, optional A previously solved model solution to use for generating the summary. If none provided (default), the summary method will resolve the model. Note that the solution o...
Below is the the instruction that describes the task: ### Input: Print a summary of the input and output fluxes of the model. Parameters ---------- solution: cobra.Solution, optional A previously solved model solution to use for generating the summary. If none provided (default), the su...
def grok_filter_name(element): """Extracts the name, which may be embedded, for a Jinja2 filter node""" e_name = None if element.name == 'default': if isinstance(element.node, jinja2.nodes.Getattr): e_name = element.node.node.name else: e_name = element.node.name ...
Extracts the name, which may be embedded, for a Jinja2 filter node
Below is the the instruction that describes the task: ### Input: Extracts the name, which may be embedded, for a Jinja2 filter node ### Response: def grok_filter_name(element): """Extracts the name, which may be embedded, for a Jinja2 filter node""" e_name = None if element.name == 'default': ...
def update_records(self, domain, records): """ Modifies an existing records for a domain. """ if not isinstance(records, list): raise TypeError("Expected records of type list") uri = "/domains/%s/records" % utils.get_id(domain) resp, resp_body = self._async_ca...
Modifies an existing records for a domain.
Below is the the instruction that describes the task: ### Input: Modifies an existing records for a domain. ### Response: def update_records(self, domain, records): """ Modifies an existing records for a domain. """ if not isinstance(records, list): raise TypeError("Expe...
def _asarray(self, vec): """Convert ``x`` to an array. Here the indices are changed such that the "outer" indices come last in order to have the access order as `numpy.linalg.svd` needs it. This is the inverse of `_asvector`. """ shape = self.domain[0, 0].shape + self.p...
Convert ``x`` to an array. Here the indices are changed such that the "outer" indices come last in order to have the access order as `numpy.linalg.svd` needs it. This is the inverse of `_asvector`.
Below is the the instruction that describes the task: ### Input: Convert ``x`` to an array. Here the indices are changed such that the "outer" indices come last in order to have the access order as `numpy.linalg.svd` needs it. This is the inverse of `_asvector`. ### Response: def _asarray...
def cmd_fence(self, args): '''fence commands''' if len(args) < 1: self.print_usage() return if args[0] == "enable": self.set_fence_enabled(1) elif args[0] == "disable": self.set_fence_enabled(0) elif args[0] == "load": ...
fence commands
Below is the the instruction that describes the task: ### Input: fence commands ### Response: def cmd_fence(self, args): '''fence commands''' if len(args) < 1: self.print_usage() return if args[0] == "enable": self.set_fence_enabled(1) elif args[...
def next_frame_id(self): """ Gets a byte of the next valid frame ID (1 - 255), increments the internal _frame_id counter and wraps it back to 1 if necessary. """ # Python 2/3 compatible way of converting 1 to "\x01" in py2 or b"\x01" # in py3. fid = bytes(bytearra...
Gets a byte of the next valid frame ID (1 - 255), increments the internal _frame_id counter and wraps it back to 1 if necessary.
Below is the the instruction that describes the task: ### Input: Gets a byte of the next valid frame ID (1 - 255), increments the internal _frame_id counter and wraps it back to 1 if necessary. ### Response: def next_frame_id(self): """ Gets a byte of the next valid frame ID (1 - 255), incr...
def calculable(self): """Check if class is calculable by its kwargs""" self._thermo = "" if self.kwargs["T"] and self.kwargs["P"]: self._thermo = "TP" elif self.kwargs["P"] and self.kwargs["h"] is not None: self._thermo = "Ph" elif self.kwargs["P"] and sel...
Check if class is calculable by its kwargs
Below is the the instruction that describes the task: ### Input: Check if class is calculable by its kwargs ### Response: def calculable(self): """Check if class is calculable by its kwargs""" self._thermo = "" if self.kwargs["T"] and self.kwargs["P"]: self._thermo = "TP" ...
def novo(args): """ %prog novo reads.fastq Reference-free tGBS pipeline v1. """ from jcvi.assembly.kmer import jellyfish, histogram from jcvi.assembly.preprocess import diginorm from jcvi.formats.fasta import filter as fasta_filter, format from jcvi.apps.cdhit import filter as cdhit_fil...
%prog novo reads.fastq Reference-free tGBS pipeline v1.
Below is the the instruction that describes the task: ### Input: %prog novo reads.fastq Reference-free tGBS pipeline v1. ### Response: def novo(args): """ %prog novo reads.fastq Reference-free tGBS pipeline v1. """ from jcvi.assembly.kmer import jellyfish, histogram from jcvi.assembly...
def ToByteArray(self): """ Serialize self and get the byte stream. Returns: bytes: serialized object. """ ms = StreamManager.GetStream() writer = BinaryWriter(ms) self.Serialize(writer) retval = ms.ToArray() StreamManager.ReleaseStrea...
Serialize self and get the byte stream. Returns: bytes: serialized object.
Below is the the instruction that describes the task: ### Input: Serialize self and get the byte stream. Returns: bytes: serialized object. ### Response: def ToByteArray(self): """ Serialize self and get the byte stream. Returns: bytes: serialized object. ...
def copy_file( source_path, target_path, allow_undo=True, no_confirm=False, rename_on_collision=True, silent=False, extra_flags=0, hWnd=None ): """Perform a shell-based file copy. Copying in this way allows the possibility of undo, auto-renaming, and showing the "flying file"...
Perform a shell-based file copy. Copying in this way allows the possibility of undo, auto-renaming, and showing the "flying file" animation during the copy. The default options allow for undo, don't automatically clobber on a name clash, automatically rename on collision and display the animation.
Below is the the instruction that describes the task: ### Input: Perform a shell-based file copy. Copying in this way allows the possibility of undo, auto-renaming, and showing the "flying file" animation during the copy. The default options allow for undo, don't automatically clobber on a name cla...
def publish_receiver_count(self, service, routing_id): '''Get the number of peers that would handle a particular publish :param service: the service name :type service: anything hash-able :param routing_id: the id used for limiting the service handlers :type routing_id: int ...
Get the number of peers that would handle a particular publish :param service: the service name :type service: anything hash-able :param routing_id: the id used for limiting the service handlers :type routing_id: int
Below is the the instruction that describes the task: ### Input: Get the number of peers that would handle a particular publish :param service: the service name :type service: anything hash-able :param routing_id: the id used for limiting the service handlers :type routing_id: int #...
def load_http_response(cls, http_response): """ This method should return an instantiated class and set its response to the requests.Response object. """ if not http_response.ok: raise APIResponseError(http_response.text) c = cls(http_response) c.respo...
This method should return an instantiated class and set its response to the requests.Response object.
Below is the the instruction that describes the task: ### Input: This method should return an instantiated class and set its response to the requests.Response object. ### Response: def load_http_response(cls, http_response): """ This method should return an instantiated class and set its re...
def encrypt_files(self, file_list, force_nocompress=False, force_compress=False, armored=False, checksum=False): """public method for multiple file encryption with optional compression, ASCII armored formatting, and file hash digest generation""" for the_file in file_list: self.encrypt_file(...
public method for multiple file encryption with optional compression, ASCII armored formatting, and file hash digest generation
Below is the the instruction that describes the task: ### Input: public method for multiple file encryption with optional compression, ASCII armored formatting, and file hash digest generation ### Response: def encrypt_files(self, file_list, force_nocompress=False, force_compress=False, armored=False, checksum=Fal...
def option_parser(): """Option Parser to give various options.""" usage = ''' $ ./crawler -d5 <url> Here in this case it goes till depth of 5 and url is target URL to start crawling. ''' version = "2.0.0" parser = optparse.OptionParser(usage=usag...
Option Parser to give various options.
Below is the the instruction that describes the task: ### Input: Option Parser to give various options. ### Response: def option_parser(): """Option Parser to give various options.""" usage = ''' $ ./crawler -d5 <url> Here in this case it goes till depth of 5 and url is target ...
def update_current_retention_level(self, value): """Set a new value for the current retention level. This updates the value of self.retain_files for an updated value of the retention level. Parameters ----------- value : int The new value to use for the rete...
Set a new value for the current retention level. This updates the value of self.retain_files for an updated value of the retention level. Parameters ----------- value : int The new value to use for the retention level.
Below is the the instruction that describes the task: ### Input: Set a new value for the current retention level. This updates the value of self.retain_files for an updated value of the retention level. Parameters ----------- value : int The new value to use for...
def find_word_prob(word_string, word_total=sum(WORD_DISTRIBUTION.values())): ''' Finds the relative probability of the word appearing given context of a base corpus. Returns this probability value as a float instance. ''' if word_string is None: return 0 elif isinstance(word_string, str)...
Finds the relative probability of the word appearing given context of a base corpus. Returns this probability value as a float instance.
Below is the the instruction that describes the task: ### Input: Finds the relative probability of the word appearing given context of a base corpus. Returns this probability value as a float instance. ### Response: def find_word_prob(word_string, word_total=sum(WORD_DISTRIBUTION.values())): ''' Finds ...
def _run_cnvkit_cancer(items, background): """Run CNVkit on a tumor/normal pair. """ paired = vcfutils.get_paired_bams([x["align_bam"] for x in items], items) normal_data = [x for x in items if dd.get_sample_name(x) != paired.tumor_name] tumor_ready, normal_ready = _match_batches(paired.tumor_data, ...
Run CNVkit on a tumor/normal pair.
Below is the the instruction that describes the task: ### Input: Run CNVkit on a tumor/normal pair. ### Response: def _run_cnvkit_cancer(items, background): """Run CNVkit on a tumor/normal pair. """ paired = vcfutils.get_paired_bams([x["align_bam"] for x in items], items) normal_data = [x for x in ...
def _islots(self): """ Return an iterator with the inferred slots. """ if "__slots__" not in self.locals: return None for slots in self.igetattr("__slots__"): # check if __slots__ is a valid type for meth in ITER_METHODS: try: ...
Return an iterator with the inferred slots.
Below is the the instruction that describes the task: ### Input: Return an iterator with the inferred slots. ### Response: def _islots(self): """ Return an iterator with the inferred slots. """ if "__slots__" not in self.locals: return None for slots in self.igetattr("__slots__"...
def save_params( self, f=None, f_params=None, f_optimizer=None, f_history=None): """Saves the module's parameters, history, and optimizer, not the whole object. To save the whole object, use pickle. ``f_params`` and ``f_optimizer`` uses PyTorchs' :func:`~torch.save`...
Saves the module's parameters, history, and optimizer, not the whole object. To save the whole object, use pickle. ``f_params`` and ``f_optimizer`` uses PyTorchs' :func:`~torch.save`. Parameters ---------- f_params : file-like object, str, None (default=None) ...
Below is the the instruction that describes the task: ### Input: Saves the module's parameters, history, and optimizer, not the whole object. To save the whole object, use pickle. ``f_params`` and ``f_optimizer`` uses PyTorchs' :func:`~torch.save`. Parameters -----...
def import_all_modules(package, skip=None, verbose=False, prefix="", depth=0): """Recursively imports all subpackages, modules, and submodules of a given package. 'package' should be an imported package, not a string. 'skip' is a list of modules or subpackages not to import. """ skip = [] if sk...
Recursively imports all subpackages, modules, and submodules of a given package. 'package' should be an imported package, not a string. 'skip' is a list of modules or subpackages not to import.
Below is the the instruction that describes the task: ### Input: Recursively imports all subpackages, modules, and submodules of a given package. 'package' should be an imported package, not a string. 'skip' is a list of modules or subpackages not to import. ### Response: def import_all_modules(package...
def get_tool(name): """ Returns an instance of a specific tool. Parameters ---------- name : str Name of the tool (case-insensitive). Returns ------- tool : MotifProgram instance """ tool = name.lower() if tool not in __tools__: raise ValueError("Tool {0} n...
Returns an instance of a specific tool. Parameters ---------- name : str Name of the tool (case-insensitive). Returns ------- tool : MotifProgram instance
Below is the the instruction that describes the task: ### Input: Returns an instance of a specific tool. Parameters ---------- name : str Name of the tool (case-insensitive). Returns ------- tool : MotifProgram instance ### Response: def get_tool(name): """ Returns an ins...
def create_validator(data_struct_dict, name=None): """ create a Validator instance from data_struct_dict :param data_struct_dict: a dict describe validator's fields, like the dict `to_dict()` method returned. :param name: name of Validator class :return: Validator instance """ if name is...
create a Validator instance from data_struct_dict :param data_struct_dict: a dict describe validator's fields, like the dict `to_dict()` method returned. :param name: name of Validator class :return: Validator instance
Below is the the instruction that describes the task: ### Input: create a Validator instance from data_struct_dict :param data_struct_dict: a dict describe validator's fields, like the dict `to_dict()` method returned. :param name: name of Validator class :return: Validator instance ### Response: de...
def get_args(): """Get the script arguments.""" description = "bum - Download and display album art \ for mpd tracks." arg = argparse.ArgumentParser(description=description) arg.add_argument("--size", metavar="\"px\"", help="what size to display the album art in....
Get the script arguments.
Below is the the instruction that describes the task: ### Input: Get the script arguments. ### Response: def get_args(): """Get the script arguments.""" description = "bum - Download and display album art \ for mpd tracks." arg = argparse.ArgumentParser(description=description) ...
def pltnp(point, v1, v2, v3): """ Find the nearest point on a triangular plate to a given point. https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/pltnp_c.html :param point: A point in 3-dimensional space. :type point: 3-Element Array of floats :param v1: Vertices of a triangu...
Find the nearest point on a triangular plate to a given point. https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/pltnp_c.html :param point: A point in 3-dimensional space. :type point: 3-Element Array of floats :param v1: Vertices of a triangular plate. :type v1: 3-Element Array o...
Below is the the instruction that describes the task: ### Input: Find the nearest point on a triangular plate to a given point. https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/pltnp_c.html :param point: A point in 3-dimensional space. :type point: 3-Element Array of floats :para...
def _locations_mirror(x): """ Mirrors the points in a list-of-list-of-...-of-list-of-points. For example: >>> _locations_mirror([[[1, 2], [3, 4]], [5, 6], [7, 8]]) [[[2, 1], [4, 3]], [6, 5], [8, 7]] """ if hasattr(x, '__iter__'): if hasattr(x[0], '__iter__'): return list...
Mirrors the points in a list-of-list-of-...-of-list-of-points. For example: >>> _locations_mirror([[[1, 2], [3, 4]], [5, 6], [7, 8]]) [[[2, 1], [4, 3]], [6, 5], [8, 7]]
Below is the the instruction that describes the task: ### Input: Mirrors the points in a list-of-list-of-...-of-list-of-points. For example: >>> _locations_mirror([[[1, 2], [3, 4]], [5, 6], [7, 8]]) [[[2, 1], [4, 3]], [6, 5], [8, 7]] ### Response: def _locations_mirror(x): """ Mirrors the point...
def _conv_tel_list(tel_list, entry): """Converts to Abook phone types""" for tel in tel_list: if not hasattr(tel, 'TYPE_param'): entry['other'] = tel.value elif tel.TYPE_param.lower() == 'home': entry['phone'] = tel.value elif tel.TYPE_...
Converts to Abook phone types
Below is the the instruction that describes the task: ### Input: Converts to Abook phone types ### Response: def _conv_tel_list(tel_list, entry): """Converts to Abook phone types""" for tel in tel_list: if not hasattr(tel, 'TYPE_param'): entry['other'] = tel.value ...
def oplot(self, x, y, **kw): """generic plotting method, overplotting any existing plot """ self.panel.oplot(x, y, **kw)
generic plotting method, overplotting any existing plot
Below is the the instruction that describes the task: ### Input: generic plotting method, overplotting any existing plot ### Response: def oplot(self, x, y, **kw): """generic plotting method, overplotting any existing plot """ self.panel.oplot(x, y, **kw)
def get_volume(self): """Get the current volume.""" self.request(EP_GET_VOLUME) return 0 if self.last_response is None else self.last_response.get('payload').get('volume')
Get the current volume.
Below is the the instruction that describes the task: ### Input: Get the current volume. ### Response: def get_volume(self): """Get the current volume.""" self.request(EP_GET_VOLUME) return 0 if self.last_response is None else self.last_response.get('payload').get('volume')
def GetFormattedEventObject(cls, event): """Retrieves a string representation of the event. Args: event (EventObject): event. Returns: str: string representation of the event. """ time_string = timelib.Timestamp.CopyToIsoFormat(event.timestamp) lines_of_text = [ '+-' * 40,...
Retrieves a string representation of the event. Args: event (EventObject): event. Returns: str: string representation of the event.
Below is the the instruction that describes the task: ### Input: Retrieves a string representation of the event. Args: event (EventObject): event. Returns: str: string representation of the event. ### Response: def GetFormattedEventObject(cls, event): """Retrieves a string representation ...
def load_dataset_items(test_file, predict_file_lst, nonfeature_file): """ This function is used to read 3 kinds of data into list, 3 kinds of data are stored in files given by parameter :param test_file: path string, the testing set used for SVm rank :param predict_file_lst: filename lst, all predic...
This function is used to read 3 kinds of data into list, 3 kinds of data are stored in files given by parameter :param test_file: path string, the testing set used for SVm rank :param predict_file_lst: filename lst, all prediction file output by SVM rank :param nonfeature_file: path string, contain all t...
Below is the the instruction that describes the task: ### Input: This function is used to read 3 kinds of data into list, 3 kinds of data are stored in files given by parameter :param test_file: path string, the testing set used for SVm rank :param predict_file_lst: filename lst, all prediction file outpu...
def process_net_command(self, py_db, cmd_id, seq, text): '''Processes a command received from the Java side @param cmd_id: the id of the command @param seq: the sequence of the command @param text: the text received in the command ''' meaning = ID_TO_MEANING[str(cmd_id)]...
Processes a command received from the Java side @param cmd_id: the id of the command @param seq: the sequence of the command @param text: the text received in the command
Below is the the instruction that describes the task: ### Input: Processes a command received from the Java side @param cmd_id: the id of the command @param seq: the sequence of the command @param text: the text received in the command ### Response: def process_net_command(self, py_db, cmd...
def recall(links_true, links_pred=None): """recall(links_true, links_pred) Compute the recall/sensitivity. The recall is given by TP/(TP+FN). Parameters ---------- links_true: pandas.MultiIndex, pandas.DataFrame, pandas.Series The true (or actual) collection of links. links_pred: ...
recall(links_true, links_pred) Compute the recall/sensitivity. The recall is given by TP/(TP+FN). Parameters ---------- links_true: pandas.MultiIndex, pandas.DataFrame, pandas.Series The true (or actual) collection of links. links_pred: pandas.MultiIndex, pandas.DataFrame, pandas.Seri...
Below is the the instruction that describes the task: ### Input: recall(links_true, links_pred) Compute the recall/sensitivity. The recall is given by TP/(TP+FN). Parameters ---------- links_true: pandas.MultiIndex, pandas.DataFrame, pandas.Series The true (or actual) collection of li...
def _has_desired_permit(permits, acategory, astatus): """ return True if permits has one whose category_code and status_code match with the given ones """ if permits is None: return False for permit in permits: if permit.category_code == acategory and\ permit.status_co...
return True if permits has one whose category_code and status_code match with the given ones
Below is the the instruction that describes the task: ### Input: return True if permits has one whose category_code and status_code match with the given ones ### Response: def _has_desired_permit(permits, acategory, astatus): """ return True if permits has one whose category_code and status_code ma...
def terminate(self): """Terminate all workers and threads.""" for t in self._threads: t.quit() self._thread = [] self._workers = []
Terminate all workers and threads.
Below is the the instruction that describes the task: ### Input: Terminate all workers and threads. ### Response: def terminate(self): """Terminate all workers and threads.""" for t in self._threads: t.quit() self._thread = [] self._workers = []
def save_stream(self, key, binary=False): """ Return a managed file-like object into which the calling code can write arbitrary data. :param key: :return: A managed stream-like object """ s = io.BytesIO() if binary else io.StringIO() yield s self....
Return a managed file-like object into which the calling code can write arbitrary data. :param key: :return: A managed stream-like object
Below is the the instruction that describes the task: ### Input: Return a managed file-like object into which the calling code can write arbitrary data. :param key: :return: A managed stream-like object ### Response: def save_stream(self, key, binary=False): """ Return a ma...
def attention_bias_local_block(mesh, block_length, memory_length, dtype=tf.int32): """Bias for attention for local blocks where attention to right is disallowed. Create the bias matrix by using two separate masks, one for the memory part which doesn't overlap with the query and sec...
Bias for attention for local blocks where attention to right is disallowed. Create the bias matrix by using two separate masks, one for the memory part which doesn't overlap with the query and second which interacts with the query and should be disallowed to look to the right of the current query position. Ar...
Below is the the instruction that describes the task: ### Input: Bias for attention for local blocks where attention to right is disallowed. Create the bias matrix by using two separate masks, one for the memory part which doesn't overlap with the query and second which interacts with the query and should be...
def _seqtk_fastq_prep_cl(data, in_file=None, read_num=0): """Provide a commandline for prep of fastq inputs with seqtk. Handles fast conversion of fastq quality scores and trimming. """ needs_convert = dd.get_quality_format(data).lower() == "illumina" trim_ends = dd.get_trim_ends(data) seqtk = ...
Provide a commandline for prep of fastq inputs with seqtk. Handles fast conversion of fastq quality scores and trimming.
Below is the the instruction that describes the task: ### Input: Provide a commandline for prep of fastq inputs with seqtk. Handles fast conversion of fastq quality scores and trimming. ### Response: def _seqtk_fastq_prep_cl(data, in_file=None, read_num=0): """Provide a commandline for prep of fastq input...