code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def group_by_day(self): """Return a dictionary of this collection's values grouped by each day of year. Key values are between 1-365. """ data_by_day = OrderedDict() for d in xrange(1, 366): data_by_day[d] = [] for v, dt in zip(self._values, self.datetimes): ...
Return a dictionary of this collection's values grouped by each day of year. Key values are between 1-365.
def form_valid(self, form): """ If form valid return response with action """ response = super(FormAjaxMixin, self).form_valid(form) if self.request.is_ajax(): return self.json_to_response() return response
If form valid return response with action
def proximal_translation(prox_factory, y): r"""Calculate the proximal of the translated function F(x - y). Parameters ---------- prox_factory : callable A factory function that, when called with a step size, returns the proximal operator of ``F``. y : Element in domain of ``F``. ...
r"""Calculate the proximal of the translated function F(x - y). Parameters ---------- prox_factory : callable A factory function that, when called with a step size, returns the proximal operator of ``F``. y : Element in domain of ``F``. Returns ------- prox_factory : functi...
def compile_less(input_file, output_file): """ Compile a LESS source file. Minifies the output in release mode. """ from .modules import less if not isinstance(input_file, str): raise RuntimeError('LESS compiler takes only a single input file.') return { 'dependencies_fn': less...
Compile a LESS source file. Minifies the output in release mode.
def drawNormal(N, mu=0.0, sigma=1.0, seed=0): ''' Generate arrays of normal draws. The mu and sigma inputs can be numbers or list-likes. If a number, output is a length N array of draws from the normal distribution with mean mu and standard deviation sigma. If a list, output is a length T list who...
Generate arrays of normal draws. The mu and sigma inputs can be numbers or list-likes. If a number, output is a length N array of draws from the normal distribution with mean mu and standard deviation sigma. If a list, output is a length T list whose t-th entry is a length N array with draws from the ...
def _repr_tty_(self) -> str: """Return a summary of this sample sheet in a TTY compatible codec.""" header_description = ['Sample_ID', 'Description'] header_samples = [ 'Sample_ID', 'Sample_Name', 'Library_ID', 'index', 'index2', ...
Return a summary of this sample sheet in a TTY compatible codec.
def _safe_timezone(obj): # type: (Union[str, int, float, _datetime.tzinfo]) -> _Timezone """ Creates a timezone instance from a string, Timezone, TimezoneInfo or integer offset. """ if isinstance(obj, _Timezone): return obj if obj is None or obj == "local": return local_time...
Creates a timezone instance from a string, Timezone, TimezoneInfo or integer offset.
def output_latex(self, filename_or_file_handle): """ Output the file to a latex document :param filename_or_file_handle: filename or already opened file handle to output to :return: """ if isinstance(filename_or_file_handle, basestring): file_handle = file(fi...
Output the file to a latex document :param filename_or_file_handle: filename or already opened file handle to output to :return:
def disconnect(): """Disconnect this worker from the raylet and object store.""" # Reset the list of cached remote functions and actors so that if more # remote functions or actors are defined and then connect is called again, # the remote functions will be exported. This is mostly relevant for the ...
Disconnect this worker from the raylet and object store.
def unregister(self, alias): """Unregisters a service instance. Stops a service and removes it from the manager. Args: alias: string, the alias of the service instance to unregister. """ if alias not in self._service_objects: raise Error(self._device, ...
Unregisters a service instance. Stops a service and removes it from the manager. Args: alias: string, the alias of the service instance to unregister.
def iter(self): """An iteration generator that allows the loop to modify the :class:`PatternSet` during the loop""" if self.patterns: patterns = list(self.patterns) for pattern in patterns: yield pattern
An iteration generator that allows the loop to modify the :class:`PatternSet` during the loop
def _path2uri(self, dirpath): ''' Convert directory path to uri ''' relpath = dirpath.replace(self.root_path, self.package_name) if relpath.startswith(os.path.sep): relpath = relpath[1:] return relpath.replace(os.path.sep, '.')
Convert directory path to uri
def write_biom(biomT, output_fp, fmt="hdf5", gzip=False): """ Write the BIOM table to a file. :type biomT: biom.table.Table :param biomT: A BIOM table containing the per-sample OTU counts and metadata to be written out to file. :type output_fp str :param output_fp: Path to the...
Write the BIOM table to a file. :type biomT: biom.table.Table :param biomT: A BIOM table containing the per-sample OTU counts and metadata to be written out to file. :type output_fp str :param output_fp: Path to the BIOM-format file that will be written. :type fmt: str :param ...
def PixelsHDU(model): ''' Construct the HDU containing the pixel-level light curve. ''' # Get mission cards cards = model._mission.HDUCards(model.meta, hdu=2) # Add EVEREST info cards = [] cards.append(('COMMENT', '************************')) cards.append(('COMMENT', '* EVERES...
Construct the HDU containing the pixel-level light curve.
def generate_hexagonal_lattice(maxv1, minv1, maxv2, minv2, mindist): """ This function generates a 2-dimensional lattice of points using a hexagonal lattice. Parameters ----------- maxv1 : float Largest value in the 1st dimension to cover minv1 : float Smallest value in the ...
This function generates a 2-dimensional lattice of points using a hexagonal lattice. Parameters ----------- maxv1 : float Largest value in the 1st dimension to cover minv1 : float Smallest value in the 1st dimension to cover maxv2 : float Largest value in the 2nd dimensi...
def change_password(self, previous_password, proposed_password): """ Change the User password """ self.check_token() response = self.client.change_password( PreviousPassword=previous_password, ProposedPassword=proposed_password, AccessToken=sel...
Change the User password
def split(self, fragment_height): """ Split an image into multiple fragments after fragment_height pixels :param fragment_height: height of fragment :return: list of PIL objects """ passes = int(math.ceil(self.height/fragment_height)) fragments = [] for n...
Split an image into multiple fragments after fragment_height pixels :param fragment_height: height of fragment :return: list of PIL objects
def create_html_link(urlbase, urlargd, link_label, linkattrd=None, escape_urlargd=True, escape_linkattrd=True, urlhash=None): """Creates a W3C compliant link. @param urlbase: base url (e.g. config.CFG_SITE_URL/search) @param urlargd: dictionary of parameters. (e.g. ...
Creates a W3C compliant link. @param urlbase: base url (e.g. config.CFG_SITE_URL/search) @param urlargd: dictionary of parameters. (e.g. p={'recid':3, 'of'='hb'}) @param link_label: text displayed in a browser (has to be already escaped) @param linkattrd: dictionary of attributes (e.g. a={'class': 'img'...
def refresh(self, refresh_binary=True): ''' Performs GET request and refreshes RDF information for resource. Args: None Returns: None ''' updated_self = self.repo.get_resource(self.uri) # if resource type of updated_self != self, raise exception if not isinstance(self, type(updated_self)): ...
Performs GET request and refreshes RDF information for resource. Args: None Returns: None
def command_runner(shell_command, force_rerun_flag, outfile_checker, cwd=None, silent=False): """Run a shell command with subprocess, with additional options to check if output file exists and printing stdout. Args: shell_command (str): Command as it would be formatted in the command-line (ie. "program...
Run a shell command with subprocess, with additional options to check if output file exists and printing stdout. Args: shell_command (str): Command as it would be formatted in the command-line (ie. "program -i test.in -o test.out"). force_rerun_flag: If the program should be rerun even if the outpu...
def _analyze(self, it): """Analyze a single morf or code unit. Returns an `Analysis` object. """ self._harvest_data() if not isinstance(it, CodeUnit): it = code_unit_factory(it, self.file_locator)[0] return Analysis(self, it)
Analyze a single morf or code unit. Returns an `Analysis` object.
def create_hparams(hparams_set, hparams_overrides_str="", data_dir=None, problem_name=None, hparams_path=None): """Create HParams with data_dir and problem hparams, if kwargs provided.""" hparams = registry.hparams(hparams_set) if hparams...
Create HParams with data_dir and problem hparams, if kwargs provided.
def print_success(msg, color=True): """ Print a success message. :param string msg: the message :param bool color: if ``True``, print with POSIX color """ if color and is_posix(): safe_print(u"%s[INFO] %s%s" % (ANSI_OK, msg, ANSI_END)) else: safe_print(u"[INFO] %s" % (msg))
Print a success message. :param string msg: the message :param bool color: if ``True``, print with POSIX color
def set_unit_spike_features(self, unit_id, feature_name, value): '''This function adds a unit features data set under the given features name to the given unit. Parameters ---------- unit_id: int The unit id for which the features will be set feature_name: st...
This function adds a unit features data set under the given features name to the given unit. Parameters ---------- unit_id: int The unit id for which the features will be set feature_name: str The name of the feature to be stored value ...
def _resolve_folder(project, parent_folder, folder_name): """ :param project: The project that the folder belongs to :type project: string :param parent_folder: Full path to the parent folder that contains folder_name :type parent_folder: string :param folder_name: Name ...
:param project: The project that the folder belongs to :type project: string :param parent_folder: Full path to the parent folder that contains folder_name :type parent_folder: string :param folder_name: Name of the folder :type folder_name: string :returns: The path to ...
def get_qubit_los(self, user_lo_config): """Embed default qubit LO frequencies from backend and format them to list object. If configured lo frequency is the same as default, this method returns `None`. Args: user_lo_config (LoConfig): A dictionary of LOs to format. Returns...
Embed default qubit LO frequencies from backend and format them to list object. If configured lo frequency is the same as default, this method returns `None`. Args: user_lo_config (LoConfig): A dictionary of LOs to format. Returns: list: A list of qubit LOs. Ra...
def get_field_errors(self, field): """ Return server side errors. Shall be overridden by derived forms to add their extra errors for AngularJS. """ identifier = format_html('{0}[\'{1}\']', self.form_name, field.name) errors = self.errors.get(field.html_name, []) r...
Return server side errors. Shall be overridden by derived forms to add their extra errors for AngularJS.
def notify_observers(self, joinpoint, post=False): """Notify observers with parameter calls and information about pre/post call. """ _observers = tuple(self.observers) for observer in _observers: observer.notify(joinpoint=joinpoint, post=post)
Notify observers with parameter calls and information about pre/post call.
def _renew_by(name, window=None): ''' Date before a certificate should be renewed :param name: Common Name of the certificate (DNS name of certificate) :param window: days before expiry date to renew :return datetime object of first renewal date ''' expiry = _expires(name) if window is ...
Date before a certificate should be renewed :param name: Common Name of the certificate (DNS name of certificate) :param window: days before expiry date to renew :return datetime object of first renewal date
def extract_path_arguments(path): """ Extracts a swagger path arguments from the given flask path. This /path/<parameter> extracts [{name: 'parameter'}] And this /<string(length=2):lang_code>/<string:id>/<float:probability> extracts: [ {name: 'lang_code', dataType: 'string'}, {name: 'id', dataType: 's...
Extracts a swagger path arguments from the given flask path. This /path/<parameter> extracts [{name: 'parameter'}] And this /<string(length=2):lang_code>/<string:id>/<float:probability> extracts: [ {name: 'lang_code', dataType: 'string'}, {name: 'id', dataType: 'string'} {name: 'probability', dataType...
def static(cls): r"""Converts the given class into a static one, by changing all the methods of it into static methods. Args: cls (class): The class to be converted. """ for attr in dir(cls): im_func = getattr(getattr(cls, attr), 'im_func', None) if im_func: setattr(cls, attr, staticmet...
r"""Converts the given class into a static one, by changing all the methods of it into static methods. Args: cls (class): The class to be converted.
def escape_newlines(s: str) -> str: """ Escapes CR, LF, and backslashes. Its counterpart is :func:`unescape_newlines`. ``s.encode("string_escape")`` and ``s.encode("unicode_escape")`` are alternatives, but they mess around with quotes, too (specifically, backslash-escaping single quotes). ...
Escapes CR, LF, and backslashes. Its counterpart is :func:`unescape_newlines`. ``s.encode("string_escape")`` and ``s.encode("unicode_escape")`` are alternatives, but they mess around with quotes, too (specifically, backslash-escaping single quotes).
def easter(year, method=EASTER_WESTERN): """ This method was ported from the work done by GM Arts, on top of the algorithm by Claus Tondering, which was based in part on the algorithm of Ouding (1940), as quoted in "Explanatory Supplement to the Astronomical Almanac", P. Kenneth Seidelmann, edi...
This method was ported from the work done by GM Arts, on top of the algorithm by Claus Tondering, which was based in part on the algorithm of Ouding (1940), as quoted in "Explanatory Supplement to the Astronomical Almanac", P. Kenneth Seidelmann, editor. This algorithm implements three different e...
def _validate(self, p): """ Recursively validates the pattern (p), ensuring it adheres to the proper key names and structure. """ if self._is_operator(p): for operator_or_filter in (p[1] if p[0] != '!' else [p[1]]): if p[0] == '^': self._va...
Recursively validates the pattern (p), ensuring it adheres to the proper key names and structure.
def trace(self, func): """Decorator to print out a function's arguments and return value.""" def wrapper(*args, **kwargs): # Print out the call to the function with its arguments. s = self.Stanza(self.indent) s.add([self.GREEN, func.__name__, self.NORMAL, '(']) ...
Decorator to print out a function's arguments and return value.
def create_session_entity_type( self, parent, session_entity_type, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): """ Creates a session entity type. Example: ...
Creates a session entity type. Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.SessionEntityTypesClient() >>> >>> parent = client.session_path('[PROJECT]', '[SESSION]') >>> >>> # TODO: Initialize ``session_enti...
def search_related_tags(self,series_search_text=None,tag_names=None,response_type=None,params=None): """ Function to request the related FRED tags for one or more FRED tags matching a series search. `<https://research.stlouisfed.org/docs/api/fred/series_search_related_tags.html>`_ :arg ...
Function to request the related FRED tags for one or more FRED tags matching a series search. `<https://research.stlouisfed.org/docs/api/fred/series_search_related_tags.html>`_ :arg str series_search_text: The words to match against economic data series. Required. :arg str tag_names: Tag names ...
def getIcon(self, glyph, isOpen, color=None): """ Returns a QIcon given a glyph name, open/closed state and color. The reslulting icon is cached so that it only needs to be rendered once. :param glyph: name of a registered glyph (e.g. 'file', 'array') :param isOpen: boolean...
Returns a QIcon given a glyph name, open/closed state and color. The reslulting icon is cached so that it only needs to be rendered once. :param glyph: name of a registered glyph (e.g. 'file', 'array') :param isOpen: boolean that indicates if the RTI is open or closed. ...
def database_list_projects(object_id, input_params={}, always_retry=True, **kwargs): """ Invokes the /database-xxxx/listProjects API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Cloning#API-method%3A-%2Fclass-xxxx%2FlistProjects """ return DXHTTPRequest('/%s/listPr...
Invokes the /database-xxxx/listProjects API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Cloning#API-method%3A-%2Fclass-xxxx%2FlistProjects
def ncpos(string, chars, start): """ Find the first occurrence in a string of a character NOT belonging to a collection of characters, starting at a specified location searching forward. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ncpos_c.html :param string: Any character string. ...
Find the first occurrence in a string of a character NOT belonging to a collection of characters, starting at a specified location searching forward. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ncpos_c.html :param string: Any character string. :type string: str :param chars: A coll...
def _update_fps(self, event): """Update the fps after every window""" self._frame_count += 1 diff = time() - self._basetime if (diff > self._fps_window): self._fps = self._frame_count / diff self._basetime = time() self._frame_count = 0 sel...
Update the fps after every window
def _create_attach_record(self, id, timed): """ Create a new pivot attachement record. """ record = super(MorphToMany, self)._create_attach_record(id, timed) record[self._morph_type] = self._morph_class return record
Create a new pivot attachement record.
def tocimxml(self, ignore_path=False): """ Return the CIM-XML representation of this CIM instance, as an object of an appropriate subclass of :term:`Element`. If the instance has no instance path specified or if `ignore_path` is `True`, the returned CIM-XML representation is an ...
Return the CIM-XML representation of this CIM instance, as an object of an appropriate subclass of :term:`Element`. If the instance has no instance path specified or if `ignore_path` is `True`, the returned CIM-XML representation is an `INSTANCE` element consistent with :term:`DSP0201`....
def add_user_grant(self, permission, user_id, recursive=False, headers=None): """ Convenience method that provides a quick way to add a canonical user grant to a bucket. This method retrieves the current ACL, creates a new grant based on the parameters passed in, adds that grant to the A...
Convenience method that provides a quick way to add a canonical user grant to a bucket. This method retrieves the current ACL, creates a new grant based on the parameters passed in, adds that grant to the ACL and then PUTs the new ACL back to GS. :type permission: string :param ...
def get_current_user_ids(self, db_read=None): """ Returns current user ids and the count. """ db_read = db_read or self.db_read return self.user_ids.using(db_read)
Returns current user ids and the count.
def on_add_cols(self, event): """ Show simple dialog that allows user to add a new column name """ col_labels = self.grid.col_labels # do not list headers that are already column labels in the grid er_items = [head for head in self.grid_headers[self.grid_type]['er'][2] if...
Show simple dialog that allows user to add a new column name
def flatMapValues(self, f): """ Pass each value in the key-value pair RDD through a flatMap function without changing the keys; this also retains the original RDD's partitioning. >>> x = sc.parallelize([("a", ["x", "y", "z"]), ("b", ["p", "r"])]) >>> def f(x): return x ...
Pass each value in the key-value pair RDD through a flatMap function without changing the keys; this also retains the original RDD's partitioning. >>> x = sc.parallelize([("a", ["x", "y", "z"]), ("b", ["p", "r"])]) >>> def f(x): return x >>> x.flatMapValues(f).collect() ...
def export_element(bpmn_graph, export_elements, node, nodes_classification, order=0, prefix="", condition="", who="", add_join=False): """ Export a node with "Element" classification (task, subprocess or gateway) :param bpmn_graph: an instance of BpmnDiagramGraph class, ...
Export a node with "Element" classification (task, subprocess or gateway) :param bpmn_graph: an instance of BpmnDiagramGraph class, :param export_elements: a dictionary object. The key is a node ID, value is a dictionary of parameters that will be used in exported CSV document, :...
def getLocationRepresentation(self): """ Get the full population representation of the location layer. """ activeCells = np.array([], dtype="uint32") totalPrevCells = 0 for module in self.L6aModules: activeCells = np.append(activeCells, module.getActiveCells(...
Get the full population representation of the location layer.
def get_tag_html(tag_id): """ Returns the Django HTML to load the tag library and render the tag. Args: tag_id (str): The tag id for the to return the HTML for. """ tag_data = get_lazy_tag_data(tag_id) tag = tag_data['tag'] args = tag_data['args'] kwargs = tag_data['kwargs'] ...
Returns the Django HTML to load the tag library and render the tag. Args: tag_id (str): The tag id for the to return the HTML for.
def rekey(self, uid=None, offset=None, **kwargs): """ Rekey an existing key. Args: uid (string): The unique ID of the symmetric key to rekey. Optional, defaults to None. offset (int): The time delta, in seconds, b...
Rekey an existing key. Args: uid (string): The unique ID of the symmetric key to rekey. Optional, defaults to None. offset (int): The time delta, in seconds, between the new key's initialization date and activation date. Optional, defaults ...
def flatten_multi_dim(sequence): """Flatten a multi-dimensional array-like to a single dimensional sequence (as a generator). """ for x in sequence: if (isinstance(x, collections.Iterable) and not isinstance(x, six.string_types)): for y in flatten_multi_dim(x): ...
Flatten a multi-dimensional array-like to a single dimensional sequence (as a generator).
def add_template_global(self, f, name=None): """Register a custom template global function. Works exactly like the :meth:`template_global` decorator. .. versionadded:: 0.10 :param name: the optional name of the global function, otherwise the function name will be u...
Register a custom template global function. Works exactly like the :meth:`template_global` decorator. .. versionadded:: 0.10 :param name: the optional name of the global function, otherwise the function name will be used.
def best_match_from_list(item,options,fuzzy=90,fname_match=True,fuzzy_fragment=None,guess=False): '''Returns the best match from :meth:`matches_from_list` or ``None`` if no good matches''' matches = matches_from_list(item,options,fuzzy,fname_match,fuzzy_fragment,guess) if len(matches)>0: return matc...
Returns the best match from :meth:`matches_from_list` or ``None`` if no good matches
def driver_send(command,hostname=None,wait=0.2): '''Send a command (or ``list`` of commands) to AFNI at ``hostname`` (defaults to local host) Requires plugouts enabled (open afni with ``-yesplugouts`` or set ``AFNI_YESPLUGOUTS = YES`` in ``.afnirc``) If ``wait`` is not ``None``, will automatically sleep ``w...
Send a command (or ``list`` of commands) to AFNI at ``hostname`` (defaults to local host) Requires plugouts enabled (open afni with ``-yesplugouts`` or set ``AFNI_YESPLUGOUTS = YES`` in ``.afnirc``) If ``wait`` is not ``None``, will automatically sleep ``wait`` seconds after sending the command (to make sure it...
def apparent_dip_correction(axes): """ Produces a two-dimensional rotation matrix that rotates a projected dataset to correct for apparent dip """ a1 = axes[0].copy() a1[-1] = 0 cosa = angle(axes[0],a1,cos=True) _ = 1-cosa**2 if _ > 1e-12: sina = N.sqrt(_) if cosa < 0...
Produces a two-dimensional rotation matrix that rotates a projected dataset to correct for apparent dip
def select_distinct_field(col, field_or_fields, filters=None): """Select distinct value or combination of values of single or multiple fields. :params fields: str or list of str. :return data: list of list. **中文文档** 选择多列中出现过的所有可能的排列组合。 """ fields = _preprocess_field_or_fields(field_or...
Select distinct value or combination of values of single or multiple fields. :params fields: str or list of str. :return data: list of list. **中文文档** 选择多列中出现过的所有可能的排列组合。
def encode_grib2_data(self): """ Encodes member percentile data to GRIB2 format. Returns: Series of GRIB2 messages """ lscale = 1e6 grib_id_start = [7, 0, 14, 14, 2] gdsinfo = np.array([0, np.product(self.data.shape[-2:]), 0, 0, 30], dtype=np.int32) ...
Encodes member percentile data to GRIB2 format. Returns: Series of GRIB2 messages
def getWorkerInfo(dataTask): """Returns the total execution time and task quantity by worker""" workertime = [] workertasks = [] for fichier, vals in dataTask.items(): if hasattr(vals, 'values'): #workers_names.append(fichier) # Data from worker totaltime = su...
Returns the total execution time and task quantity by worker
def _create_page(cls, page, lang, auto_title, cms_app=None, parent=None, namespace=None, site=None, set_home=False): """ Create a single page or titles :param page: Page instance :param lang: language code :param auto_title: title text for the newly created ...
Create a single page or titles :param page: Page instance :param lang: language code :param auto_title: title text for the newly created title :param cms_app: Apphook Class to be attached to the page :param parent: parent page (None when creating the home page) :param na...
def randtld(self): """ -> a random #str tld via :mod:tlds """ self.tlds = tuple(tlds.tlds) if not self.tlds else self.tlds return self.random.choice(self.tlds)
-> a random #str tld via :mod:tlds
def join_state(self, state, history_index, concurrency_history_item): """ a utility function to join a state :param state: the state to join :param history_index: the index of the execution history stack in the concurrency history item for the given state ...
a utility function to join a state :param state: the state to join :param history_index: the index of the execution history stack in the concurrency history item for the given state :param concurrency_history_item: the concurrency history item that stores the exe...
def s3_etag(url: str) -> Optional[str]: """Check ETag on S3 object.""" s3_resource = boto3.resource("s3") bucket_name, s3_path = split_s3_path(url) s3_object = s3_resource.Object(bucket_name, s3_path) return s3_object.e_tag
Check ETag on S3 object.
def _deregister(self, session): """ Deregister a session. """ if session in self: self._sessions.pop(self._get_session_key(session), None)
Deregister a session.
def update_agent_state(): '''Update the current agent state in opencast. ''' configure_service('capture.admin') status = 'idle' # Determine reported agent state with priority list if get_service_status(db.Service.SCHEDULE) == db.ServiceStatus.STOPPED: status = 'offline' elif get_ser...
Update the current agent state in opencast.
def GetVersion(): """Gets the version from googleads/common.py. We can't import this directly because new users would get ImportErrors on our third party dependencies. Returns: The version of the library. """ with open(os.path.join('googleads', 'common.py')) as versions_file: source = versions_fil...
Gets the version from googleads/common.py. We can't import this directly because new users would get ImportErrors on our third party dependencies. Returns: The version of the library.
def DVSFile(ID, season, cadence='lc'): ''' Returns the name of the DVS PDF for a given target. :param ID: The target ID :param int season: The target season number :param str cadence: The cadence type. Default `lc` ''' if cadence == 'sc': strcadence = '_sc' else: strca...
Returns the name of the DVS PDF for a given target. :param ID: The target ID :param int season: The target season number :param str cadence: The cadence type. Default `lc`
def n_to_one(num_inputs, num_streams, bits_per_axis, weight_per_axis): """ Creating inputs of the form: ``( x, y, ..., y )'' |---------| n Here n = num_streams -1. To be more precise, for each component we allocate a fixed number of units `bits_p...
Creating inputs of the form: ``( x, y, ..., y )'' |---------| n Here n = num_streams -1. To be more precise, for each component we allocate a fixed number of units `bits_per_axis` and encode each component with a scalar encoder. This is a toy exampl...
def compile_link_import_strings(codes, build_dir=None, **kwargs): """ Creates a temporary directory and dumps, compiles and links provided source code. Parameters ---------- codes: iterable of name/source pair tuples build_dir: string (default: None) path to cache_dir. None implies ...
Creates a temporary directory and dumps, compiles and links provided source code. Parameters ---------- codes: iterable of name/source pair tuples build_dir: string (default: None) path to cache_dir. None implies use a temporary directory. **kwargs: keyword arguments passed onto...
def find_end(self, text, start_token, end_token, ignore_end_token=None): '''find the of a token. Returns the offset in the string immediately after the matching end_token''' if not text.startswith(start_token): raise MAVParseError("invalid token start") offset = len(start_tok...
find the of a token. Returns the offset in the string immediately after the matching end_token
def convert(self, txn): """ Convert an OFX Transaction to a posting """ ofxid = self.mk_ofxid(txn.id) metadata = {} posting_metadata = {"ofxid": ofxid} if isinstance(txn, OfxTransaction): posting = Posting(self.name, Amo...
Convert an OFX Transaction to a posting
def constant(X, n, mu, hyper_deriv=None): """Function implementing a constant mean suitable for use with :py:class:`MeanFunction`. """ if (n == 0).all(): if hyper_deriv is not None: return scipy.ones(X.shape[0]) else: return mu * scipy.ones(X.shape[0]) else: ...
Function implementing a constant mean suitable for use with :py:class:`MeanFunction`.
def addpackage(sys_sitedir, pthfile, known_dirs): """ Wrapper for site.addpackage Try and work out which directories are added by the .pth and add them to the known_dirs set :param sys_sitedir: system site-packages directory :param pthfile: path file to add :param known_dirs: set of known ...
Wrapper for site.addpackage Try and work out which directories are added by the .pth and add them to the known_dirs set :param sys_sitedir: system site-packages directory :param pthfile: path file to add :param known_dirs: set of known directories
def closed(self, reason): ''' 异步爬取全部结束后,执行此关闭方法,对 ``item_list`` 中的数据进行 **JSON** 序列化,并输出到指定文件中,传递给 :meth:`.ZhihuDaily.crawl` :param obj reason: 爬虫关闭原因 ''' self.logger.debug('结果列表: {}'.format(self.item_list)) output_strings = json.dumps(self.item_list, ensure_asci...
异步爬取全部结束后,执行此关闭方法,对 ``item_list`` 中的数据进行 **JSON** 序列化,并输出到指定文件中,传递给 :meth:`.ZhihuDaily.crawl` :param obj reason: 爬虫关闭原因
def close(self, reply_code=0, reply_text='', method_sig=(0, 0)): """ request a channel close This method indicates that the sender wants to close the channel. This may be due to internal conditions (e.g. a forced shut-down) or due to an error handling a specific method, i.e. ...
request a channel close This method indicates that the sender wants to close the channel. This may be due to internal conditions (e.g. a forced shut-down) or due to an error handling a specific method, i.e. an exception. When a close is due to an exception, the sender provides ...
def set(self, image_file, source=None): """ Updates store for the `image_file`. Makes sure the `image_file` has a size set. """ image_file.set_size() # make sure its got a size self._set(image_file.key, image_file) if source is not None: if not self.g...
Updates store for the `image_file`. Makes sure the `image_file` has a size set.
def pem_as_string(cert): """ Only return False if the certificate is a file path. Otherwise it is a file object or raw string and will need to be fed to the file open context. """ if hasattr(cert, 'read'): # File object - return as is return cert cert = cert.encode('utf-8') if isinst...
Only return False if the certificate is a file path. Otherwise it is a file object or raw string and will need to be fed to the file open context.
def commit_on_success(using=None): """ This decorator activates commit on response. This way, if the view function runs successfully, a commit is made; if the viewfunc produces an exception, a rollback is made. This is one of the most common ways to do transaction control in Web apps. """ de...
This decorator activates commit on response. This way, if the view function runs successfully, a commit is made; if the viewfunc produces an exception, a rollback is made. This is one of the most common ways to do transaction control in Web apps.
def quick_add(self, api_token, text, **kwargs): """Add a task using the Todoist 'Quick Add Task' syntax. :param api_token: The user's login api_token. :type api_token: str :param text: The text of the task that is parsed. A project name starts with the `#` character, a label...
Add a task using the Todoist 'Quick Add Task' syntax. :param api_token: The user's login api_token. :type api_token: str :param text: The text of the task that is parsed. A project name starts with the `#` character, a label starts with a `@` and an assignee starts with ...
def target_to_ipv6_short(target): """ Attempt to return a IPv6 short-range list from a target string. """ splitted = target.split('-') if len(splitted) != 2: return None try: start_packed = inet_pton(socket.AF_INET6, splitted[0]) end_value = int(splitted[1], 16) except (sock...
Attempt to return a IPv6 short-range list from a target string.
def add_synonym(self, syn): """ Adds a synonym for a node """ n = self.node(syn.class_id) if 'meta' not in n: n['meta'] = {} meta = n['meta'] if 'synonyms' not in meta: meta['synonyms'] = [] meta['synonyms'].append(syn.as_dict())
Adds a synonym for a node
def update_channel(self, channel): """ Method to update a channel. :param channel: List containing channel's desired to be created on database. :return: Id. """ data = {'channels': channel} return super(ApiInterfaceRequest, self).put('api/v3/channel/', data)
Method to update a channel. :param channel: List containing channel's desired to be created on database. :return: Id.
def CreateWeightTableLDAS(in_ldas_nc, in_nc_lon_var, in_nc_lat_var, in_catchment_shapefile, river_id, in_connectivity_file, out_weight_table, ...
Create Weight Table for NLDAS, GLDAS grids as well as for 2D Joules, or LIS Grids Parameters ---------- in_ldas_nc: str Path to the land surface model NetCDF grid. in_nc_lon_var: str The variable name in the NetCDF file for the longitude. in_nc_lat_var: str The variable ...
def from_miss(self, **kwargs): """Called to initialize an instance when it is not found in the cache. For example, if your CacheModel should pull data from the database to populate the cache, ... def from_miss(self, username): user = User.objects.get(us...
Called to initialize an instance when it is not found in the cache. For example, if your CacheModel should pull data from the database to populate the cache, ... def from_miss(self, username): user = User.objects.get(username=username) self.emai...
def get_target_list(self, scan_id): """ Get a scan's target list. """ target_list = [] for target, _, _ in self.scans_table[scan_id]['targets']: target_list.append(target) return target_list
Get a scan's target list.
def items(self): """non-class attributes ordered by alphabetical order. :: >>> class MyClass(Constant): ... a = 1 # non-class attributre ... b = 2 # non-class attributre ... ... class C(Constant): ... pass ...
non-class attributes ordered by alphabetical order. :: >>> class MyClass(Constant): ... a = 1 # non-class attributre ... b = 2 # non-class attributre ... ... class C(Constant): ... pass ... ... ...
async def ack(self): """|coro| Marks this message as read. The user must not be a bot user. Raises ------- HTTPException Acking failed. ClientException You must not be a bot user. """ state = self._state if state...
|coro| Marks this message as read. The user must not be a bot user. Raises ------- HTTPException Acking failed. ClientException You must not be a bot user.
def polytropic_exponent(k, n=None, eta_p=None): r'''Calculates one of: * Polytropic exponent from polytropic efficiency * Polytropic efficiency from the polytropic exponent .. math:: n = \frac{k\eta_p}{1 - k(1-\eta_p)} .. math:: \eta_p = \frac{\left(\frac{n}{n-1}\right...
r'''Calculates one of: * Polytropic exponent from polytropic efficiency * Polytropic efficiency from the polytropic exponent .. math:: n = \frac{k\eta_p}{1 - k(1-\eta_p)} .. math:: \eta_p = \frac{\left(\frac{n}{n-1}\right)}{\left(\frac{k}{k-1} \right)} = \frac{n(k-...
def _set_view(self): """Assign a horizontal view to current graph""" if self.logarithmic: view_class = HorizontalLogView else: view_class = HorizontalView self.view = view_class( self.width - self.margin_box.x, self.height - self.margin_box.y, ...
Assign a horizontal view to current graph
def get_feat_segments(F, bound_idxs): """Returns a set of segments defined by the bound_idxs. Parameters ---------- F: np.ndarray Matrix containing the features, one feature vector per row. bound_idxs: np.ndarray Array with boundary indeces. Returns ------- feat_segment...
Returns a set of segments defined by the bound_idxs. Parameters ---------- F: np.ndarray Matrix containing the features, one feature vector per row. bound_idxs: np.ndarray Array with boundary indeces. Returns ------- feat_segments: list List of segments, one for eac...
def close(self, error=None): """Close socket and fail all in-flight-requests. Arguments: error (Exception, optional): pending in-flight-requests will be failed with this exception. Default: kafka.errors.KafkaConnectionError. """ if self.state ...
Close socket and fail all in-flight-requests. Arguments: error (Exception, optional): pending in-flight-requests will be failed with this exception. Default: kafka.errors.KafkaConnectionError.
def submit_export(cls, file, volume, location, properties=None, overwrite=False, copy_only=False, api=None): """ Submit new export job. :param file: File to be exported. :param volume: Volume identifier. :param location: Volume location. :param prop...
Submit new export job. :param file: File to be exported. :param volume: Volume identifier. :param location: Volume location. :param properties: Properties dictionary. :param overwrite: If true it will overwrite file if exists :param copy_only: If true files are kept on Se...
def lookup_rdap(self, inc_raw=False, retry_count=3, depth=0, excluded_entities=None, bootstrap=False, rate_limit_timeout=120, asn_alts=None, extra_org_map=None, inc_nir=True, nir_field_list=None, asn_methods=None, get_asn_description=True):...
The function for retrieving and parsing whois information for an IP address via HTTP (RDAP). **This is now the recommended method, as RDAP contains much better information to parse.** Args: inc_raw (:obj:`bool`): Whether to include the raw whois results in t...
def update_readme(self, template_readme: Template): """Generate the new README file locally.""" readme = os.path.join(self.cached_repo, "README.md") if os.path.exists(readme): os.remove(readme) links = {model_type: {} for model_type in self.models.keys()} for model_ty...
Generate the new README file locally.
def eval(self, expr): """ Evaluates an expression :param expr: Expression to evaluate :return: Result of expression """ # set a copy of the expression aside, so we can give nice errors... self.expr = expr # and evaluate: return self._eval(ast.pa...
Evaluates an expression :param expr: Expression to evaluate :return: Result of expression
def sort(self, **parameters): """ Enhance the default sort method to accept a new parameter "by_score", to use instead of "by" if you want to sort by the score of a sorted set. You must pass to "by_sort" the key of a redis sorted set (or a sortedSetField attached to an instance) ...
Enhance the default sort method to accept a new parameter "by_score", to use instead of "by" if you want to sort by the score of a sorted set. You must pass to "by_sort" the key of a redis sorted set (or a sortedSetField attached to an instance)
def replace(self, source, dest): """Replace source broker with destination broker in replica set if found.""" for i, broker in enumerate(self.replicas): if broker == source: self.replicas[i] = dest return
Replace source broker with destination broker in replica set if found.
def _read_config(self): """Read the configuration from the various places it may be read from. :rtype: str :raises: ValueError """ if not self._file_path: return None elif self._file_path.startswith('s3://'): return self._read_s3_config() ...
Read the configuration from the various places it may be read from. :rtype: str :raises: ValueError
def _validate_ding0_grid_import(mv_grid, ding0_mv_grid, lv_grid_mapping): """Cross-check imported data with original data source Parameters ---------- mv_grid: MVGrid eDisGo MV grid instance ding0_mv_grid: MVGridDing0 Ding0 MV grid instance lv_grid_mapping: dict Translat...
Cross-check imported data with original data source Parameters ---------- mv_grid: MVGrid eDisGo MV grid instance ding0_mv_grid: MVGridDing0 Ding0 MV grid instance lv_grid_mapping: dict Translates Ding0 LV grids to associated, newly created eDisGo LV grids
def pull_logs(self, project_name, logstore_name, shard_id, cursor, count=None, end_cursor=None, compress=None): """ batch pull log data from log service Unsuccessful opertaion will cause an LogException. :type project_name: string :param project_name: the Project name :...
batch pull log data from log service Unsuccessful opertaion will cause an LogException. :type project_name: string :param project_name: the Project name :type logstore_name: string :param logstore_name: the logstore name :type shard_id: int :param sh...