code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def ordersku_update(self, oid, sku_id=None, sku_props=None): '''taobao.trade.ordersku.update 更新交易订单的销售属性 需要商家或以上权限才可调用此接口,可重复调用本接口更新交易备注,本接口同时具有添加备注的功能''' request = TOPRequest('taobao.trade.ordersku.update') request['oid'] = oid if sku_id!=None: request['sku_id'] = sku_i...
taobao.trade.ordersku.update 更新交易订单的销售属性 需要商家或以上权限才可调用此接口,可重复调用本接口更新交易备注,本接口同时具有添加备注的功能
Below is the the instruction that describes the task: ### Input: taobao.trade.ordersku.update 更新交易订单的销售属性 需要商家或以上权限才可调用此接口,可重复调用本接口更新交易备注,本接口同时具有添加备注的功能 ### Response: def ordersku_update(self, oid, sku_id=None, sku_props=None): '''taobao.trade.ordersku.update 更新交易订单的销售属性 需...
def http_construct(args, unknown): """ Construct the --http <arg> from the args/unknown space -- relevant only for 'purl'. :param args: :param unknown: :return: """ str_http = '' b_httpSpecd = False if '--http' in unknown: try: str_httpArg = unknown[unknown....
Construct the --http <arg> from the args/unknown space -- relevant only for 'purl'. :param args: :param unknown: :return:
Below is the the instruction that describes the task: ### Input: Construct the --http <arg> from the args/unknown space -- relevant only for 'purl'. :param args: :param unknown: :return: ### Response: def http_construct(args, unknown): """ Construct the --http <arg> from the args/unknown space...
def _get_service(name): ''' Get information about a service. If the service is not found, raise an error :param str name: Service label, file name, or full path :return: The service information for the service, otherwise an Error :rtype: dict ''' services = __utils__['mac_utils.availa...
Get information about a service. If the service is not found, raise an error :param str name: Service label, file name, or full path :return: The service information for the service, otherwise an Error :rtype: dict
Below is the the instruction that describes the task: ### Input: Get information about a service. If the service is not found, raise an error :param str name: Service label, file name, or full path :return: The service information for the service, otherwise an Error :rtype: dict ### Response: de...
def promote(self, level=None): """Convert to the next higher level summary level""" if level is None: if len(self.fields) < 2: if self.level in ('region', 'division', 'state', 'ua'): cls = self.get_class('us') else: re...
Convert to the next higher level summary level
Below is the the instruction that describes the task: ### Input: Convert to the next higher level summary level ### Response: def promote(self, level=None): """Convert to the next higher level summary level""" if level is None: if len(self.fields) < 2: if self.level in...
def most_visited_pages_charts(): """Chart for most visited pages.""" stats = most_visited_pages_stats() charts = [] for i, stat in enumerate(stats['more_than_10']): bound = stat['bound'] subset = stat['subset'] chart_options = { 'chart': { 'type': '...
Chart for most visited pages.
Below is the the instruction that describes the task: ### Input: Chart for most visited pages. ### Response: def most_visited_pages_charts(): """Chart for most visited pages.""" stats = most_visited_pages_stats() charts = [] for i, stat in enumerate(stats['more_than_10']): bound = stat['b...
def pre_process_data(filepath): """ This is dependent on your training data source but we will try to generalize it as best as possible. """ positive_path = os.path.join(filepath, 'pos') negative_path = os.path.join(filepath, 'neg') pos_label = 1 neg_label = 0 dataset = [] for fil...
This is dependent on your training data source but we will try to generalize it as best as possible.
Below is the the instruction that describes the task: ### Input: This is dependent on your training data source but we will try to generalize it as best as possible. ### Response: def pre_process_data(filepath): """ This is dependent on your training data source but we will try to generalize it as best as ...
def get_source(fileobj): """Translate fileobj into file contents. fileobj is either a string or a dict. If it's a string, that's the file contents. If it's a string, then the filename key contains the name of the file whose contents we are to use. If the dict contains a true value for the key dele...
Translate fileobj into file contents. fileobj is either a string or a dict. If it's a string, that's the file contents. If it's a string, then the filename key contains the name of the file whose contents we are to use. If the dict contains a true value for the key delete_after_use, the file shoul...
Below is the the instruction that describes the task: ### Input: Translate fileobj into file contents. fileobj is either a string or a dict. If it's a string, that's the file contents. If it's a string, then the filename key contains the name of the file whose contents we are to use. If the dict c...
def classify_users(X_test, model, classifier_type, meta_model, upper_cutoff): """ Uses a trained model and the unlabelled features to associate users with labels. The decision is done as per scikit-learn: http://scikit-learn.org/stable/modules/generated/sklearn.multiclass.OneVsRestClassifier.html h...
Uses a trained model and the unlabelled features to associate users with labels. The decision is done as per scikit-learn: http://scikit-learn.org/stable/modules/generated/sklearn.multiclass.OneVsRestClassifier.html http://scikit-learn.org/stable/modules/generated/sklearn.svm.LinearSVC.html#sklearn.svm.Lin...
Below is the the instruction that describes the task: ### Input: Uses a trained model and the unlabelled features to associate users with labels. The decision is done as per scikit-learn: http://scikit-learn.org/stable/modules/generated/sklearn.multiclass.OneVsRestClassifier.html http://scikit-learn.or...
def deptree(self, field, oids, date=None, level=None, table=None): ''' Dependency tree builder. Recursively fetchs objects that are children of the initial set of parent object ids provided. :param field: Field that contains the 'parent of' data :param oids: Object oids to build...
Dependency tree builder. Recursively fetchs objects that are children of the initial set of parent object ids provided. :param field: Field that contains the 'parent of' data :param oids: Object oids to build depedency tree for :param date: date (metrique date range) that should be quer...
Below is the the instruction that describes the task: ### Input: Dependency tree builder. Recursively fetchs objects that are children of the initial set of parent object ids provided. :param field: Field that contains the 'parent of' data :param oids: Object oids to build depedency tree fo...
def create_pywbem_ssl_context(): """ Create an SSL context based on what is commonly accepted as the required limitations. This code attempts to create the same context for Python 2 and Python 3 except for the ciphers This list is based on what is currently defined in the Python SSL ...
Create an SSL context based on what is commonly accepted as the required limitations. This code attempts to create the same context for Python 2 and Python 3 except for the ciphers This list is based on what is currently defined in the Python SSL module create_default_context function ...
Below is the the instruction that describes the task: ### Input: Create an SSL context based on what is commonly accepted as the required limitations. This code attempts to create the same context for Python 2 and Python 3 except for the ciphers This list is based on what is currently define...
def rps_at(self, t): '''Return rps for second t''' if 0 <= t <= self.duration: return self.minrps + \ float(self.maxrps - self.minrps) * t / self.duration else: return 0
Return rps for second t
Below is the the instruction that describes the task: ### Input: Return rps for second t ### Response: def rps_at(self, t): '''Return rps for second t''' if 0 <= t <= self.duration: return self.minrps + \ float(self.maxrps - self.minrps) * t / self.duration else:...
def construct(self, **bindings): """Constructs the graph and returns either a tensor or a sequence. Args: **bindings: Arguments for every deferred parameter. Returns: The value that is placed into this. """ context = _assign_values_to_unbound_vars(self._unbound_vars, bindings) conte...
Constructs the graph and returns either a tensor or a sequence. Args: **bindings: Arguments for every deferred parameter. Returns: The value that is placed into this.
Below is the the instruction that describes the task: ### Input: Constructs the graph and returns either a tensor or a sequence. Args: **bindings: Arguments for every deferred parameter. Returns: The value that is placed into this. ### Response: def construct(self, **bindings): """Construc...
def get_student_current_grades(self, username, course_ids=None): """ Returns a CurrentGradesByUser object with the user current grades. Args: username (str): an edx user's username course_ids (list): a list of edX course ids. Returns: CurrentGradesBy...
Returns a CurrentGradesByUser object with the user current grades. Args: username (str): an edx user's username course_ids (list): a list of edX course ids. Returns: CurrentGradesByUser: object representing the student current grades
Below is the the instruction that describes the task: ### Input: Returns a CurrentGradesByUser object with the user current grades. Args: username (str): an edx user's username course_ids (list): a list of edX course ids. Returns: CurrentGradesByUser: object rep...
def print_line(line): """ Print given line to stdout (i3bar). """ sys.__stdout__.write("{}\n".format(line)) sys.__stdout__.flush()
Print given line to stdout (i3bar).
Below is the the instruction that describes the task: ### Input: Print given line to stdout (i3bar). ### Response: def print_line(line): """ Print given line to stdout (i3bar). """ sys.__stdout__.write("{}\n".format(line)) sys.__stdout__.flush()
async def send_maps(self, map_list): """Sends a request to the server containing maps (dicts).""" params = { 'VER': 8, # channel protocol version 'RID': 81188, # request identifier 'ctype': 'hangouts', # client type } if self._gsessionid_param is no...
Sends a request to the server containing maps (dicts).
Below is the the instruction that describes the task: ### Input: Sends a request to the server containing maps (dicts). ### Response: async def send_maps(self, map_list): """Sends a request to the server containing maps (dicts).""" params = { 'VER': 8, # channel protocol version ...
def add_filename_pattern(self, dir_name, pattern): """ Adds a Unix shell-style wildcard pattern underneath the specified directory :param dir_name: str: directory that contains the pattern :param pattern: str: Unix shell-style wildcard pattern """ full_pattern = '{}{}{}'....
Adds a Unix shell-style wildcard pattern underneath the specified directory :param dir_name: str: directory that contains the pattern :param pattern: str: Unix shell-style wildcard pattern
Below is the the instruction that describes the task: ### Input: Adds a Unix shell-style wildcard pattern underneath the specified directory :param dir_name: str: directory that contains the pattern :param pattern: str: Unix shell-style wildcard pattern ### Response: def add_filename_pattern(self, ...
def proxyInit(self): """ To receive events the proxy has to tell the CCU / Homegear where to send the events. For that we call the init-method. """ # Call init() with local XML RPC config and interface_id (the name of # the receiver) to receive events. XML RPC server has to be ru...
To receive events the proxy has to tell the CCU / Homegear where to send the events. For that we call the init-method.
Below is the the instruction that describes the task: ### Input: To receive events the proxy has to tell the CCU / Homegear where to send the events. For that we call the init-method. ### Response: def proxyInit(self): """ To receive events the proxy has to tell the CCU / Homegear where to send the...
async def add_shade_to_scene(self, shade_id, scene_id, position=None): """Add a shade to a scene.""" if position is None: _shade = await self.get_shade(shade_id) position = await _shade.get_current_position() await (SceneMembers(self.request)).create_scene_member( ...
Add a shade to a scene.
Below is the the instruction that describes the task: ### Input: Add a shade to a scene. ### Response: async def add_shade_to_scene(self, shade_id, scene_id, position=None): """Add a shade to a scene.""" if position is None: _shade = await self.get_shade(shade_id) position =...
async def verify(self, message: bytes, signature: bytes, signer: str = None) -> bool: """ Verify signature with input signer verification key (via lookup by DID first if need be). Raise WalletState if wallet is closed. :param message: Content to sign, as bytes :param signature: ...
Verify signature with input signer verification key (via lookup by DID first if need be). Raise WalletState if wallet is closed. :param message: Content to sign, as bytes :param signature: signature, as bytes :param signer: signer DID or verification key; omit for anchor's own :...
Below is the the instruction that describes the task: ### Input: Verify signature with input signer verification key (via lookup by DID first if need be). Raise WalletState if wallet is closed. :param message: Content to sign, as bytes :param signature: signature, as bytes :param si...
def DbExportEvent(self, argin): """ Export Event channel to database :param argin: Str[0] = event channel name (or factory name) Str[1] = CORBA IOR Str[2] = Notifd host name Str[3] = Notifd pid Str[4] = Notifd version :type: tango.DevVarStringArray :retur...
Export Event channel to database :param argin: Str[0] = event channel name (or factory name) Str[1] = CORBA IOR Str[2] = Notifd host name Str[3] = Notifd pid Str[4] = Notifd version :type: tango.DevVarStringArray :return: :rtype: tango.DevVoid
Below is the the instruction that describes the task: ### Input: Export Event channel to database :param argin: Str[0] = event channel name (or factory name) Str[1] = CORBA IOR Str[2] = Notifd host name Str[3] = Notifd pid Str[4] = Notifd version :type: tango.DevVarS...
def target(key, full=True): ''' Return the basename of a SysFS key path :param key: the location to resolve within SysFS :param full: full path instead of basename :return: fullpath or basename of path CLI example: .. code-block:: bash salt '*' sysfs.read class/ttyS0 ''' ...
Return the basename of a SysFS key path :param key: the location to resolve within SysFS :param full: full path instead of basename :return: fullpath or basename of path CLI example: .. code-block:: bash salt '*' sysfs.read class/ttyS0
Below is the the instruction that describes the task: ### Input: Return the basename of a SysFS key path :param key: the location to resolve within SysFS :param full: full path instead of basename :return: fullpath or basename of path CLI example: .. code-block:: bash salt '*' sysfs...
def m2i(self, pkt, s): """ ASN1F_SEQUENCE behaves transparently, with nested ASN1_objects being dissected one by one. Because we use obj.dissect (see loop below) instead of obj.m2i (as we trust dissect to do the appropriate set_vals) we do not directly retrieve the list of nested...
ASN1F_SEQUENCE behaves transparently, with nested ASN1_objects being dissected one by one. Because we use obj.dissect (see loop below) instead of obj.m2i (as we trust dissect to do the appropriate set_vals) we do not directly retrieve the list of nested objects. Thus m2i returns an empty...
Below is the the instruction that describes the task: ### Input: ASN1F_SEQUENCE behaves transparently, with nested ASN1_objects being dissected one by one. Because we use obj.dissect (see loop below) instead of obj.m2i (as we trust dissect to do the appropriate set_vals) we do not directly r...
def origin(hosts): """ Return a function that returns a valid HTTP Origin or localhost if none found. """ hosts = [urlsplit(h) for h in hosts] def func(environ): if 'ISSO_CORS_ORIGIN' in environ: return environ['ISSO_CORS_ORIGIN'] if not hosts: return "...
Return a function that returns a valid HTTP Origin or localhost if none found.
Below is the the instruction that describes the task: ### Input: Return a function that returns a valid HTTP Origin or localhost if none found. ### Response: def origin(hosts): """ Return a function that returns a valid HTTP Origin or localhost if none found. """ hosts = [urlsplit(h) for h...
def joint_sfs_folded(ac1, ac2, n1=None, n2=None): """Compute the joint folded site frequency spectrum between two populations. Parameters ---------- ac1 : array_like, int, shape (n_variants, 2) Allele counts for the first population. ac2 : array_like, int, shape (n_variants, 2) ...
Compute the joint folded site frequency spectrum between two populations. Parameters ---------- ac1 : array_like, int, shape (n_variants, 2) Allele counts for the first population. ac2 : array_like, int, shape (n_variants, 2) Allele counts for the second population. n1, n2 : int...
Below is the the instruction that describes the task: ### Input: Compute the joint folded site frequency spectrum between two populations. Parameters ---------- ac1 : array_like, int, shape (n_variants, 2) Allele counts for the first population. ac2 : array_like, int, shape (n_variants,...
def wrsamp(self, expanded=False, write_dir=''): """ Write a wfdb header file and any associated dat files from this object. Parameters ---------- expanded : bool, optional Whether to write the expanded signal (e_d_signal) instead of the uniform si...
Write a wfdb header file and any associated dat files from this object. Parameters ---------- expanded : bool, optional Whether to write the expanded signal (e_d_signal) instead of the uniform signal (d_signal). write_dir : str, optional The d...
Below is the the instruction that describes the task: ### Input: Write a wfdb header file and any associated dat files from this object. Parameters ---------- expanded : bool, optional Whether to write the expanded signal (e_d_signal) instead of the uniform s...
def _parse_positional_arguments(self, argv): """Parse the positional arguments part of an argument list. argv <list str>: List of arguments. Will be altered. """ for posarg in self.positional_args: posarg.parse(argv) if argv: if None in [p.narg...
Parse the positional arguments part of an argument list. argv <list str>: List of arguments. Will be altered.
Below is the the instruction that describes the task: ### Input: Parse the positional arguments part of an argument list. argv <list str>: List of arguments. Will be altered. ### Response: def _parse_positional_arguments(self, argv): """Parse the positional arguments part of an argument...
def ensure_timezone(func, argname, arg): """Argument preprocessor that converts the input into a tzinfo object. Examples -------- >>> from zipline.utils.preprocess import preprocess >>> @preprocess(tz=ensure_timezone) ... def foo(tz): ... return tz >>> foo('utc') <UTC> """ ...
Argument preprocessor that converts the input into a tzinfo object. Examples -------- >>> from zipline.utils.preprocess import preprocess >>> @preprocess(tz=ensure_timezone) ... def foo(tz): ... return tz >>> foo('utc') <UTC>
Below is the the instruction that describes the task: ### Input: Argument preprocessor that converts the input into a tzinfo object. Examples -------- >>> from zipline.utils.preprocess import preprocess >>> @preprocess(tz=ensure_timezone) ... def foo(tz): ... return tz >>> foo('utc'...
def add_index_argument(cls, group): """ Subclasses may call this to add an index argument. Args: group: arparse.ArgumentGroup, the extension argument group prefix: str, arguments have to be namespaced """ prefix = cls.argument_prefix group.add_ar...
Subclasses may call this to add an index argument. Args: group: arparse.ArgumentGroup, the extension argument group prefix: str, arguments have to be namespaced
Below is the the instruction that describes the task: ### Input: Subclasses may call this to add an index argument. Args: group: arparse.ArgumentGroup, the extension argument group prefix: str, arguments have to be namespaced ### Response: def add_index_argument(cls, group): ...
def goals_by_version(self): """Goals organized into three tuples by whether they are v1, ambiguous, or v2 goals (respectively). It's possible for a goal to be implemented with both v1 and v2, in which case a consumer should use the `--v1` and `--v2` global flags to disambiguate. """ v1, ambiguous, ...
Goals organized into three tuples by whether they are v1, ambiguous, or v2 goals (respectively). It's possible for a goal to be implemented with both v1 and v2, in which case a consumer should use the `--v1` and `--v2` global flags to disambiguate.
Below is the the instruction that describes the task: ### Input: Goals organized into three tuples by whether they are v1, ambiguous, or v2 goals (respectively). It's possible for a goal to be implemented with both v1 and v2, in which case a consumer should use the `--v1` and `--v2` global flags to disambi...
def display_data_item(self, data_item: DataItem, source_display_panel=None, source_data_item=None): """Display a new data item and gives it keyboard focus. Uses existing display if it is already displayed. .. versionadded:: 1.0 Status: Provisional Scriptable: Yes """ fo...
Display a new data item and gives it keyboard focus. Uses existing display if it is already displayed. .. versionadded:: 1.0 Status: Provisional Scriptable: Yes
Below is the the instruction that describes the task: ### Input: Display a new data item and gives it keyboard focus. Uses existing display if it is already displayed. .. versionadded:: 1.0 Status: Provisional Scriptable: Yes ### Response: def display_data_item(self, data_item: DataItem, ...
def configure_dot_code(self, info): """ Handles display of the dot code in a text editor. """ if not info.initialized: return self.dot_code = str(self.model) retval = self.edit_traits( parent = info.ui.control, kind = "livemodal",...
Handles display of the dot code in a text editor.
Below is the the instruction that describes the task: ### Input: Handles display of the dot code in a text editor. ### Response: def configure_dot_code(self, info): """ Handles display of the dot code in a text editor. """ if not info.initialized: return self.dot_code =...
def output_barplot(df, figformat, path, title=None, palette=None): """Create barplots based on number of reads and total sum of nucleotides sequenced.""" logging.info("Nanoplotter: Creating barplots for number of reads and total throughput.") read_count = Plot(path=path + "NanoComp_number_of_reads." + figfo...
Create barplots based on number of reads and total sum of nucleotides sequenced.
Below is the the instruction that describes the task: ### Input: Create barplots based on number of reads and total sum of nucleotides sequenced. ### Response: def output_barplot(df, figformat, path, title=None, palette=None): """Create barplots based on number of reads and total sum of nucleotides sequenced."...
def indexOf(a, b): "Return the first index of b in a." for i, j in enumerate(a): if j == b: return i else: raise ValueError('sequence.index(x): x not in sequence')
Return the first index of b in a.
Below is the the instruction that describes the task: ### Input: Return the first index of b in a. ### Response: def indexOf(a, b): "Return the first index of b in a." for i, j in enumerate(a): if j == b: return i else: raise ValueError('sequence.index(x): x not in sequence'...
def _set_maps(self, v, load=False): """ Setter method for maps, mapped from YANG variable /rbridge_id/maps (container) If this variable is read-only (config: false) in the source YANG file, then _set_maps is considered as a private method. Backends looking to populate this variable should do so ...
Setter method for maps, mapped from YANG variable /rbridge_id/maps (container) If this variable is read-only (config: false) in the source YANG file, then _set_maps is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_maps() directly.
Below is the the instruction that describes the task: ### Input: Setter method for maps, mapped from YANG variable /rbridge_id/maps (container) If this variable is read-only (config: false) in the source YANG file, then _set_maps is considered as a private method. Backends looking to populate this varia...
def received(self): """ Combined :class:`~charms.reactive.endpoints.JSONUnitDataView` of the data of all units in this list, with automatic JSON decoding. """ if not hasattr(self, '_data'): # NB: units are reversed so that lowest numbered unit takes precedence ...
Combined :class:`~charms.reactive.endpoints.JSONUnitDataView` of the data of all units in this list, with automatic JSON decoding.
Below is the the instruction that describes the task: ### Input: Combined :class:`~charms.reactive.endpoints.JSONUnitDataView` of the data of all units in this list, with automatic JSON decoding. ### Response: def received(self): """ Combined :class:`~charms.reactive.endpoints.JSONUnitDataV...
def keep_only_digits(s): r''' local helper to just keep digits ''' fs = '' for c in s: if c.isdigit(): fs += c return int(fs)
r''' local helper to just keep digits
Below is the the instruction that describes the task: ### Input: r''' local helper to just keep digits ### Response: def keep_only_digits(s): r''' local helper to just keep digits ''' fs = '' for c in s: if c.isdigit(): fs += c return int(fs)
def createZone(self, zone, zoneFile=None, callback=None, errback=None, **kwargs): """ Create a new zone, and return an associated high level Zone object. Several optional keyword arguments are available to configure the SOA record. If zoneFile is specified, up...
Create a new zone, and return an associated high level Zone object. Several optional keyword arguments are available to configure the SOA record. If zoneFile is specified, upload the specific zone definition file to populate the zone with. :param str zone: zone name, like 'exam...
Below is the the instruction that describes the task: ### Input: Create a new zone, and return an associated high level Zone object. Several optional keyword arguments are available to configure the SOA record. If zoneFile is specified, upload the specific zone definition file to po...
def setPenColor(self, color): """ Sets the pen for this node. :param color <QColor> || None """ color = QColor(color) if self._palette is None: self._palette = XNodePalette(self._scenePalette) self._palette.setColor(self._pal...
Sets the pen for this node. :param color <QColor> || None
Below is the the instruction that describes the task: ### Input: Sets the pen for this node. :param color <QColor> || None ### Response: def setPenColor(self, color): """ Sets the pen for this node. :param color <QColor> || None """ ...
def _get_taxids(self, taxids=None): """Return user-specified taxids or taxids in self.taxid2asscs""" taxid_keys = set(self.taxid2asscs.keys()) return taxid_keys if taxids is None else set(taxids).intersection(taxid_keys)
Return user-specified taxids or taxids in self.taxid2asscs
Below is the the instruction that describes the task: ### Input: Return user-specified taxids or taxids in self.taxid2asscs ### Response: def _get_taxids(self, taxids=None): """Return user-specified taxids or taxids in self.taxid2asscs""" taxid_keys = set(self.taxid2asscs.keys()) return tax...
def _get_dbid2goids(associations): """Return gene2go data for user-specified taxids.""" id2gos = cx.defaultdict(set) for ntd in associations: id2gos[ntd.DB_ID].add(ntd.GO_ID) return dict(id2gos)
Return gene2go data for user-specified taxids.
Below is the the instruction that describes the task: ### Input: Return gene2go data for user-specified taxids. ### Response: def _get_dbid2goids(associations): """Return gene2go data for user-specified taxids.""" id2gos = cx.defaultdict(set) for ntd in associations: id2gos[ntd....
def add_var_arg(self,arg_index): """ Add a command to the submit file to allow variable (macro) arguments to be passed to the executable. """ try: self.__var_args[arg_index] except IndexError: if arg_index != self.__arg_index: raise CondorDAGJobError, "mismatch between job an...
Add a command to the submit file to allow variable (macro) arguments to be passed to the executable.
Below is the the instruction that describes the task: ### Input: Add a command to the submit file to allow variable (macro) arguments to be passed to the executable. ### Response: def add_var_arg(self,arg_index): """ Add a command to the submit file to allow variable (macro) arguments to be passed ...
def instruction_in_grid(self, instruction): """Returns an `InstructionInGrid` object for the `instruction`""" row_position = self._rows_in_grid[instruction.row].xy x = instruction.index_of_first_consumed_mesh_in_row position = Point(row_position.x + x, row_position.y) return Inst...
Returns an `InstructionInGrid` object for the `instruction`
Below is the the instruction that describes the task: ### Input: Returns an `InstructionInGrid` object for the `instruction` ### Response: def instruction_in_grid(self, instruction): """Returns an `InstructionInGrid` object for the `instruction`""" row_position = self._rows_in_grid[instruction.row]...
def from_properties(cls, angle, axis, invert, translation): """Initialize a transformation based on the properties""" rot = Rotation.from_properties(angle, axis, invert) return Complete(rot.r, translation)
Initialize a transformation based on the properties
Below is the the instruction that describes the task: ### Input: Initialize a transformation based on the properties ### Response: def from_properties(cls, angle, axis, invert, translation): """Initialize a transformation based on the properties""" rot = Rotation.from_properties(angle, axis, invert...
def datetime_utc_to_local(utc): """ An ugly hack to convert naive :std:`datetime.datetime` object containing UTC time to a naive :std:`datetime.datetime` object with local time. It seems standard Python 2.3 library doesn't provide any better way to do that. """ # pylint: disable-msg=C0103 ...
An ugly hack to convert naive :std:`datetime.datetime` object containing UTC time to a naive :std:`datetime.datetime` object with local time. It seems standard Python 2.3 library doesn't provide any better way to do that.
Below is the the instruction that describes the task: ### Input: An ugly hack to convert naive :std:`datetime.datetime` object containing UTC time to a naive :std:`datetime.datetime` object with local time. It seems standard Python 2.3 library doesn't provide any better way to do that. ### Response: de...
def _translate_cond(self, c): #pylint:disable=no-self-use """ Checks whether this condition can be supported by FastMemory." """ if isinstance(c, claripy.ast.Base) and not c.singlevalued: raise SimFastMemoryError("size not supported") if c is None: return ...
Checks whether this condition can be supported by FastMemory."
Below is the the instruction that describes the task: ### Input: Checks whether this condition can be supported by FastMemory." ### Response: def _translate_cond(self, c): #pylint:disable=no-self-use """ Checks whether this condition can be supported by FastMemory." """ if isinstanc...
def represented_args(args, separator=" "): """ Args: args (list | tuple | None): Arguments to represent separator (str | unicode): Separator to use Returns: (str): Quoted as needed textual representation """ result = [] if args: for text in args: resu...
Args: args (list | tuple | None): Arguments to represent separator (str | unicode): Separator to use Returns: (str): Quoted as needed textual representation
Below is the the instruction that describes the task: ### Input: Args: args (list | tuple | None): Arguments to represent separator (str | unicode): Separator to use Returns: (str): Quoted as needed textual representation ### Response: def represented_args(args, separator=" "): """...
def get_function(pkgpath): """Take a full path to a python method or class, for example mypkg.subpkg.method and return the method or class (after importing the required packages) """ # Extract the module and function name from pkgpath elems = pkgpath.split('.') if len(elems) <= 1: ra...
Take a full path to a python method or class, for example mypkg.subpkg.method and return the method or class (after importing the required packages)
Below is the the instruction that describes the task: ### Input: Take a full path to a python method or class, for example mypkg.subpkg.method and return the method or class (after importing the required packages) ### Response: def get_function(pkgpath): """Take a full path to a python method or class,...
def _learner_distributed(learn:Learner, cuda_id:int, cache_dir:PathOrStr='tmp'): "Put `learn` on distributed training with `cuda_id`." learn.callbacks.append(DistributedTrainer(learn, cuda_id)) learn.callbacks.append(DistributedRecorder(learn, cuda_id, cache_dir)) return learn
Put `learn` on distributed training with `cuda_id`.
Below is the the instruction that describes the task: ### Input: Put `learn` on distributed training with `cuda_id`. ### Response: def _learner_distributed(learn:Learner, cuda_id:int, cache_dir:PathOrStr='tmp'): "Put `learn` on distributed training with `cuda_id`." learn.callbacks.append(DistributedTrainer...
def class_method(cls, f): """Decorator which dynamically binds class methods to the model for later use.""" setattr(cls, f.__name__, classmethod(f)) return f
Decorator which dynamically binds class methods to the model for later use.
Below is the the instruction that describes the task: ### Input: Decorator which dynamically binds class methods to the model for later use. ### Response: def class_method(cls, f): """Decorator which dynamically binds class methods to the model for later use.""" setattr(cls, f.__name__, classmethod...
def encrypt(self, plaintext, encoder=encoding.RawEncoder): """ Encrypts the plaintext message using a random-generated ephemeral keypair and returns a "composed ciphertext", containing both the public part of the keypair and the ciphertext proper, encoded with the encoder. ...
Encrypts the plaintext message using a random-generated ephemeral keypair and returns a "composed ciphertext", containing both the public part of the keypair and the ciphertext proper, encoded with the encoder. The private part of the ephemeral key-pair will be scrubbed before r...
Below is the the instruction that describes the task: ### Input: Encrypts the plaintext message using a random-generated ephemeral keypair and returns a "composed ciphertext", containing both the public part of the keypair and the ciphertext proper, encoded with the encoder. The pri...
def _uncheck_descendant(self, item): """Uncheck the boxes of item's descendant.""" children = self.get_children(item) for iid in children: self.change_state(iid, "unchecked") self._uncheck_descendant(iid)
Uncheck the boxes of item's descendant.
Below is the the instruction that describes the task: ### Input: Uncheck the boxes of item's descendant. ### Response: def _uncheck_descendant(self, item): """Uncheck the boxes of item's descendant.""" children = self.get_children(item) for iid in children: self.change_state(iid...
def get_next_section_start_line(self, data): """Get the starting line number of next section. It will return -1 if no section was found. The section is a section key (e.g. 'Parameters:') then the content :param data: a list of strings containing the docstring's lines :re...
Get the starting line number of next section. It will return -1 if no section was found. The section is a section key (e.g. 'Parameters:') then the content :param data: a list of strings containing the docstring's lines :returns: the index of next section else -1
Below is the the instruction that describes the task: ### Input: Get the starting line number of next section. It will return -1 if no section was found. The section is a section key (e.g. 'Parameters:') then the content :param data: a list of strings containing the docstring's line...
def clean(input, suffix, stat="pmode1", maxiter=15, sigrej=2.0, lower=None, upper=None, binwidth=0.3, mask1=None, mask2=None, dqbits=None, rpt_clean=0, atol=0.01, clobber=False, verbose=True): r"""Remove horizontal stripes from ACS WFC post-SM4 data. Parameters ---------- ...
r"""Remove horizontal stripes from ACS WFC post-SM4 data. Parameters ---------- input : str or list of str Input filenames in one of these formats: * a Python list of filenames * a partial filename with wildcards ('\*flt.fits') * filename of an ASN table ('j1234...
Below is the the instruction that describes the task: ### Input: r"""Remove horizontal stripes from ACS WFC post-SM4 data. Parameters ---------- input : str or list of str Input filenames in one of these formats: * a Python list of filenames * a partial filename with wi...
def connect_entry_signals(): """ Connect all the signals on Entry model. """ post_save.connect( ping_directories_handler, sender=Entry, dispatch_uid=ENTRY_PS_PING_DIRECTORIES) post_save.connect( ping_external_urls_handler, sender=Entry, dispatch_uid=ENTRY_PS_PING_EXTE...
Connect all the signals on Entry model.
Below is the the instruction that describes the task: ### Input: Connect all the signals on Entry model. ### Response: def connect_entry_signals(): """ Connect all the signals on Entry model. """ post_save.connect( ping_directories_handler, sender=Entry, dispatch_uid=ENTRY_PS_PING_D...
def version_binary(self): ''' Return version number which is stored in binary format. Returns: str: <major 0-255>.<minior 0-255>.<build 0-65535> or None if not found ''' # Under MSI 'Version' is a 'REG_DWORD' which then sets other registry # values like Displ...
Return version number which is stored in binary format. Returns: str: <major 0-255>.<minior 0-255>.<build 0-65535> or None if not found
Below is the the instruction that describes the task: ### Input: Return version number which is stored in binary format. Returns: str: <major 0-255>.<minior 0-255>.<build 0-65535> or None if not found ### Response: def version_binary(self): ''' Return version number which is st...
def preprocess_input(features, target, train_config, preprocess_output_dir, model_type): """Perform some transformations after reading in the input tensors. Args: features: dict of feature_name to tensor target: tensor train_config: our training config object preprocess_output_...
Perform some transformations after reading in the input tensors. Args: features: dict of feature_name to tensor target: tensor train_config: our training config object preprocess_output_dir: folder should contain the vocab files. model_type: the tf model type. Raises: ValueError: if wrong ...
Below is the the instruction that describes the task: ### Input: Perform some transformations after reading in the input tensors. Args: features: dict of feature_name to tensor target: tensor train_config: our training config object preprocess_output_dir: folder should contain the vocab files. ...
def apply_dependencies(self): """Creates dependencies links between elements. :return: None """ self.hosts.apply_dependencies() self.services.apply_dependencies(self.hosts)
Creates dependencies links between elements. :return: None
Below is the the instruction that describes the task: ### Input: Creates dependencies links between elements. :return: None ### Response: def apply_dependencies(self): """Creates dependencies links between elements. :return: None """ self.hosts.apply_dependencies() ...
def entries(self, start = None, end = None): '''Retrieves entries from all people/tasks logged to this project. Can be filtered based on time by specifying start/end datetimes.''' if not start: start = self.earliest_record if not end: end = self.latest_record ...
Retrieves entries from all people/tasks logged to this project. Can be filtered based on time by specifying start/end datetimes.
Below is the the instruction that describes the task: ### Input: Retrieves entries from all people/tasks logged to this project. Can be filtered based on time by specifying start/end datetimes. ### Response: def entries(self, start = None, end = None): '''Retrieves entries from all people/tasks lo...
def load(self, service_name, api_version=None, cached=True): """ Loads the desired JSON for a service. (uncached) This will fall back through all the ``data_dirs`` provided to the constructor, returning the **first** one it finds. :param service_name: The name of the desired se...
Loads the desired JSON for a service. (uncached) This will fall back through all the ``data_dirs`` provided to the constructor, returning the **first** one it finds. :param service_name: The name of the desired service :type service_name: string :param api_version: (Optional) ...
Below is the the instruction that describes the task: ### Input: Loads the desired JSON for a service. (uncached) This will fall back through all the ``data_dirs`` provided to the constructor, returning the **first** one it finds. :param service_name: The name of the desired service ...
def get(self): """Get specific information about this hub.""" output = helm("get", self.release) if output.returncode != 0: print("Something went wrong!") print(output.stderr) else: print(output.stdout)
Get specific information about this hub.
Below is the the instruction that describes the task: ### Input: Get specific information about this hub. ### Response: def get(self): """Get specific information about this hub.""" output = helm("get", self.release) if output.returncode != 0: print("Something went wrong!") ...
def get_file(self, file_hash, save_file_at): """ Get the scan results for a file. Even if you do not have a Private Mass API key that you can use, you can still download files from the VirusTotal storage making use of your VirusTotal Intelligence quota, i.e. programmatic downloads will ...
Get the scan results for a file. Even if you do not have a Private Mass API key that you can use, you can still download files from the VirusTotal storage making use of your VirusTotal Intelligence quota, i.e. programmatic downloads will also deduct quota. :param file_hash: You may use...
Below is the the instruction that describes the task: ### Input: Get the scan results for a file. Even if you do not have a Private Mass API key that you can use, you can still download files from the VirusTotal storage making use of your VirusTotal Intelligence quota, i.e. programmatic downloads w...
def process_token(self, kind, string, start, end, line): """ Process a single token. """ if self.current_block.is_comment: if kind == tokenize.COMMENT: self.current_block.add(string, start, end, line) else: self.new_noncomment(start[0], end...
Process a single token.
Below is the the instruction that describes the task: ### Input: Process a single token. ### Response: def process_token(self, kind, string, start, end, line): """ Process a single token. """ if self.current_block.is_comment: if kind == tokenize.COMMENT: self.cur...
def _set_formatter(self): """ Inspects config and sets the name of the formatter to either "json" or "text" as instance attr. If not present in config, default is "text" """ if hasattr(self._config, "formatter") and self._config.formatter == "json": self._formatter = ...
Inspects config and sets the name of the formatter to either "json" or "text" as instance attr. If not present in config, default is "text"
Below is the the instruction that describes the task: ### Input: Inspects config and sets the name of the formatter to either "json" or "text" as instance attr. If not present in config, default is "text" ### Response: def _set_formatter(self): """ Inspects config and sets the name of the f...
def replace_tax_rate_by_id(cls, tax_rate_id, tax_rate, **kwargs): """Replace TaxRate Replace all attributes of TaxRate This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.replace_tax_rate_by_id(ta...
Replace TaxRate Replace all attributes of TaxRate This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.replace_tax_rate_by_id(tax_rate_id, tax_rate, async=True) >>> result = thread.get() :...
Below is the the instruction that describes the task: ### Input: Replace TaxRate Replace all attributes of TaxRate This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.replace_tax_rate_by_id(tax_rate_i...
def param_to_array(*param): """ Convert an arbitrary number of parameters to :class:ndarray class objects. This is for converting parameter objects to numpy arrays, when using scipy.weave.inline routine. In scipy.weave.blitz there is no automatic array detection (even when the array inherits from :...
Convert an arbitrary number of parameters to :class:ndarray class objects. This is for converting parameter objects to numpy arrays, when using scipy.weave.inline routine. In scipy.weave.blitz there is no automatic array detection (even when the array inherits from :class:ndarray)
Below is the the instruction that describes the task: ### Input: Convert an arbitrary number of parameters to :class:ndarray class objects. This is for converting parameter objects to numpy arrays, when using scipy.weave.inline routine. In scipy.weave.blitz there is no automatic array detection (even w...
def partition_all(s, sep): """ Uses str.partition() to split every occurrence of sep in s. The returned list does not contain empty strings. If sep is a list, all separators are evaluated. :param s: The string to split. :param sep: A separator string or a list of separator strings. :return: A l...
Uses str.partition() to split every occurrence of sep in s. The returned list does not contain empty strings. If sep is a list, all separators are evaluated. :param s: The string to split. :param sep: A separator string or a list of separator strings. :return: A list of parts split by sep
Below is the the instruction that describes the task: ### Input: Uses str.partition() to split every occurrence of sep in s. The returned list does not contain empty strings. If sep is a list, all separators are evaluated. :param s: The string to split. :param sep: A separator string or a list of separ...
def fail(self, err='MockupDB query failure', *args, **kwargs): """Reply to a query with the QueryFailure flag and an '$err' key. Returns True so it is suitable as an `~MockupDB.autoresponds` handler. """ kwargs.setdefault('flags', 0) kwargs['flags'] |= REPLY_FLAGS['QueryFailure'...
Reply to a query with the QueryFailure flag and an '$err' key. Returns True so it is suitable as an `~MockupDB.autoresponds` handler.
Below is the the instruction that describes the task: ### Input: Reply to a query with the QueryFailure flag and an '$err' key. Returns True so it is suitable as an `~MockupDB.autoresponds` handler. ### Response: def fail(self, err='MockupDB query failure', *args, **kwargs): """Reply to a query wi...
def get_level_nodes(self, level): """! @brief Traverses CF-tree to obtain nodes at the specified level. @param[in] level (uint): CF-tree level from that nodes should be returned. @return (list) List of CF-nodes that are located on the specified level of the CF-tre...
! @brief Traverses CF-tree to obtain nodes at the specified level. @param[in] level (uint): CF-tree level from that nodes should be returned. @return (list) List of CF-nodes that are located on the specified level of the CF-tree.
Below is the the instruction that describes the task: ### Input: ! @brief Traverses CF-tree to obtain nodes at the specified level. @param[in] level (uint): CF-tree level from that nodes should be returned. @return (list) List of CF-nodes that are located on the specif...
def dropSpans(spans, text): """ Drop from text the blocks identified in :param spans:, possibly nested. """ spans.sort() res = '' offset = 0 for s, e in spans: if offset <= s: # handle nesting if offset < s: res += text[offset:s] offse...
Drop from text the blocks identified in :param spans:, possibly nested.
Below is the the instruction that describes the task: ### Input: Drop from text the blocks identified in :param spans:, possibly nested. ### Response: def dropSpans(spans, text): """ Drop from text the blocks identified in :param spans:, possibly nested. """ spans.sort() res = '' offset = 0...
def linear_rescale(image, in_range=(0, 1), out_range=(1, 255)): """ Linear rescaling. Attributes ---------- image : numpy ndarray Image array to rescale. in_range : list, int, optional, (default: [0,1]) Image min/max value to rescale. out_range : list, int, optional, (defaul...
Linear rescaling. Attributes ---------- image : numpy ndarray Image array to rescale. in_range : list, int, optional, (default: [0,1]) Image min/max value to rescale. out_range : list, int, optional, (default: [1,255]) output min/max bounds to rescale to. Returns --...
Below is the the instruction that describes the task: ### Input: Linear rescaling. Attributes ---------- image : numpy ndarray Image array to rescale. in_range : list, int, optional, (default: [0,1]) Image min/max value to rescale. out_range : list, int, optional, (default: [1,2...
def _run_setup_py(self, args, echo=True, echo2=True, ff=''): """Run setup.py with monkey-patched setuptools. The patch forces setuptools to use the file-finder 'ff'. If 'ff' is the empty string, the patch is not applied. 'args' is the list of arguments that should be passed to ...
Run setup.py with monkey-patched setuptools. The patch forces setuptools to use the file-finder 'ff'. If 'ff' is the empty string, the patch is not applied. 'args' is the list of arguments that should be passed to setup.py.
Below is the the instruction that describes the task: ### Input: Run setup.py with monkey-patched setuptools. The patch forces setuptools to use the file-finder 'ff'. If 'ff' is the empty string, the patch is not applied. 'args' is the list of arguments that should be passed to set...
def find_gui_and_backend(gui=None): """Given a gui string return the gui and mpl backend. Parameters ---------- gui : str Can be one of ('tk','gtk','wx','qt','qt4','inline'). Returns ------- A tuple of (gui, backend) where backend is one of ('TkAgg','GTKAgg', 'WXAgg','Qt4Agg','...
Given a gui string return the gui and mpl backend. Parameters ---------- gui : str Can be one of ('tk','gtk','wx','qt','qt4','inline'). Returns ------- A tuple of (gui, backend) where backend is one of ('TkAgg','GTKAgg', 'WXAgg','Qt4Agg','module://IPython.zmq.pylab.backend_inline')...
Below is the the instruction that describes the task: ### Input: Given a gui string return the gui and mpl backend. Parameters ---------- gui : str Can be one of ('tk','gtk','wx','qt','qt4','inline'). Returns ------- A tuple of (gui, backend) where backend is one of ('TkAgg','GTKAg...
def config_stdio(self, log_configurations: Optional[List[LogConfiguration]] = None, default_level=logging.INFO) -> None: """ Configure the stdio `StreamHandler` levels on the specified loggers. If no log configurations are specified then the `default_level` will be applied to all handlers. ...
Configure the stdio `StreamHandler` levels on the specified loggers. If no log configurations are specified then the `default_level` will be applied to all handlers. Args: log_configurations: a list of (component name, log level) tuples default_level: logging level to apply when...
Below is the the instruction that describes the task: ### Input: Configure the stdio `StreamHandler` levels on the specified loggers. If no log configurations are specified then the `default_level` will be applied to all handlers. Args: log_configurations: a list of (component name, log...
def fingerprint(txt): """ takes a string and truncates to standard form for data matching. Based on the spec at OpenRefine https://github.com/OpenRefine/OpenRefine/wiki/Clustering-In-Depth#fingerprint - remove leading and trailing whitespace - change all characters to their lowercase representation - remo...
takes a string and truncates to standard form for data matching. Based on the spec at OpenRefine https://github.com/OpenRefine/OpenRefine/wiki/Clustering-In-Depth#fingerprint - remove leading and trailing whitespace - change all characters to their lowercase representation - remove all punctuation and control...
Below is the the instruction that describes the task: ### Input: takes a string and truncates to standard form for data matching. Based on the spec at OpenRefine https://github.com/OpenRefine/OpenRefine/wiki/Clustering-In-Depth#fingerprint - remove leading and trailing whitespace - change all characters to ...
def takeAt( self, index ): """ Removes the widget from the rollout at the inputed index. :param index | <int> :return <QWidget> || None """ layout = self.widget().layout() item = layout.takeAt(index) if ( not item ): ...
Removes the widget from the rollout at the inputed index. :param index | <int> :return <QWidget> || None
Below is the the instruction that describes the task: ### Input: Removes the widget from the rollout at the inputed index. :param index | <int> :return <QWidget> || None ### Response: def takeAt( self, index ): """ Removes the widget from the rollout at th...
def declone_3rad(data, sample): """ 3rad uses random adapters to identify pcr duplicates. We will remove pcr dupes here. Basically append the radom adapter to each sequence, do a regular old vsearch derep, then trim off the adapter, and push it down the pipeline. This will remove all identical s...
3rad uses random adapters to identify pcr duplicates. We will remove pcr dupes here. Basically append the radom adapter to each sequence, do a regular old vsearch derep, then trim off the adapter, and push it down the pipeline. This will remove all identical seqs with identical random i5 adapters.
Below is the the instruction that describes the task: ### Input: 3rad uses random adapters to identify pcr duplicates. We will remove pcr dupes here. Basically append the radom adapter to each sequence, do a regular old vsearch derep, then trim off the adapter, and push it down the pipeline. This will ...
def add_paragraph(self, text='', style=None): """ Return a paragraph newly added to the end of the content in this cell. If present, *text* is added to the paragraph in a single run. If specified, the paragraph style *style* is applied. If *style* is not specified or is |None|, t...
Return a paragraph newly added to the end of the content in this cell. If present, *text* is added to the paragraph in a single run. If specified, the paragraph style *style* is applied. If *style* is not specified or is |None|, the result is as though the 'Normal' style was applied. Not...
Below is the the instruction that describes the task: ### Input: Return a paragraph newly added to the end of the content in this cell. If present, *text* is added to the paragraph in a single run. If specified, the paragraph style *style* is applied. If *style* is not specified or is |None|...
def base_geodetic_crs(self): """The :class:`GeodeticCRS` on which this projection is based.""" base = self.element.find(GML_NS + 'baseGeodeticCRS') href = base.attrib[XLINK_NS + 'href'] return get(href)
The :class:`GeodeticCRS` on which this projection is based.
Below is the the instruction that describes the task: ### Input: The :class:`GeodeticCRS` on which this projection is based. ### Response: def base_geodetic_crs(self): """The :class:`GeodeticCRS` on which this projection is based.""" base = self.element.find(GML_NS + 'baseGeodeticCRS') href...
def match(self, text, noprefix=False): """Matches date/datetime string against date patterns and returns pattern and parsed date if matched. It's not indeded for common usage, since if successful it returns date as array of numbers and pattern that matched this date :param text: ...
Matches date/datetime string against date patterns and returns pattern and parsed date if matched. It's not indeded for common usage, since if successful it returns date as array of numbers and pattern that matched this date :param text: Any human readable string :type date_...
Below is the the instruction that describes the task: ### Input: Matches date/datetime string against date patterns and returns pattern and parsed date if matched. It's not indeded for common usage, since if successful it returns date as array of numbers and pattern that matched this date :...
def _set_config(config): """Set gl configuration""" pyglet_config = pyglet.gl.Config() pyglet_config.red_size = config['red_size'] pyglet_config.green_size = config['green_size'] pyglet_config.blue_size = config['blue_size'] pyglet_config.alpha_size = config['alpha_size'] pyglet_config.acc...
Set gl configuration
Below is the the instruction that describes the task: ### Input: Set gl configuration ### Response: def _set_config(config): """Set gl configuration""" pyglet_config = pyglet.gl.Config() pyglet_config.red_size = config['red_size'] pyglet_config.green_size = config['green_size'] pyglet_config.b...
def get(self, request, *args, **kwargs): """ redirect user to captive page with the social auth token in the querystring (which will allow the captive page to send the token to freeradius) """ if not request.GET.get('cp'): return HttpResponse(_('missing cp GET...
redirect user to captive page with the social auth token in the querystring (which will allow the captive page to send the token to freeradius)
Below is the the instruction that describes the task: ### Input: redirect user to captive page with the social auth token in the querystring (which will allow the captive page to send the token to freeradius) ### Response: def get(self, request, *args, **kwargs): """ redirect user t...
def _parse_hostname(self): """Parses the global config and returns the hostname value Returns: dict: The configured value for hostname. The returned dict object is intended to be merged into the resource dict """ value = 'localhost' match = re.search...
Parses the global config and returns the hostname value Returns: dict: The configured value for hostname. The returned dict object is intended to be merged into the resource dict
Below is the the instruction that describes the task: ### Input: Parses the global config and returns the hostname value Returns: dict: The configured value for hostname. The returned dict object is intended to be merged into the resource dict ### Response: def _parse_hostname...
def comment_set(self): """ Get the comments that have been submitted for the chat """ ct = ContentType.objects.get_for_model(self.__class__) qs = Comment.objects.filter( content_type=ct, object_pk=self.pk) qs = qs.exclude(is_removed=True) qs = qs.o...
Get the comments that have been submitted for the chat
Below is the the instruction that describes the task: ### Input: Get the comments that have been submitted for the chat ### Response: def comment_set(self): """ Get the comments that have been submitted for the chat """ ct = ContentType.objects.get_for_model(self.__class__) qs = Com...
def detail_poi(self, **kwargs): """Obtain detailed info of a given POI. Args: family (str): Family code of the POI (3 chars). lang (str): Language code (*es* or *en*). id (int): Optional, ID of the POI to query. Passing value -1 will result in informa...
Obtain detailed info of a given POI. Args: family (str): Family code of the POI (3 chars). lang (str): Language code (*es* or *en*). id (int): Optional, ID of the POI to query. Passing value -1 will result in information from all POIs. Returns: ...
Below is the the instruction that describes the task: ### Input: Obtain detailed info of a given POI. Args: family (str): Family code of the POI (3 chars). lang (str): Language code (*es* or *en*). id (int): Optional, ID of the POI to query. Passing value -1 will ...
def cited_names_from_aux_file(stream): """Parse a LaTeX ".aux" file and generate a list of names cited according to LaTeX ``\\citation`` commands. Repeated names are generated only once. The argument should be a opened I/O stream. """ cited = set() for line in stream: if not line.start...
Parse a LaTeX ".aux" file and generate a list of names cited according to LaTeX ``\\citation`` commands. Repeated names are generated only once. The argument should be a opened I/O stream.
Below is the the instruction that describes the task: ### Input: Parse a LaTeX ".aux" file and generate a list of names cited according to LaTeX ``\\citation`` commands. Repeated names are generated only once. The argument should be a opened I/O stream. ### Response: def cited_names_from_aux_file(stream): ...
def title(self, value): """ Setter for **self.__title** attribute. :param value: Attribute value. :type value: unicode """ if value is not None: assert type(value) is unicode, "'{0}' attribute: '{1}' type is not 'unicode'!".format( "title", v...
Setter for **self.__title** attribute. :param value: Attribute value. :type value: unicode
Below is the the instruction that describes the task: ### Input: Setter for **self.__title** attribute. :param value: Attribute value. :type value: unicode ### Response: def title(self, value): """ Setter for **self.__title** attribute. :param value: Attribute value. ...
def _handle_keypad_message(self, data): """ Handle keypad messages. :param data: keypad message to parse :type data: string :returns: :py:class:`~alarmdecoder.messages.Message` """ msg = Message(data) if self._internal_address_mask & msg.mask > 0: ...
Handle keypad messages. :param data: keypad message to parse :type data: string :returns: :py:class:`~alarmdecoder.messages.Message`
Below is the the instruction that describes the task: ### Input: Handle keypad messages. :param data: keypad message to parse :type data: string :returns: :py:class:`~alarmdecoder.messages.Message` ### Response: def _handle_keypad_message(self, data): """ Handle keypad mes...
def _clear_strobes(self): """ Resets the "enable" and "load" output streams to all 0. """ #reset some stuff self['SEQ']['GLOBAL_SHIFT_EN'].setall(False) self['SEQ']['GLOBAL_CTR_LD'].setall(False) self['SEQ']['GLOBAL_DAC_LD'].setall(False) self['SEQ']['PIX...
Resets the "enable" and "load" output streams to all 0.
Below is the the instruction that describes the task: ### Input: Resets the "enable" and "load" output streams to all 0. ### Response: def _clear_strobes(self): """ Resets the "enable" and "load" output streams to all 0. """ #reset some stuff self['SEQ']['GLOBAL_SHIFT_EN']....
def pick_deep(pick_dct, dct): """ Implementation of pick that recurses. This tests the same keys at every level of dict and in lists :param pick_dct: Deep dict matching some portion of dct. :param dct: Dct to filter. Any key matching pick_dct pass through. It doesn't matter what the pick_dct value i...
Implementation of pick that recurses. This tests the same keys at every level of dict and in lists :param pick_dct: Deep dict matching some portion of dct. :param dct: Dct to filter. Any key matching pick_dct pass through. It doesn't matter what the pick_dct value is as long as the key exists. Arrays also p...
Below is the the instruction that describes the task: ### Input: Implementation of pick that recurses. This tests the same keys at every level of dict and in lists :param pick_dct: Deep dict matching some portion of dct. :param dct: Dct to filter. Any key matching pick_dct pass through. It doesn't matter wh...
def get_language_model(n_tok, emb_sz, n_hid, n_layers, pad_token, dropout=0.4, dropouth=0.3, dropouti=0.5, dropoute=0.1, wdrop=0.5, tie_weights=True, qrnn=False, bias=False): """Returns a SequentialRNN model. A RNN_Encoder layer is instantiated using the parameters provided. This is follo...
Returns a SequentialRNN model. A RNN_Encoder layer is instantiated using the parameters provided. This is followed by the creation of a LinearDecoder layer. Also by default (i.e. tie_weights = True), the embedding matrix used in the RNN_Encoder is used to instantiate the weights for the LinearDecode...
Below is the the instruction that describes the task: ### Input: Returns a SequentialRNN model. A RNN_Encoder layer is instantiated using the parameters provided. This is followed by the creation of a LinearDecoder layer. Also by default (i.e. tie_weights = True), the embedding matrix used in the RNN...
def _displayFeatures(self, fig, features, minX, maxX, offsetAdjuster): """ Add the given C{features} to the figure in C{fig}. @param fig: A matplotlib figure. @param features: A C{FeatureList} instance. @param minX: The smallest x coordinate. @param maxX: The largest x c...
Add the given C{features} to the figure in C{fig}. @param fig: A matplotlib figure. @param features: A C{FeatureList} instance. @param minX: The smallest x coordinate. @param maxX: The largest x coordinate. @param offsetAdjuster: a function for adjusting feature X axis offsets ...
Below is the the instruction that describes the task: ### Input: Add the given C{features} to the figure in C{fig}. @param fig: A matplotlib figure. @param features: A C{FeatureList} instance. @param minX: The smallest x coordinate. @param maxX: The largest x coordinate. @pa...
def p_generate(self, p): 'generate : GENERATE generate_items ENDGENERATE' p[0] = GenerateStatement(p[2], lineno=p.lineno(1)) p.set_lineno(0, p.lineno(1))
generate : GENERATE generate_items ENDGENERATE
Below is the the instruction that describes the task: ### Input: generate : GENERATE generate_items ENDGENERATE ### Response: def p_generate(self, p): 'generate : GENERATE generate_items ENDGENERATE' p[0] = GenerateStatement(p[2], lineno=p.lineno(1)) p.set_lineno(0, p.lineno(1))
def filter(self, limit=None, to=None, category=None): """ Returns the events that match the filters Args: limit (int, optional): the max length of the events to return (Default value = None) to (str, optional): only events that have been sent or received by 'to' (Default val...
Returns the events that match the filters Args: limit (int, optional): the max length of the events to return (Default value = None) to (str, optional): only events that have been sent or received by 'to' (Default value = None) category (str, optional): only events belonging to th...
Below is the the instruction that describes the task: ### Input: Returns the events that match the filters Args: limit (int, optional): the max length of the events to return (Default value = None) to (str, optional): only events that have been sent or received by 'to' (Default value = ...
def get(protocol, subset, classes=CLASSES, variables=VARIABLES): '''Returns the data subset given a particular protocol Parameters protocol (string): one of the valid protocols supported by this interface subset (string): one of 'train' or 'test' classes (list of string): a list of strings containi...
Returns the data subset given a particular protocol Parameters protocol (string): one of the valid protocols supported by this interface subset (string): one of 'train' or 'test' classes (list of string): a list of strings containing the names of the classes from which you want to have the data...
Below is the the instruction that describes the task: ### Input: Returns the data subset given a particular protocol Parameters protocol (string): one of the valid protocols supported by this interface subset (string): one of 'train' or 'test' classes (list of string): a list of strings containin...
def sliceit(iterable, lower=0, upper=None): """Apply a slice on input iterable. :param iterable: object which provides the method __getitem__ or __iter__. :param int lower: lower bound from where start to get items. :param int upper: upper bound from where finish to get items. :return: sliced objec...
Apply a slice on input iterable. :param iterable: object which provides the method __getitem__ or __iter__. :param int lower: lower bound from where start to get items. :param int upper: upper bound from where finish to get items. :return: sliced object of the same type of iterable if not dict, or spec...
Below is the the instruction that describes the task: ### Input: Apply a slice on input iterable. :param iterable: object which provides the method __getitem__ or __iter__. :param int lower: lower bound from where start to get items. :param int upper: upper bound from where finish to get items. :re...
def planck(wave, temp, wavelength=True): """The Planck radiation or Blackbody radiation as a function of wavelength or wavenumber. SI units. _planck(wave, temperature, wavelength=True) wave = Wavelength/wavenumber or a sequence of wavelengths/wavenumbers (m or m^-1) temp = Temperature (scalar) or a...
The Planck radiation or Blackbody radiation as a function of wavelength or wavenumber. SI units. _planck(wave, temperature, wavelength=True) wave = Wavelength/wavenumber or a sequence of wavelengths/wavenumbers (m or m^-1) temp = Temperature (scalar) or a sequence of temperatures (K) Output: Wave...
Below is the the instruction that describes the task: ### Input: The Planck radiation or Blackbody radiation as a function of wavelength or wavenumber. SI units. _planck(wave, temperature, wavelength=True) wave = Wavelength/wavenumber or a sequence of wavelengths/wavenumbers (m or m^-1) temp = Temp...
def post_gist(report_data, old_sha, new_sha): """Post the report to a GitHub Gist and return the URL of the gist.""" payload = { "description": ("Changes in OpenStack-Ansible between " "{0} and {1}".format(old_sha, new_sha)), "public": True, "files": { ...
Post the report to a GitHub Gist and return the URL of the gist.
Below is the the instruction that describes the task: ### Input: Post the report to a GitHub Gist and return the URL of the gist. ### Response: def post_gist(report_data, old_sha, new_sha): """Post the report to a GitHub Gist and return the URL of the gist.""" payload = { "description": ("Changes i...
def validate(repo, validator_name=None, filename=None, rulesfiles=None, args=[]): """ Validate the content of the files for consistency. Validators can look as deeply as needed into the files. dgit treats them all as black boxes. Parameters ...
Validate the content of the files for consistency. Validators can look as deeply as needed into the files. dgit treats them all as black boxes. Parameters ---------- repo: Repository object validator_name: Name of validator, if any. If none, then all validators specified in dgit.json will be i...
Below is the the instruction that describes the task: ### Input: Validate the content of the files for consistency. Validators can look as deeply as needed into the files. dgit treats them all as black boxes. Parameters ---------- repo: Repository object validator_name: Name of validator, ...
def get_long_description(): """Transform README.md into a usable long description. Replaces relative references to svg images to absolute https references. """ with open('README.md') as f: read_me = f.read() def replace_relative_with_absolute(match): svg_path = match.group(0)[1:-1...
Transform README.md into a usable long description. Replaces relative references to svg images to absolute https references.
Below is the the instruction that describes the task: ### Input: Transform README.md into a usable long description. Replaces relative references to svg images to absolute https references. ### Response: def get_long_description(): """Transform README.md into a usable long description. Replaces relat...
def _deduce_security(kwargs) -> nmcli.SECURITY_TYPES: """ Make sure that the security_type is known, or throw. """ # Security should be one of our valid strings sec_translation = { 'wpa-psk': nmcli.SECURITY_TYPES.WPA_PSK, 'none': nmcli.SECURITY_TYPES.NONE, 'wpa-eap': nmcli.SECURITY_T...
Make sure that the security_type is known, or throw.
Below is the the instruction that describes the task: ### Input: Make sure that the security_type is known, or throw. ### Response: def _deduce_security(kwargs) -> nmcli.SECURITY_TYPES: """ Make sure that the security_type is known, or throw. """ # Security should be one of our valid strings sec_transl...