code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def bind(self, family, type, proto=0): """Create (or recreate) the actual socket object.""" self.socket = sockets.Socket(family, type, proto) self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.socket.setblocking(0) #~ self.socket.setsockopt(socket.SOL_SOCKET, socket.TCP_NODE...
Create (or recreate) the actual socket object.
def ValidateLanguageCode(lang, column_name=None, problems=None): """ Validates a non-required language code value using the pybcp47 module: - if invalid adds InvalidValue error (if problems accumulator is provided) - distinguishes between 'not well-formed' and 'not valid' and adds error reasons accord...
Validates a non-required language code value using the pybcp47 module: - if invalid adds InvalidValue error (if problems accumulator is provided) - distinguishes between 'not well-formed' and 'not valid' and adds error reasons accordingly - an empty language code is regarded as valid! Otherwise we mig...
def visit_ListComp(self, node: ast.ListComp) -> Any: """Compile the list comprehension as a function and call it.""" result = self._execute_comprehension(node=node) for generator in node.generators: self.visit(generator.iter) self.recomputed_values[node] = result re...
Compile the list comprehension as a function and call it.
def remover(self, id_perms): """Remove Administrative Permission from by the identifier. :param id_perms: Identifier of the Administrative Permission. Integer value and greater than zero. :return: None :raise InvalidParameterError: The identifier of Administrative Permission is null a...
Remove Administrative Permission from by the identifier. :param id_perms: Identifier of the Administrative Permission. Integer value and greater than zero. :return: None :raise InvalidParameterError: The identifier of Administrative Permission is null and invalid. :raise PermissaoAdmi...
def wait(self): """Blocks until the rate is met""" now = _monotonic() if now < self._ref: delay = max(0, self._ref - now) self.sleep_func(delay) self._update_ref()
Blocks until the rate is met
def update_file(url, filename): """Update the content of a single file.""" resp = urlopen(url) if resp.code != 200: raise Exception('GET {} failed.'.format(url)) with open(_get_package_path(filename), 'w') as fp: for l in resp: if not l.startswith(b'#'): fp.wr...
Update the content of a single file.
def CreateMuskingumKfacFile(in_drainage_line, river_id, length_id, slope_id, celerity, formula_type, in_connectivity_file, o...
r""" Creates the Kfac file for calibration. The improved methods using slope to generate values for Kfac were used here: Tavakoly, A. A., A. D. Snow, C. H. David, M. L. Follum, D. R. Maidment, and Z.-L. Yang, (2016) "Continental-Scale River Flow Modeling of the Mississippi River Basin Using Hi...
def plotConvergenceByObject(results, objectRange, featureRange, numTrials, linestyle='-'): """ Plots the convergence graph: iterations vs number of objects. Each curve shows the convergence for a given number of unique features. """ #################################################...
Plots the convergence graph: iterations vs number of objects. Each curve shows the convergence for a given number of unique features.
def evaluate(self, batchsize): """Evaluate how well the classifier is doing. Return mean loss and mean accuracy""" sum_loss, sum_accuracy = 0, 0 for i in range(0, self.testsize, batchsize): x = Variable(self.x_test[i: i + batchsize]) y = Variable(self.y_test[i: i + batchs...
Evaluate how well the classifier is doing. Return mean loss and mean accuracy
def ttfautohint(in_file, out_file, args=None, **kwargs): """Thin wrapper around the ttfautohint command line tool. Can take in command line arguments directly as a string, or spelled out as Python keyword arguments. """ arg_list = ["ttfautohint"] file_args = [in_file, out_file] if args is...
Thin wrapper around the ttfautohint command line tool. Can take in command line arguments directly as a string, or spelled out as Python keyword arguments.
def get_query_string(environ): """Returns the `QUERY_STRING` from the WSGI environment. This also takes care about the WSGI decoding dance on Python 3 environments as a native string. The string returned will be restricted to ASCII characters. .. versionadded:: 0.9 :param environ: the WSGI e...
Returns the `QUERY_STRING` from the WSGI environment. This also takes care about the WSGI decoding dance on Python 3 environments as a native string. The string returned will be restricted to ASCII characters. .. versionadded:: 0.9 :param environ: the WSGI environment object to get the query str...
def block(self, tofile="block.dat"): ''' 获取证券板块信息 :param tofile: :return: pd.dataFrame or None ''' with self.client.connect(*self.bestip): data = self.client.get_and_parse_block_info(tofile) return self.client.to_df(data)
获取证券板块信息 :param tofile: :return: pd.dataFrame or None
def do_lisp(self, subcmd, opts, folder=""): """${cmd_name}: list messages in the specified folder in JSON format ${cmd_usage} """ client = MdClient(self.maildir, filesystem=self.filesystem) client.lisp( foldername=folder, stream=self.stdout, ...
${cmd_name}: list messages in the specified folder in JSON format ${cmd_usage}
def createDataport(self, auth, desc, defer=False): """Create a dataport resource. "format" and "retention" are required { "format": "float" | "integer" | "string", "meta": string = "", "name": string = "", "preprocess": list ...
Create a dataport resource. "format" and "retention" are required { "format": "float" | "integer" | "string", "meta": string = "", "name": string = "", "preprocess": list = [], "public": boolean = false, ...
def ReleaseObject(self, identifier): """Releases a cached object based on the identifier. This method decrements the cache value reference count. Args: identifier (str): VFS object identifier. Raises: KeyError: if the VFS object is not found in the cache. RuntimeError: if the cache ...
Releases a cached object based on the identifier. This method decrements the cache value reference count. Args: identifier (str): VFS object identifier. Raises: KeyError: if the VFS object is not found in the cache. RuntimeError: if the cache value is missing.
def apply(self, im): """ Apply an n-dimensional displacement by shifting an image or volume. Parameters ---------- im : ndarray The image or volume to shift """ from scipy.ndimage.interpolation import shift return shift(im, map(lambda x: -x, s...
Apply an n-dimensional displacement by shifting an image or volume. Parameters ---------- im : ndarray The image or volume to shift
def masked(name, runtime=False, root=None): ''' .. versionadded:: 2015.8.0 .. versionchanged:: 2015.8.5 The return data for this function has changed. If the service is masked, the return value will now be the output of the ``systemctl is-enabled`` command (so that a persistent mask ...
.. versionadded:: 2015.8.0 .. versionchanged:: 2015.8.5 The return data for this function has changed. If the service is masked, the return value will now be the output of the ``systemctl is-enabled`` command (so that a persistent mask can be distinguished from a runtime mask). If th...
def list_users(self, limit=None, marker=None): """Returns a list of the names of all users for this instance.""" return self._user_manager.list(limit=limit, marker=marker)
Returns a list of the names of all users for this instance.
def build_payment_parameters(amount: Money, client_ref: str) -> PaymentParameters: """ Builds the parameters needed to present the user with a datatrans payment form. :param amount: The amount and currency we want the user to pay :param client_ref: A unique reference for this payment :return: The p...
Builds the parameters needed to present the user with a datatrans payment form. :param amount: The amount and currency we want the user to pay :param client_ref: A unique reference for this payment :return: The parameters needed to display the datatrans form
def gaussian(df, width=0.3, downshift=-1.8, prefix=None): """ Impute missing values by drawing from a normal distribution :param df: :param width: Scale factor for the imputed distribution relative to the standard deviation of measured values. Can be a single number or list of one per column. :para...
Impute missing values by drawing from a normal distribution :param df: :param width: Scale factor for the imputed distribution relative to the standard deviation of measured values. Can be a single number or list of one per column. :param downshift: Shift the imputed values down, in units of std. dev. Can ...
def get_stock_quote(self, code_list): """ 获取订阅股票报价的实时数据,有订阅要求限制。 对于异步推送,参见StockQuoteHandlerBase :param code_list: 股票代码列表,必须确保code_list中的股票均订阅成功后才能够执行 :return: (ret, data) ret == RET_OK 返回pd dataframe数据,数据列格式如下 ret != RET_OK 返回错误字符串 ...
获取订阅股票报价的实时数据,有订阅要求限制。 对于异步推送,参见StockQuoteHandlerBase :param code_list: 股票代码列表,必须确保code_list中的股票均订阅成功后才能够执行 :return: (ret, data) ret == RET_OK 返回pd dataframe数据,数据列格式如下 ret != RET_OK 返回错误字符串 ===================== =========== ===============...
def _partition_data(datavol, roivol, roivalue, maskvol=None, zeroe=True): """ Extracts the values in `datavol` that are in the ROI with value `roivalue` in `roivol`. The ROI can be masked by `maskvol`. Parameters ---------- datavol: numpy.ndarray 4D timeseries volume or a 3D volume to be pa...
Extracts the values in `datavol` that are in the ROI with value `roivalue` in `roivol`. The ROI can be masked by `maskvol`. Parameters ---------- datavol: numpy.ndarray 4D timeseries volume or a 3D volume to be partitioned roivol: numpy.ndarray 3D ROIs volume roivalue: int or ...
def generate(self, model_len=None, model_width=None): """Generates a CNN. Args: model_len: An integer. Number of convolutional layers. model_width: An integer. Number of filters for the convolutional layers. Returns: An instance of the class Graph. Represents ...
Generates a CNN. Args: model_len: An integer. Number of convolutional layers. model_width: An integer. Number of filters for the convolutional layers. Returns: An instance of the class Graph. Represents the neural architecture graph of the generated model.
def _load_params(params, logger=logging): """Given a str as a path to the .params file or a pair of params, returns two dictionaries representing arg_params and aux_params. """ if isinstance(params, str): cur_path = os.path.dirname(os.path.realpath(__file__)) param_file_path = os.path.jo...
Given a str as a path to the .params file or a pair of params, returns two dictionaries representing arg_params and aux_params.
def namedb_query_execute( cur, query, values, abort=True): """ Execute a query. If it fails, abort. Retry with timeouts on lock DO NOT CALL THIS DIRECTLY. """ return db_query_execute(cur, query, values, abort=abort)
Execute a query. If it fails, abort. Retry with timeouts on lock DO NOT CALL THIS DIRECTLY.
def reference(self, refobj, taskfileinfo): """Reference the given taskfileinfo into the scene and return the created reference node The created reference node will be used on :meth:`RefobjInterface.set_reference` to set the reference on a reftrack node. Do not call :meth:`RefobjInterfac...
Reference the given taskfileinfo into the scene and return the created reference node The created reference node will be used on :meth:`RefobjInterface.set_reference` to set the reference on a reftrack node. Do not call :meth:`RefobjInterface.set_reference` yourself. This will also cre...
def export_osm_file(self): """Generate OpenStreetMap element tree from ``Osm``.""" osm = create_elem('osm', {'generator': self.generator, 'version': self.version}) osm.extend(obj.toosm() for obj in self) return etree.ElementTree(osm)
Generate OpenStreetMap element tree from ``Osm``.
def read_committed_file(gitref, filename): """Retrieve the content of a file in an old commit and returns it. Ketword Arguments: :gitref: (str) -- full reference of the git commit :filename: (str) -- name (full path) of the file Returns: str -- content of the file """ repo ...
Retrieve the content of a file in an old commit and returns it. Ketword Arguments: :gitref: (str) -- full reference of the git commit :filename: (str) -- name (full path) of the file Returns: str -- content of the file
def calc_fc_size(img_height, img_width): '''Calculates shape of data after encoding. Parameters ---------- img_height : int Height of input image. img_width : int Width of input image. Returns ------- encoded_shape : tuple(int) Gives back 3-tuple with new dims. ...
Calculates shape of data after encoding. Parameters ---------- img_height : int Height of input image. img_width : int Width of input image. Returns ------- encoded_shape : tuple(int) Gives back 3-tuple with new dims.
def set_path(self, data, path, value): """ Sets the given key in the given dict object to the given value. If the given path is nested, child dicts are created as appropriate. Accepts either a dot-delimited path or an array of path elements as the `path` variable. """ ...
Sets the given key in the given dict object to the given value. If the given path is nested, child dicts are created as appropriate. Accepts either a dot-delimited path or an array of path elements as the `path` variable.
def get_instance(cls, state): """:rtype: UserStorageHandler""" if cls.instance is None: cls.instance = UserStorageHandler(state) return cls.instance
:rtype: UserStorageHandler
def set_scale_alpha_from_selection(self): ''' Set scale marker to alpha for selected layer. ''' # 1. Look up selected layer. selection = self.treeview_layers.get_selection() list_store, selected_iter = selection.get_selected() # 2. Set adjustment to current alph...
Set scale marker to alpha for selected layer.
def get(self, field, value=None): """Gets user input for given field and checks if it is valid. If input is invalid, it will ask the user to enter it again. Defaults values to empty or :value:. It does not check validity of parent index. It can only be tested further down the r...
Gets user input for given field and checks if it is valid. If input is invalid, it will ask the user to enter it again. Defaults values to empty or :value:. It does not check validity of parent index. It can only be tested further down the road, so for now accept anything. :fi...
def _writeFASTA(self, i, image): """ Write a FASTA file containing the set of reads that hit a sequence. @param i: The number of the image in self._images. @param image: A member of self._images. @return: A C{str}, either 'fasta' or 'fastq' indicating the format of t...
Write a FASTA file containing the set of reads that hit a sequence. @param i: The number of the image in self._images. @param image: A member of self._images. @return: A C{str}, either 'fasta' or 'fastq' indicating the format of the reads in C{self._titlesAlignments}.
def write_totals(self, file_path='', date=str(datetime.date.today()), organization='N/A', members=0, teams=0): """ Updates the total.csv file with current data. """ total_exists = os.path.isfile(file_path) with open(file_path, 'a') as out_total: if not total_...
Updates the total.csv file with current data.
def tiles(self) -> np.array: """An array of this consoles tile data. This acts as a combination of the `ch`, `fg`, and `bg` attributes. Colors include an alpha channel but how alpha works is currently undefined. Example:: >>> con = tcod.console.Console(10, 2, order=...
An array of this consoles tile data. This acts as a combination of the `ch`, `fg`, and `bg` attributes. Colors include an alpha channel but how alpha works is currently undefined. Example:: >>> con = tcod.console.Console(10, 2, order="F") >>> con.tiles[0, 0] = (...
def Convert(self, metadata, checkresult, token=None): """Converts a single CheckResult. Args: metadata: ExportedMetadata to be used for conversion. checkresult: CheckResult to be converted. token: Security token. Yields: Resulting ExportedCheckResult. Empty list is a valid result a...
Converts a single CheckResult. Args: metadata: ExportedMetadata to be used for conversion. checkresult: CheckResult to be converted. token: Security token. Yields: Resulting ExportedCheckResult. Empty list is a valid result and means that conversion wasn't possible.
def select_waveform_generator(approximant): """Returns the single-IFO generator for the approximant. Parameters ---------- approximant : str Name of waveform approximant. Valid names can be found using ``pycbc.waveform`` methods. Returns ------- generator : (PyCBC generator...
Returns the single-IFO generator for the approximant. Parameters ---------- approximant : str Name of waveform approximant. Valid names can be found using ``pycbc.waveform`` methods. Returns ------- generator : (PyCBC generator instance) A waveform generator object. ...
def lat(self): """Latitude of grid centers (degrees North) :getter: Returns the points of axis ``'lat'`` if availible in the process's domains. :type: array :raises: :exc:`ValueError` if no ``'lat'`` axis can be found. """ ...
Latitude of grid centers (degrees North) :getter: Returns the points of axis ``'lat'`` if availible in the process's domains. :type: array :raises: :exc:`ValueError` if no ``'lat'`` axis can be found.
def show(self, temp_file_name = 'ani.mp4', **kwargs): """ ## Arguments: - 'args' and 'kwargs' will be passed to 'self.save()' """ ## [NOTE] Make this method as a method of base class. ## [NOTE] This should be modified to prevent erasing other existing file with ...
## Arguments: - 'args' and 'kwargs' will be passed to 'self.save()'
def angle(self, deg=False): """Return the angle of a complex Timeseries Args: deg (bool, optional): Return angle in degrees if True, radians if False (default). Returns: angle (Timeseries): The counterclockwise angle from the positive real axis on ...
Return the angle of a complex Timeseries Args: deg (bool, optional): Return angle in degrees if True, radians if False (default). Returns: angle (Timeseries): The counterclockwise angle from the positive real axis on the complex plane, with dtype...
def get_proficiency_form_for_create(self, objective_id, resource_id, proficiency_record_types): """Gets the proficiency form for creating new proficiencies. A new form should be requested for each create transaction. arg: objective_id (osid.id.Id): the ``Id`` of the ``Object...
Gets the proficiency form for creating new proficiencies. A new form should be requested for each create transaction. arg: objective_id (osid.id.Id): the ``Id`` of the ``Objective`` arg: resource_id (osid.id.Id): the ``Id`` of the ``Resource`` arg: proficiency_...
def AddFXrefRead(self, method, classobj, field): """ Add a Field Read to this class :param method: :param classobj: :param field: :return: """ if field not in self._fields: self._fields[field] = FieldClassAnalysis(field) self._fields[f...
Add a Field Read to this class :param method: :param classobj: :param field: :return:
def get_book_progress(self, asin): """Returns the progress data available for a book. NOTE: A summary of the two progress formats can be found in the docstring for `ReadingProgress`. Args: asin: The asin of the book to be queried. Returns: A `ReadingProgress` instance corresponding to...
Returns the progress data available for a book. NOTE: A summary of the two progress formats can be found in the docstring for `ReadingProgress`. Args: asin: The asin of the book to be queried. Returns: A `ReadingProgress` instance corresponding to the book associated with `asin`.
def collapse(cls, holomap, ranges=None, mode='data'): """ Given a map of Overlays, apply all applicable compositors. """ # No potential compositors if cls.definitions == []: return holomap # Apply compositors clone = holomap.clone(shared_data=False) ...
Given a map of Overlays, apply all applicable compositors.
def claim_invitations(user): """Claims any pending invitations for the given user's email address.""" # See if there are any build invitations present for the user with this # email address. If so, replace all those invitations with the real user. invitation_user_id = '%s:%s' % ( models.User.EMA...
Claims any pending invitations for the given user's email address.
def get_ascii(self, show_internal=True, compact=False, attributes=None): """ Returns a string containing an ascii drawing of the tree. Parameters: ----------- show_internal: include internal edge names. compact: use exactly one line per ...
Returns a string containing an ascii drawing of the tree. Parameters: ----------- show_internal: include internal edge names. compact: use exactly one line per tip. attributes: A list of node attributes to shown in the ASCII represe...
def log2_lut(v): """ See `this algo <https://graphics.stanford.edu/~seander/bithacks.html#IntegerLogLookup>`__ for computing the log2 of a 32 bit integer using a look up table Parameters ---------- v : int 32 bit integer Returns ------- """ res = np.zeros(v.shape, dtyp...
See `this algo <https://graphics.stanford.edu/~seander/bithacks.html#IntegerLogLookup>`__ for computing the log2 of a 32 bit integer using a look up table Parameters ---------- v : int 32 bit integer Returns -------
def main(): """ Main function of this example. """ parser = argparse.ArgumentParser() parser.add_argument( '--digest', default="md5", help="Digest to use", choices=sorted( getattr(hashlib, 'algorithms', None) or hashlib.algorithms_available)) parser.add_argument( ...
Main function of this example.
def open_ioc(fn): """ Opens an IOC file, or XML string. Returns the root element, top level indicator element, and parameters element. If the IOC or string fails to parse, an IOCParseError is raised. This is a helper function used by __init__. :param fn: This is a pat...
Opens an IOC file, or XML string. Returns the root element, top level indicator element, and parameters element. If the IOC or string fails to parse, an IOCParseError is raised. This is a helper function used by __init__. :param fn: This is a path to a file to open, or a string conta...
def poll(self): """ Poll agents for data """ start_time = time.time() for agent in self.agents: for collect in agent.reader: # don't crush if trash or traceback came from agent to stdout if not collect: return 0 ...
Poll agents for data
def convert_to_python(self, xmlrpc=None): """ Extracts a value for the field from an XML-RPC response. """ if xmlrpc: return xmlrpc.get(self.name, self.default) elif self.default: return self.default else: return None
Extracts a value for the field from an XML-RPC response.
def rsdl(self): """Compute fixed point residual in Fourier domain.""" diff = self.Xf - self.Yfprv return sl.rfl2norm2(diff, self.X.shape, axis=self.cri.axisN)
Compute fixed point residual in Fourier domain.
def names2dnsrepr(x): """ Take as input a list of DNS names or a single DNS name and encode it in DNS format (with possible compression) If a string that is already a DNS name in DNS format is passed, it is returned unmodified. Result is a string. !!! At the moment, compression is not implement...
Take as input a list of DNS names or a single DNS name and encode it in DNS format (with possible compression) If a string that is already a DNS name in DNS format is passed, it is returned unmodified. Result is a string. !!! At the moment, compression is not implemented !!!
def config_md5(self, source_config): """Compute MD5 hash of file.""" file_contents = source_config + "\n" # Cisco IOS automatically adds this file_contents = file_contents.encode("UTF-8") return hashlib.md5(file_contents).hexdigest()
Compute MD5 hash of file.
def _get_kind(self, limit): """ Get a set of dominant file types. The files must contribute at least C{limit}% to the item's total size. """ histo = self.fetch("custom_kind") if histo: # Parse histogram from cached field histo = [i.split("%_") for i i...
Get a set of dominant file types. The files must contribute at least C{limit}% to the item's total size.
def tracker_index(): """Get tracker overview.""" stats = server.stats if stats and stats.snapshots: stats.annotate() timeseries = [] for cls in stats.tracked_classes: series = [] for snapshot in stats.snapshots: series.append(snapshot.classes.g...
Get tracker overview.
def configure_gateway( cls, launch_jvm: bool = True, gateway: Union[GatewayParameters, Dict[str, Any]] = None, callback_server: Union[CallbackServerParameters, Dict[str, Any]] = False, javaopts: Iterable[str] = (), classpath: Iterable[str] = ''): """ Confi...
Configure a Py4J gateway. :param launch_jvm: ``True`` to spawn a Java Virtual Machine in a subprocess and connect to it, ``False`` to connect to an existing Py4J enabled JVM :param gateway: either a :class:`~py4j.java_gateway.GatewayParameters` object or a dictionary of keyword ...
def avl_join_dir_recursive(t1, t2, node, direction): """ Recursive version of join_left and join_right TODO: make this iterative using a stack """ other_side = 1 - direction if _DEBUG_JOIN_DIR: print('--JOIN DIR (dir=%r) --' % (direction,)) ascii_tree(t1, 't1') ascii_tree...
Recursive version of join_left and join_right TODO: make this iterative using a stack
def popen(fn, *args, **kwargs) -> subprocess.Popen: """ Please ensure you're not killing the process before it had started properly :param fn: :param args: :param kwargs: :return: """ args = popen_encode(fn, *args, **kwargs) logging.getLogger(__name__).debug('Start %s', args) ...
Please ensure you're not killing the process before it had started properly :param fn: :param args: :param kwargs: :return:
def get_tunnel_info_input_filter_type_filter_by_dip_dest_ip(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_tunnel_info = ET.Element("get_tunnel_info") config = get_tunnel_info input = ET.SubElement(get_tunnel_info, "input") filter_ty...
Auto Generated Code
def delete(self): """ Deletes the resource. """ return self._client._delete( self.__class__.base_url( self.sys['space'].id, self.sys['id'], environment_id=self._environment_id ) )
Deletes the resource.
def bsinPoints(pb, pe): """Return Bezier control points, when pb and pe stand for a full period from (0,0) to (2*pi, 0), respectively, in the user's coordinate system. The returned points can be used to draw up to four Bezier curves for the complete phase of the sine function graph (0 to 360 degrees). ...
Return Bezier control points, when pb and pe stand for a full period from (0,0) to (2*pi, 0), respectively, in the user's coordinate system. The returned points can be used to draw up to four Bezier curves for the complete phase of the sine function graph (0 to 360 degrees).
def _import_submodules( __all__, __path__, __name__, include=None, exclude=None, include_private_modules=False, require__all__=True, recursive=True): """ Import all available submodules, all objects defined in the `__all__` lists of those submodules, and extend `__all__` with the imported ob...
Import all available submodules, all objects defined in the `__all__` lists of those submodules, and extend `__all__` with the imported objects. Args: __all__ (list): The list of public objects in the "root" module __path__ (str): The path where the ``__init__.py`` file for the "root" ...
def process_query(self): """Q.process_query() -- processes the user query, by tokenizing and stemming words. """ self.query = wt(self.query) self.processed_query = [] for word in self.query: if word not in self.stop_words and word not in self.punctuation: self.processed_query.append(self.stemmer.ste...
Q.process_query() -- processes the user query, by tokenizing and stemming words.
def destination(self, value): """ Set the destination of the message. :type value: tuple :param value: (ip, port) :raise AttributeError: if value is not a ip and a port. """ if value is not None and (not isinstance(value, tuple) or len(value)) != 2: r...
Set the destination of the message. :type value: tuple :param value: (ip, port) :raise AttributeError: if value is not a ip and a port.
def get_order(self, order_id): """Lookup an order based on the order id returned from one of the order functions. Parameters ---------- order_id : str The unique identifier for the order. Returns ------- order : Order The order ob...
Lookup an order based on the order id returned from one of the order functions. Parameters ---------- order_id : str The unique identifier for the order. Returns ------- order : Order The order object.
def put(self, url, data=None, verify=False, headers=None, proxies=None, timeout=60, **kwargs): """Sends a PUT request. Refactor from requests module :param url: URL for the new :class:`Request` object. :param data: (optional) Dictionary, bytes, or file-like object to sen...
Sends a PUT request. Refactor from requests module :param url: URL for the new :class:`Request` object. :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`. :param verify: (optional) if ``True``, the SSL cert will be verified. ...
def list_flavors(self, limit=None, marker=None): """Returns a list of all available Flavors.""" return self._flavor_manager.list(limit=limit, marker=marker)
Returns a list of all available Flavors.
def response(uri, method, res, token='', keyword='', content='', raw_flag=False): """Response of tonicdns_client request Arguments: uri: TonicDNS API URI method: TonicDNS API request method res: Response of against request to TonicDNS API token: Toni...
Response of tonicdns_client request Arguments: uri: TonicDNS API URI method: TonicDNS API request method res: Response of against request to TonicDNS API token: TonicDNS API token keyword: Processing keyword content: JSON data raw_flag: True...
def restart_listener(self, topics): '''Restart listener after configuration update. ''' if self.listener is not None: if self.listener.running: self.stop() self.__init__(topics=topics)
Restart listener after configuration update.
def is_valid_preview(preview): ''' Verifies that the preview is a valid filetype ''' if not preview: return False if mimetype(preview) not in [ExportMimeType.PNG, ExportMimeType.PDF]: return False return True
Verifies that the preview is a valid filetype
def delete_records(self, domain, name, record_type=None): """Deletes records by name. You can also add a record type, which will only delete records with the specified type/name combo. If no record type is specified, ALL records that have a matching name will be deleted. This is hapha...
Deletes records by name. You can also add a record type, which will only delete records with the specified type/name combo. If no record type is specified, ALL records that have a matching name will be deleted. This is haphazard functionality. I DO NOT recommend using this in Production cod...
def occurrences_after(self, after=None): """ It is often useful to know what the next occurrence is given a list of events. This function produces a generator that yields the the most recent occurrence after the date ``after`` from any of the events in ``self.events`` ""...
It is often useful to know what the next occurrence is given a list of events. This function produces a generator that yields the the most recent occurrence after the date ``after`` from any of the events in ``self.events``
def timer_expired(self): """ This method is invoked in context of the timer thread, so we cannot directly throw exceptions (we can, but they would be in the wrong thread), so instead we shut down the socket of the connection. When the timeout happens in early phases of the connec...
This method is invoked in context of the timer thread, so we cannot directly throw exceptions (we can, but they would be in the wrong thread), so instead we shut down the socket of the connection. When the timeout happens in early phases of the connection setup, there is no socket object...
def make_order_string(cls, order_specification): """ Converts the given order specification to a CQL order expression. """ registry = get_current_registry() visitor_cls = registry.getUtility(IOrderSpecificationVisitor, name=EXPRESSION_KIN...
Converts the given order specification to a CQL order expression.
def write_contents(self, table, reader): """Write the contents of `table` :Parameters: - `table`: an instance of a :py:class:`mysql2pgsql.lib.mysql_reader.MysqlReader.Table` object that represents the table to read/write. - `reader`: an instance of a :py:class:`mysql2pgsql.lib.mysql...
Write the contents of `table` :Parameters: - `table`: an instance of a :py:class:`mysql2pgsql.lib.mysql_reader.MysqlReader.Table` object that represents the table to read/write. - `reader`: an instance of a :py:class:`mysql2pgsql.lib.mysql_reader.MysqlReader` object that allows reading from...
def support_autoupload_param_hostip(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") support = ET.SubElement(config, "support", xmlns="urn:brocade.com:mgmt:brocade-ras") autoupload_param = ET.SubElement(support, "autoupload-param") hostip = ET.Sub...
Auto Generated Code
def get_template_by_name(name,**kwargs): """ Get a specific resource template, by name. """ try: tmpl_i = db.DBSession.query(Template).filter(Template.name == name).options(joinedload_all('templatetypes.typeattrs.default_dataset.metadata')).one() return tmpl_i except NoResultFoun...
Get a specific resource template, by name.
def request(self, path, method='GET', headers=None, **kwargs): """Perform a HTTP request. Given a relative Bugzilla URL path, an optional request method, and arguments suitable for requests.Request(), perform a HTTP request. """ headers = {} if headers is None else heade...
Perform a HTTP request. Given a relative Bugzilla URL path, an optional request method, and arguments suitable for requests.Request(), perform a HTTP request.
def gpg_interactive_input(self, sub_keys_number): """ processes series of inputs normally supplied on --edit-key but passed through stdin this ensures that no other --edit-key command is actually passing through. """ deselect_sub_key = "key 0\n" _input = self._main_key_comma...
processes series of inputs normally supplied on --edit-key but passed through stdin this ensures that no other --edit-key command is actually passing through.
def importobj(modpath, attrname): """imports a module, then resolves the attrname on it""" module = __import__(modpath, None, None, ['__doc__']) if not attrname: return module retval = module names = attrname.split(".") for x in names: retval = getattr(retval, x) return retv...
imports a module, then resolves the attrname on it
def _get_connection(self): """ Returns connection to sqlite db. Returns: connection to the sqlite db who stores mpr data. """ if getattr(self, '_connection', None): logger.debug('Connection to sqlite db already exists. Using existing one.') else: ...
Returns connection to sqlite db. Returns: connection to the sqlite db who stores mpr data.
def __wrap( self, method_name ): """ This method actually does the wrapping. When it's given a method to copy it returns that method with facilities to log the call so it can be repeated. :param str method_name: The name of the method precisely as it's called on the object to wr...
This method actually does the wrapping. When it's given a method to copy it returns that method with facilities to log the call so it can be repeated. :param str method_name: The name of the method precisely as it's called on the object to wrap. :rtype lambda function:
def check_input(prolog_file): ''' Check for illegal predicates (like reading/writing, opening sockets, etc). ''' if prolog_file == None: return for pred in illegal_predicates: if type(pred) == tuple: print_name = pred[1] pred = pred[0] else: ...
Check for illegal predicates (like reading/writing, opening sockets, etc).
def _learnPhase1(self, activeColumns, readOnly=False): """ Compute the learning active state given the predicted state and the bottom-up input. :param activeColumns list of active bottom-ups :param readOnly True if being called from backtracking logic. This tells us no...
Compute the learning active state given the predicted state and the bottom-up input. :param activeColumns list of active bottom-ups :param readOnly True if being called from backtracking logic. This tells us not to increment any segment duty cycles or ...
def purge_old_user_tasks(): """ Delete any UserTaskStatus and UserTaskArtifact records older than ``settings.USER_TASKS_MAX_AGE``. Intended to be run as a scheduled task. """ limit = now() - settings.USER_TASKS_MAX_AGE # UserTaskArtifacts will also be removed via deletion cascading UserTask...
Delete any UserTaskStatus and UserTaskArtifact records older than ``settings.USER_TASKS_MAX_AGE``. Intended to be run as a scheduled task.
def copy_ifcfg_file(source_interface, dest_interface): """Copies an existing ifcfg network script to another :param source_interface: String (e.g. 1) :param dest_interface: String (e.g. 0:0) :return: None :raises TypeError, OSError """ log = logging.getLogger(mod_logger + '.copy_ifcfg_file'...
Copies an existing ifcfg network script to another :param source_interface: String (e.g. 1) :param dest_interface: String (e.g. 0:0) :return: None :raises TypeError, OSError
def fig_intro(params, ana_params, T=[800, 1000], fraction=0.05, rasterized=False): '''set up plot for introduction''' ana_params.set_PLOS_2column_fig_style(ratio=0.5) #load spike as database networkSim = CachedNetwork(**params.networkSimParams) if analysis_params.bw: networkSim.colors =...
set up plot for introduction
def log_queries(recipe): """ Logs recipe instance SQL queries (actually, only time). """ logger.debug( '⚐ Badge %s: SQL queries time %.2f second(s)', recipe.slug, sum([float(q['time']) for q in connection.queries]))
Logs recipe instance SQL queries (actually, only time).
def move_part_instance(part_instance, target_parent, part_model, name=None, include_children=True): """ Move the `Part` instance to target parent and updates the properties based on the original part instance. .. versionadded:: 2.3 :param part_instance: `Part` object to be moved :type part_instanc...
Move the `Part` instance to target parent and updates the properties based on the original part instance. .. versionadded:: 2.3 :param part_instance: `Part` object to be moved :type part_instance: :class:`Part` :param part_model: `Part` object representing the model of part_instance :type part_mod...
def replace_free_shipping_promotion_by_id(cls, free_shipping_promotion_id, free_shipping_promotion, **kwargs): """Replace FreeShippingPromotion Replace all attributes of FreeShippingPromotion This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, ...
Replace FreeShippingPromotion Replace all attributes of FreeShippingPromotion This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.replace_free_shipping_promotion_by_id(free_shipping_promotion_id, free_shi...
def FindSolFile(shot=0, t=0, Dt=None, Mesh='Rough1', Deg=2, Deriv='D2N2', Sep=True, Pos=True, OutPath='/afs/ipp-garching.mpg.de/home/d/didiv/Python/tofu/src/Outputs_AUG/'): """ Identify the good Sol2D saved file in a given folder (OutPath), based on key ToFu criteria When trying to load a Sol2D object (i.e.: s...
Identify the good Sol2D saved file in a given folder (OutPath), based on key ToFu criteria When trying to load a Sol2D object (i.e.: solution of a tomographic inversion), it may be handy to provide the key parameters (shot, time, mesh name, degree of basis functions, regularisation functional) instead of copy-past...
def invert_inventory(inventory): """Return {item: binding} from {binding: item} Protect against items with additional metadata and items whose type is a number Returns: Dictionary of inverted inventory """ inverted = dict() for binding, items in inventory.iteritems(): for...
Return {item: binding} from {binding: item} Protect against items with additional metadata and items whose type is a number Returns: Dictionary of inverted inventory
def get_std_end_date(self): """ If the date is custom, return the end datetime with the format %Y-%m-%d %H:%M:%S. Else, returns "". """ _, second = self._val if second != datetime.max: return second.strftime("%Y-%m-%d %H:%M:%S") else: return ""
If the date is custom, return the end datetime with the format %Y-%m-%d %H:%M:%S. Else, returns "".
def stringify(req, resp): """ dumps all valid jsons This is the latest after hook """ if isinstance(resp.body, dict): try: resp.body = json.dumps(resp.body) except(nameError): resp.status = falcon.HTTP_500
dumps all valid jsons This is the latest after hook
def refresh(self): """Obtain a new access token.""" grant_type = "https://oauth.reddit.com/grants/installed_client" self._request_token(grant_type=grant_type, device_id=self._device_id)
Obtain a new access token.
def log_event(cls, event, text = None): """ Log lines of text associated with a debug event. @type event: L{Event} @param event: Event object. @type text: str @param text: (Optional) Text to log. If no text is provided the default is to show a description ...
Log lines of text associated with a debug event. @type event: L{Event} @param event: Event object. @type text: str @param text: (Optional) Text to log. If no text is provided the default is to show a description of the event itself. @rtype: str @return: ...
def memoize(max_cache_size=1000): """Python 2.4 compatible memoize decorator. It creates a cache that has a maximum size. If the cache exceeds the max, it is thrown out and a new one made. With such behavior, it is wise to set the cache just a little larger that the maximum expected need. Paramet...
Python 2.4 compatible memoize decorator. It creates a cache that has a maximum size. If the cache exceeds the max, it is thrown out and a new one made. With such behavior, it is wise to set the cache just a little larger that the maximum expected need. Parameters: max_cache_size - the size to w...
def eth_getTransactionByBlockNumberAndIndex(self, block=BLOCK_TAG_LATEST, index=0): """https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_gettransactionbyblocknumberandindex :param block: Block tag or number (optional) :type block: int or BLOCK_TA...
https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_gettransactionbyblocknumberandindex :param block: Block tag or number (optional) :type block: int or BLOCK_TAGS :param index: Index position (optional) :type index: int :return: transaction :rtype: dict or None