docstring
stringlengths
52
499
function
stringlengths
67
35.2k
__index_level_0__
int64
52.6k
1.16M
Remove profile from credentials file. Args: profile (str): Credentials profile to remove. Returns: list: List of affected document IDs.
def remove_profile(self, profile=None): with self.db: return self.db.remove(self.query.profile == profile)
551,569
Write credentials. Write credentials to credentials file. Performs ``upsert``. Args: cache_token (bool): If ``True``, stores ``access_token`` in token store. Defaults to ``True``. credentials (class): Read-only credentials. profile (str): Credentials profile. Defaul...
def write_credentials(self, credentials=None, profile=None, cache_token=None): d = { 'profile': profile, 'client_id': credentials.client_id, 'client_secret': credentials.client_secret, 'refresh_token': credentials.refresh_token ...
551,570
Send a negative read-acknowledgement to the service. Causes the channel's read point to move to its previous position prior to the last poll. Args: channel_id (str): The channel ID. **kwargs: Supported :meth:`~pancloud.httpclient.HTTPClient.request` parameters. ...
def nack(self, channel_id=None, **kwargs): # pragma: no cover path = "/event-service/v1/channels/{}/nack".format(channel_id) r = self._httpclient.request( method="POST", url=self.url, path=path, **kwargs ) return r
551,571
Read one or more events from a channel. Reads events (log records) from the identified channel. Events are read in chronological order. Args: channel_id (str): The channel ID. json (dict): Payload/request body. **kwargs: Supported :meth:`~pancloud.httpclient...
def poll(self, channel_id=None, json=None, **kwargs): # pragma: no cover path = "/event-service/v1/channels/{}/poll".format(channel_id) r = self._httpclient.request( method="POST", url=self.url, json=json, path=path, **kwargs ...
551,572
Update Authorization header. Update request headers with latest `access_token`. Perform token `refresh` if token is ``None``. Args: auto_refresh (bool): Perform token refresh if access_token is ``None`` or expired. Defaults to ``True``. credentials (class): Read-only cr...
def _apply_credentials(auto_refresh=True, credentials=None, headers=None): token = credentials.get_credentials().access_token if auto_refresh is True: if token is None: token = credentials.refresh( access_token=None, tim...
551,575
Determine the starting and ending beta from h J Args: h (dict) J (dict) Assume each variable in J is also in h. We use the minimum bias to give a lower bound on the minimum energy gap, such at the final sweeps we are highly likely to settle into the current valley.
def _default_ising_beta_range(h, J): # Get nonzero, absolute biases abs_h = [abs(hh) for hh in h.values() if hh != 0] abs_J = [abs(jj) for jj in J.values() if jj != 0] abs_biases = abs_h + abs_J if not abs_biases: return [0.1, 1.0] # Rough approximation of min change in energy whe...
551,931
Leave module and check remaining triple quotes. Args: node: the module node we are leaving.
def leave_module(self, node): for triple_quote in self._tokenized_triple_quotes.values(): self._check_triple_quotes(triple_quote) # after we are done checking these, clear out the triple-quote # tracking collection so nothing is left over for the next module. self._...
551,954
Check for docstring quote consistency. Args: node: the AST node being visited. node_type: the type of node being operated on.
def _process_for_docstring(self, node, node_type): # if there is no docstring, don't need to do anything. if node.doc is not None: # the module is everything, so to find the docstring, we # iterate line by line from the start until the first element # to fin...
551,955
Find the docstring associated with a definition with no body in the node. In these cases, the provided start and end line number for that element are the same, so we must get the docstring based on the sequential position of known docstrings. Args: start: the row wh...
def _find_docstring_line_for_no_body(self, start): tracked = sorted(list(self._tokenized_triple_quotes.keys())) for i in tracked: if min(start, i) == start: return i return None
551,956
Find the row where a docstring starts in a function or class. This will search for the first match of a triple quote token in row sequence from the start of the class or function. Args: start: the row where the class / function starts. end: the row where the class / fun...
def _find_docstring_line(self, start, end): for i in range(start, end + 1): if i in self._tokenized_triple_quotes: return i return None
551,957
Process the token stream. This is required to override the parent class' implementation. Args: tokens: the tokens from the token stream to process.
def process_tokens(self, tokens): for tok_type, token, (start_row, start_col), _, _ in tokens: if tok_type == tokenize.STRING: # 'token' is the whole un-parsed token; we can look at the start # of it to see whether it's a raw or unicode string etc. ...
551,958
Internal method for identifying and checking string tokens from the token stream. Args: token: the token to check. start_row: the line on which the token was found. start_col: the column on which the token was found.
def _process_string_token(self, token, start_row, start_col): for i, char in enumerate(token): if char in QUOTES: break # pylint: disable=undefined-loop-variable # ignore prefix markers like u, b, r norm_quote = token[i:] # triple-quote stri...
551,959
Check if the triple quote from tokenization is valid. Args: quote_record: a tuple containing the info about the string from tokenization, giving the (token, quote, row number, column).
def _check_triple_quotes(self, quote_record): _, triple, row, col = quote_record if triple != TRIPLE_QUOTE_OPTS.get(self.config.triple_quote): self._invalid_triple_quote(triple, row, col)
551,960
Check if the docstring quote from tokenization is valid. Args: quote_record: a tuple containing the info about the string from tokenization, giving the (token, quote, row number).
def _check_docstring_quotes(self, quote_record): _, triple, row, col = quote_record if triple != TRIPLE_QUOTE_OPTS.get(self.config.docstring_quote): self._invalid_docstring_quote(triple, row, col)
551,961
Add a message for an invalid string literal quote. Args: quote: The quote characters that were found. row: The row number the quote character was found on. correct_quote: The quote characters that is required. If None (default), will use the one from the conf...
def _invalid_string_quote(self, quote, row, correct_quote=None, col=None): if not correct_quote: correct_quote = SMART_QUOTE_OPTS.get(self.config.string_quote) self.add_message( 'invalid-string-quote', line=row, args=(quote, correct_quote), ...
551,962
Add a message for an invalid triple quote. Args: quote: The quote characters that were found. row: The row number the quote characters were found on. col: The column the quote characters were found on.
def _invalid_triple_quote(self, quote, row, col=None): self.add_message( 'invalid-triple-quote', line=row, args=(quote, TRIPLE_QUOTE_OPTS.get(self.config.triple_quote)), **self.get_offset(col) )
551,963
Add a message for an invalid docstring quote. Args: quote: The quote characters that were found. row: The row number the quote characters were found on. col: The column the quote characters were found on.
def _invalid_docstring_quote(self, quote, row, col=None): self.add_message( 'invalid-docstring-quote', line=row, args=(quote, TRIPLE_QUOTE_OPTS.get(self.config.docstring_quote)), **self.get_offset(col) )
551,964
Accepts a Metric object and evaluates it at each fold. Parameters: Thresholds: [Float], default: None Thresholds for reporting the two metrics. If not set, thresholds are model predictions from all runs computed on the fly. lower_quantile, upper_quantile: Float, default...
def __init__(self, metric1, metric2, granularity_sigfigs=3, **kwargs): Reporter.__init__(self, **kwargs) if (not isinstance(metric1, metrics.ThresholdMetric) or not isinstance(metric2, metrics.ThresholdMetric)): raise TypeError("Requires ThresholdMetric") sel...
554,218
Provides an iterator over passed-in configuration values, allowing for easy exploration of models. Parameters: ___________ base_model_definition: The base `ModelDefinition` to augment kwargs: Can be any keyword accepted by `ModelDefinition`. Values should be iterables.
def model_definition_factory(base_model_definition, **kwargs): if not kwargs: yield config else: for param in kwargs: if not hasattr(base_model_definition, param): raise ValueError("'%s' is not a valid configuration parameter" % param) for raw_params in ...
554,224
run the event loops in the background. Args: eventLoops (list): a list of event loops to run
def run_multiple(self, eventLoops): self.nruns += len(eventLoops) return self.communicationChannel.put_multiple(eventLoops)
554,427
Convert ``key_vals_dict`` to `tuple_list``. Args: key_vals_dict (dict): The first parameter. fill: a value to fill missing data Returns: A list of tuples
def key_vals_dict_to_tuple_list(key_vals_dict, fill=float('nan')): tuple_list = [ ] if not key_vals_dict: return tuple_list vlen = max([len(vs) for vs in itertools.chain(*key_vals_dict.values())]) for k, vs in key_vals_dict.items(): try: tuple_list.extend([k + tuple(v) + (fi...
554,432
expand a path config Args: path_cfg (str, tuple, dict): a config for path alias_dict (dict): a dict for aliases overriding_kargs (dict): to be used for recursive call
def expand_path_cfg(path_cfg, alias_dict={ }, overriding_kargs={ }): if isinstance(path_cfg, str): return _expand_str(path_cfg, alias_dict, overriding_kargs) if isinstance(path_cfg, dict): return _expand_dict(path_cfg, alias_dict) # assume tuple or list return _expand_tuple(path_...
554,518
expand a path config given as a string Args: path_cfg (str): an alias alias_dict (dict): overriding_kargs (dict):
def _expand_str_alias(path_cfg, alias_dict, overriding_kargs): # e.g., # path_cfg = 'var_cut' new_path_cfg = alias_dict[path_cfg] # e.g., ('ev : {low} <= ev.var[0] < {high}', {'low': 10, 'high': 200}) new_overriding_kargs = dict(alias=path_cfg) # e.g., {'alias': 'var_cut'} new_overr...
554,521
Get a child HTTPAPI instance. Args: user: The Matrix ID of the user whose API to get. Returns: A HTTPAPI instance that always uses the given Matrix ID.
def user(self, user: str) -> "ChildHTTPAPI": if self.is_real_user: raise ValueError("Can't get child of real user") try: return self.children[user] except KeyError: child = ChildHTTPAPI(user, self) self.children[user] = child ...
554,950
Get the intent API for a specific user. Args: user: The Matrix ID of the user whose intent API to get. Returns: The IntentAPI for the given user.
def intent(self, user: str = None, token: Optional[str] = None) -> "IntentAPI": if self.is_real_user: raise ValueError("Can't get child intent of real user") if token: return IntentAPI(user, self.real_user(user, token), self.bot_intent(), self.state_store, ...
554,953
Get the intent API for a specific user. This is just a proxy to :func:`~HTTPAPI.intent`. You should only call this method for the bot user. Calling it with child intent APIs will result in a warning log. Args: user: The Matrix ID of the user whose intent API to get. tok...
def user(self, user: str, token: Optional[str] = None) -> "IntentAPI": if not self.bot: return self.client.intent(user, token) else: self.log.warning("Called IntentAPI#user() of child intent object.") return self.bot.client.intent(user, token)
554,961
Set the display name of the user. See also: `API reference`_ Args: name: The new display name for the user. .. _API reference: https://matrix.org/docs/spec/client_server/r0.3.0.html#put-matrix-client-r0-profile-userid-displayname
async def set_display_name(self, name: str): await self.ensure_registered() content = {"displayname": name} await self.client.request("PUT", f"/profile/{self.mxid}/displayname", content)
554,963
Set the online status of the user. See also: `API reference`_ Args: status: The online status of the user. Allowed values: "online", "offline", "unavailable". ignore_cache: Whether or not to set presence even if the cache says the presence is already set to that value. ...
async def set_presence(self, status: str = "online", ignore_cache: bool = False): await self.ensure_registered() if not ignore_cache and self.state_store.has_presence(self.mxid, status): return content = { "presence": status } resp = await self.c...
554,964
Set the avatar of the user. See also: `API reference`_ Args: url: The new avatar URL for the user. Must be a MXC URI. .. _API reference: https://matrix.org/docs/spec/client_server/r0.3.0.html#put-matrix-client-r0-profile-userid-avatar-url
async def set_avatar(self, url: str): await self.ensure_registered() content = {"avatar_url": url} await self.client.request("PUT", f"/profile/{self.mxid}/avatar_url", content)
554,965
Upload a file to the content repository. See also: `API reference`_ Args: data: The data to upload. mime_type: The MIME type to send with the upload request. Returns: The MXC URI to the uploaded file. Raises: MatrixResponseError: If the response...
async def upload_file(self, data: bytes, mime_type: Optional[str] = None) -> str: await self.ensure_registered() if magic: mime_type = mime_type or magic.from_buffer(data, mime=True) resp = await self.client.request("POST", "", content=data, ...
554,966
Download a file from the content repository. See also: `API reference`_ Args: url: The MXC URI to download. Returns: The raw downloaded data. .. _API reference: https://matrix.org/docs/spec/client_server/r0.3.0.html#get-matrix-media-r0-download-servername-me...
async def download_file(self, url: str) -> bytes: await self.ensure_registered() url = self.client.get_download_url(url) async with self.client.session.get(url) as response: return await response.read()
554,967
Adds a new section to the free section list, but before that and if section merge is enabled, tries to join the rectangle with all existing sections, if successful the resulting section is again merged with the remaining sections until the operation fails. The result is then appended...
def _add_section(self, section): section.rid = 0 plen = 0 while self._merge and self._sections and plen != len(self._sections): plen = len(self._sections) self._sections = [s for s in self._sections if not section.join(s)] self._sections.append(sect...
555,016
Add rectangle of widthxheight dimensions. Arguments: width (int, float): Rectangle width height (int, float): Rectangle height rid: Optional rectangle user id Returns: Rectangle: Rectangle with placemente coordinates None: If the rectangle co...
def add_rect(self, width, height, rid=None): assert(width > 0 and height >0) # Obtain the best section to place the rectangle. section, rotated = self._select_fittest_section(width, height) if not section: return None if rotated: wi...
555,019
Use bottom-left packing algorithm to find a lower height for the container. Arguments: width height Returns: tuple (width, height, PackingAlgorithm):
def _refine_candidate(self, width, height): packer = newPacker(PackingMode.Offline, PackingBin.BFF, pack_algo=self._pack_algo, sort_algo=SORT_LSIDE, rotation=self._rotation) packer.add_bin(width, height) for r in self._rectangles: pac...
555,028
When a rectangle is placed inside a maximal rectangle, it stops being one and up to 4 new maximal rectangles may appear depending on the placement. _generate_splits calculates them. Arguments: m (Rectangle): max_rect rectangle r (Rectangle): rectangle placed Ret...
def _generate_splits(self, m, r): new_rects = [] if r.left > m.left: new_rects.append(Rectangle(m.left, m.bottom, r.left-m.left, m.height)) if r.right < m.right: new_rects.append(Rectangle(r.right, m.bottom, m.right-r.right, m.height)) if r.top <...
555,032
Split all max_rects intersecting the rectangle rect into up to 4 new max_rects. Arguments: rect (Rectangle): Rectangle Returns: split (Rectangle list): List of rectangles resulting from the split
def _split(self, rect): max_rects = collections.deque() for r in self._max_rects: if r.intersects(rect): max_rects.extend(self._generate_splits(r, rect)) else: max_rects.append(r) # Add newly generated max_rects self._max...
555,033
Metric used to rate how much space is wasted if a rectangle is placed. Returns a value greater or equal to zero, the smaller the value the more 'fit' is the rectangle. If the rectangle can't be placed, returns None. Arguments: width (int, float): Rectangle width height ...
def fitness(self, width, height): assert(width > 0 and height > 0) rect, max_rect = self._select_position(width, height) if rect is None: return None # Return fitness return self._rect_fitness(max_rect, rect.width, rect.height)
555,035
Add rectangle of widthxheight dimensions. Arguments: width (int, float): Rectangle width height (int, float): Rectangle height rid: Optional rectangle user id Returns: Rectangle: Rectangle with placemente coordinates None: If the rectangle co...
def add_rect(self, width, height, rid=None): assert(width > 0 and height >0) # Search best position and orientation rect, _ = self._select_position(width, height) if not rect: return None # Subdivide all the max rectangles intersecting with the sele...
555,036
Initialize packing algorithm Arguments: width (int, float): Packing surface width height (int, float): Packing surface height rot (bool): Rectangle rotation enabled or disabled bid (string|int|...): Packing surface identification
def __init__(self, width, height, rot=True, bid=None, *args, **kwargs): self.width = width self.height = height self.rot = rot self.rectangles = [] self.bid = bid self._surface = Rectangle(0, 0, width, height) self.reset()
555,040
Test surface is big enough to place a rectangle Arguments: width (int, float): Rectangle width height (int, float): Rectangle height Returns: boolean: True if it could be placed, False otherwise
def _fits_surface(self, width, height): assert(width > 0 and height > 0) if self.rot and (width > self.width or height > self.height): width, height = height, width if width > self.width or height > self.height: return False else: return True
555,041
Create an Horizontal segment given its left most end point and its length. Arguments: - start (Point): Starting Point - length (number): segment length
def __init__(self, start, length): assert(isinstance(start, Point) and not isinstance(length, Point)) super(HSegment, self).__init__(start, Point(start.x+length, start.y))
555,050
Move Rectangle to x,y coordinates Arguments: x (int, float): X coordinate y (int, float): Y coordinate
def move(self, x, y): self.x = x self.y = y
555,054
Tests if another rectangle is contained by this one Arguments: rect (Rectangle): The other rectangle Returns: bool: True if it is container, False otherwise
def contains(self, rect): return (rect.y >= self.y and \ rect.x >= self.x and \ rect.y+rect.height <= self.y+self.height and \ rect.x+rect.width <= self.x+self.width)
555,055
Detect intersections between this rectangle and rect. Args: rect (Rectangle): Rectangle to test for intersections. edges (bool): Accept edge touching rectangles as intersects or not Returns: bool: True if the rectangles intersect, False otherwise
def intersects(self, rect, edges=False): # Not even touching if (self.bottom > rect.top or \ self.top < rect.bottom or \ self.left > rect.right or \ self.right < rect.left): return False # Discard edge intersects if not edge...
555,056
Try to join a rectangle to this one, if the result is also a rectangle and the operation is successful and this rectangle is modified to the union. Arguments: other (Rectangle): Rectangle to join Returns: bool: True when successfully joined, False otherwise
def join(self, other): if self.contains(other): return True if other.contains(self): self.x = other.x self.y = other.y self.width = other.width self.height = other.height return True if not self.intersects(other, ...
555,058
Convert float (or int) to Decimal (rounding up) with the requested number of decimal digits. Arguments: ft (float, int): Number to convert decimal (int): Number of digits after decimal point Return: Decimal: Number converted to decima
def float2dec(ft, decimal_digits): with decimal.localcontext() as ctx: ctx.rounding = decimal.ROUND_UP places = decimal.Decimal(10)**(-decimal_digits) return decimal.Decimal.from_float(float(ft)).quantize(places)
555,059
Packer factory helper function Arguments: mode (PackingMode): Packing mode Online: Rectangles are packed as soon are they are added Offline: Rectangles aren't packed untils pack() is called bin_algo (PackingBin): Bin selection heuristic pack_algo (PackingAlgorithm): ...
def newPacker(mode=PackingMode.Offline, bin_algo=PackingBin.BBF, pack_algo=MaxRectsBssf, sort_algo=SORT_AREA, rotation=True): packer_class = None # Online Mode if mode == PackingMode.Online: sort_algo=None if bin_algo == PackingBin.BNF: p...
555,060
Return best fitness rectangle from rectangles packing _sorted_rect list Arguments: pbin (PackingAlgorithm): Packing bin Returns: key of the rectangle with best fitness
def _find_best_fit(self, pbin): fit = ((pbin.fitness(r[0], r[1]), k) for k, r in self._sorted_rect.items()) fit = (f for f in fit if f[0] is not None) try: _, rect = min(fit, key=self.first_item) return rect except ValueError: return None
555,081
Extract the next bin where at least one of the rectangles in rem Arguments: remaining_rect (dict): rectangles not placed yet Returns: PackingAlgorithm: Initialized empty packing bin. None: No bin big enough for the rectangle was found
def _new_open_bin(self, remaining_rect): factories_to_delete = set() # new_bin = None for key, binfac in self._empty_bins.items(): # Only return the new bin if at least one of the remaining # rectangles fit inside. a_rectangle_fits = False ...
555,082
_skyline is the list used to store all the skyline segments, each one is a list with the format [x, y, width] where x is the x coordinate of the left most point of the segment, y the y coordinate of the segment, and width the length of the segment. The initial segment is allways [0, 0,...
def __init__(self, width, height, rot=True, *args, **kwargs): self._waste_management = False self._waste = WasteManager(rot=rot) super(Skyline, self).__init__(width, height, rot, merge=False, *args, **kwargs)
555,084
Returns a generator for the x coordinates of all the placement points on the skyline for a given rectangle. WARNING: In some cases could be duplicated points, but it is faster to compute them twice than to remove them. Arguments: skyline (list): Skyline HSegment lis...
def _placement_points_generator(self, skyline, width): skyline_r = skyline[-1].right skyline_l = skyline[0].left # Placements using skyline segment left point ppointsl = (s.left for s in skyline if s.left+width <= skyline_r) # Placements using skyline segment right po...
555,085
Generate a list with Arguments: skyline (list): SkylineHSegment list width (number): Returns: tuple (Rectangle, fitness): Rectangle: Rectangle in valid position left_skyline: Index for the skyline under the rectangle left edge. ...
def _generate_placements(self, width, height): skyline = self._skyline points = collections.deque() left_index = right_index = 0 # Left and right side skyline index support_height = skyline[0].top support_index = 0 placements = self._placement_points_gene...
555,086
Return a human-readable string representation of an object. Uses `pretty_str` if the given value is an instance of `CodeEntity` and `repr` otherwise. Args: something: Some value to convert. Kwargs: indent (int): The amount of spaces to use as indentation.
def pretty_str(something, indent=0): if isinstance(something, CodeEntity): return something.pretty_str(indent=indent) else: return (' ' * indent) + repr(something)
555,480
Base constructor for code objects. Args: scope (CodeEntity): The program scope where this object belongs. parent (CodeEntity): This object's parent in the program tree.
def __init__(self, scope, parent): self.scope = scope self.parent = parent self.file = None self.line = None self.column = None
555,481
Retrieves all descendants (including self) that are instances of a given class. Args: cls (class): The class to use as a filter. Kwargs: recursive (bool): Whether to descend recursively down the tree.
def filter(self, cls, recursive=False): source = self.walk_preorder if recursive else self._children return [ codeobj for codeobj in source() if isinstance(codeobj, cls) ]
555,483
Constructor for variables. Args: scope (CodeEntity): The program scope where this object belongs. parent (CodeEntity): This object's parent in the program tree. id: An unique identifier for this variable. name (str): The name of the variable in the program. ...
def __init__(self, scope, parent, id, name, result): CodeEntity.__init__(self, scope, parent) self.id = id self.name = name self.result = result self.value = None self.member_of = None self.references = [] self.writes = []
555,486
Constructor for functions. Args: scope (CodeEntity): The program scope where this object belongs. parent (CodeEntity): This object's parent in the program tree. id: An unique identifier for this function. name (str): The name of the function in the program. ...
def __init__(self, scope, parent, id, name, result, definition=True): CodeEntity.__init__(self, scope, parent) self.id = id self.name = name self.result = result self.parameters = [] self.body = CodeBlock(self, self, explicit=True) self.member_of = None ...
555,491
Constructor for classes. Args: scope (CodeEntity): The program scope where this object belongs. parent (CodeEntity): This object's parent in the program tree. id: An unique identifier for this class. name (str): The name of the class in the program.
def __init__(self, scope, parent, id_, name, definition=True): CodeEntity.__init__(self, scope, parent) self.id = id_ self.name = name self.members = [] self.superclasses = [] self.member_of = None self.references = [] self._definition = self if d...
555,497
Constructor for namespaces. Args: scope (CodeEntity): The program scope where this object belongs. parent (CodeEntity): This object's parent in the program tree. name (str): The name of the namespace in the program.
def __init__(self, scope, parent, name): CodeEntity.__init__(self, scope, parent) self.name = name self.children = []
555,501
Constructor for expressions. Args: scope (CodeEntity): The program scope where this object belongs. parent (CodeEntity): This object's parent in the program tree. name (str): The name of the expression in the program. result (str): The return type of the expressi...
def __init__(self, scope, parent, name, result, paren=False): CodeEntity.__init__(self, scope, parent) self.name = name self.result = result self.parenthesis = paren
555,505
Constructor for null literals. Args: scope (CodeEntity): The program scope where this object belongs. parent (CodeEntity): This object's parent in the program tree. Kwargs: paren (bool): Whether the null literal is enclosed in parentheses.
def __init__(self, scope, parent, paren=False): CodeLiteral.__init__(self, scope, parent, None, 'null', paren)
555,509
Constructor for a compound literal. Args: scope (CodeEntity): The program scope where this object belongs. parent (CodeEntity): This object's parent in the program tree. value (iterable): The initial value sequence in this composition. result (str): The return ty...
def __init__(self, scope, parent, result, value=(), paren=False): try: value = list(value) except TypeError as te: raise AssertionError(str(te)) CodeLiteral.__init__(self, scope, parent, value, result, paren)
555,510
Constructor for references. Args: scope (CodeEntity): The program scope where this object belongs. parent (CodeEntity): This object's parent in the program tree. name (str): The name of the reference in the program. result (str): The return type of the expression...
def __init__(self, scope, parent, name, result, paren=False): CodeExpression.__init__(self, scope, parent, name, result, paren) self.field_of = None self.reference = None
555,513
Constructor for operators. Args: scope (CodeEntity): The program scope where this object belongs. parent (CodeEntity): This object's parent in the program tree. name (str): The name of the operator in the program. result (str): The return type of the operator in ...
def __init__(self, scope, parent, name, result, args=None, paren=False): CodeExpression.__init__(self, scope, parent, name, result, paren) self.arguments = args or ()
555,516
Constructor for function calls. Args: scope (CodeEntity): The program scope where this object belongs. parent (CodeEntity): This object's parent in the program tree. name (str): The name of the function in the program. result (str): The return type of the express...
def __init__(self, scope, parent, name, result, paren=False): CodeExpression.__init__(self, scope, parent, name, result, paren) self.full_name = name self.arguments = () self.method_of = None self.reference = None
555,519
Constructor for default arguments. Args: scope (CodeEntity): The program scope where this object belongs. parent (CodeEntity): This object's parent in the program tree. result (str): The return type of the argument in the program.
def __init__(self, scope, parent, result): CodeExpression.__init__(self, scope, parent, '(default)', result)
555,523
Constructor for statements. Args: scope (CodeEntity): The program scope where this object belongs. parent (CodeEntity): This object's parent in the program tree.
def __init__(self, scope, parent): CodeEntity.__init__(self, scope, parent) self._si = -1
555,524
Constructor for jump statements. Args: scope (CodeEntity): The program scope where this object belongs. parent (CodeEntity): This object's parent in the program tree. name (str): The name of the statement in the program.
def __init__(self, scope, parent, name): CodeStatement.__init__(self, scope, parent) self.name = name self.value = None
555,525
Constructor for expression statements. Args: scope (CodeEntity): The program scope where this object belongs. parent (CodeEntity): This object's parent in the program tree. Kwargs: expression (CodeExpression): The expression of this statement.
def __init__(self, scope, parent, expression=None): CodeStatement.__init__(self, scope, parent) self.expression = expression
555,528
Constructor for code blocks. Args: scope (CodeEntity): The program scope where this object belongs. parent (CodeEntity): This object's parent in the program tree. Kwargs: explicit (bool): Whether the block is explicit in the code.
def __init__(self, scope, parent, explicit=True): CodeStatement.__init__(self, scope, parent) self.body = [] self.explicit = explicit
555,529
Constructor for declaration statements. Args: scope (CodeEntity): The program scope where this object belongs. parent (CodeEntity): This object's parent in the program tree.
def __init__(self, scope, parent): CodeStatement.__init__(self, scope, parent) self.variables = []
555,532
Constructor for control flow structures. Args: scope (CodeEntity): The program scope where this object belongs. parent (CodeEntity): This object's parent in the program tree. name (str): The name of the control flow statement in the program.
def __init__(self, scope, parent, name): CodeStatement.__init__(self, scope, parent) self.name = name self.condition = True self.body = CodeBlock(scope, self, explicit=False)
555,535
Constructor for conditionals. Args: scope (CodeEntity): The program scope where this object belongs. parent (CodeEntity): This object's parent in the program tree.
def __init__(self, scope, parent): CodeControlFlow.__init__(self, scope, parent, 'if') self.else_body = CodeBlock(scope, self, explicit=False)
555,538
Constructor for loops. Args: scope (CodeEntity): The program scope where this object belongs. parent (CodeEntity): This object's parent in the program tree. name (str): The name of the loop statement in the program.
def __init__(self, scope, parent, name): CodeControlFlow.__init__(self, scope, parent, name) self.declarations = None self.increment = None
555,545
Constructor for switches. Args: scope (CodeEntity): The program scope where this object belongs. parent (CodeEntity): This object's parent in the program tree.
def __init__(self, scope, parent): CodeControlFlow.__init__(self, scope, parent, "switch") self.cases = [] self.default_case = None
555,550
Constructor for try block structures. Args: scope (CodeEntity): The program scope where this object belongs. parent (CodeEntity): This object's parent in the program tree.
def __init__(self, scope, parent): CodeStatement.__init__(self, scope, parent) self.body = CodeBlock(scope, self, explicit=True) self.catches = [] self.finally_body = CodeBlock(scope, self, explicit=True)
555,552
Is the RecurringCost ready to be enacted as of the date `as_of` This determines if `as_of` precedes the start of `initial_billing_cycle`. If so, we should not be enacting this RecurringCost yet. Args: as_of (Date):
def _is_ready(self, as_of): if self.is_one_off(): return self.initial_billing_cycle.date_range.lower <= as_of else: return True
556,502
Split the value given by amount according to the RecurringCostSplit's portions Args: amount (Decimal): Returns: list[(RecurringCostSplit, Decimal)]: A list with elements in the form (RecurringCostSplit, Decimal)
def split(self, amount): split_objs = list(self.all()) if not split_objs: raise NoSplitsFoundForRecurringCost() portions = [split_obj.portion for split_obj in split_objs] split_amounts = ratio_split(amount, portions) return [ (split_objs[i], spl...
556,507
Populate the table with billing cycles starting from `as_of` Args: as_of (date): The date at which to begin the populating delete (bool): Should future billing cycles be deleted?
def _populate(cls, as_of=None, delete=False): billing_cycle_helper = get_billing_cycle() billing_cycles_exist = BillingCycle.objects.exists() try: current_billing_cycle = BillingCycle.objects.as_of(date=as_of) except BillingCycle.DoesNotExist: current_bi...
556,520
Read contents of the specified file. Parameters: ----------- filename : str The name of the file to be read Returns: lines : list of str The contents of the file, split by line
def read_file(filename): infile = open(filename, 'r') lines = infile.readlines() infile.close() return lines
556,567
i4_sobol_generate generates a Sobol dataset. Parameters: Input, integer dim_num, the spatial dimension. Input, integer N, the number of points to generate. Input, integer SKIP, the number of initial points to skip. Output, real R(M,N), the points.
def i4_sobol_generate(dim_num, n, skip=1): r = np.full((n, dim_num), np.nan) for j in range(n): seed = j + skip r[j, 0:dim_num], next_seed = i4_sobol(dim_num, seed) return r
556,814
Generates multivariate standard normal quasi-random variables. Parameters: Input, integer dim_num, the spatial dimension. Input, integer n, the number of points to generate. Input, integer SKIP, the number of initial points to skip. Output, real np array of shape (n, dim_num).
def i4_sobol_generate_std_normal(dim_num, n, skip=1): sobols = i4_sobol_generate(dim_num, n, skip) normals = norm.ppf(sobols) return normals
556,815
is_prime returns True if N is a prime number, False otherwise Parameters: Input, integer N, the number to be checked. Output, boolean value, True or False
def is_prime(n): if n != int(n) or n < 2: return False if n == 2 or n == 3: return True if n % 2 == 0 or n % 3 == 0: return False # All primes >3 are of the form 6n+1 or 6n+5 (6n, 6n+2, 6n+4 are 2-divisible, 6n+3 is 3-divisible) p = 5 root = int(np.ceil(np.sqrt(n))) ...
556,819
Counts number of satellites used in calculation from total visible satellites Arguments: feed feed=data_stream.TPV['satellites'] Returns: total_satellites(int): used_satellites (int):
def satellites_used(feed): total_satellites = 0 used_satellites = 0 if not isinstance(feed, list): return 0, 0 for satellites in feed: total_satellites += 1 if satellites['used'] is True: used_satellites += 1 return total_satellites, used_satellites
557,058
Connect to a host on a given port. Arguments: host: default host='127.0.0.1' port: default port=2947
def connect(self, host=HOST, port=GPSD_PORT): for alotta_stuff in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM): family, socktype, proto, _canonname, host_port = alotta_stuff try: self.streamSock = socket.socket(family, socktype, proto) se...
557,066
watch gpsd in various gpsd_protocols or devices. Arguments: enable: (bool) stream data to socket gpsd_protocol: (str) 'json' | 'nmea' | 'rare' | 'raw' | 'scaled' | 'split24' | 'pps' devicepath: (str) device path - '/dev/ttyUSBn' for some number n or '/dev/whatever_works' ...
def watch(self, enable=True, gpsd_protocol=PROTOCOL, devicepath=None): # N.B.: 'timing' requires special attention, as it is undocumented and lives with dragons. command = '?WATCH={{"enable":true,"{0}":true}}'.format(gpsd_protocol) if gpsd_protocol == 'rare': # 1 for a channel, gpsd r...
557,067
Ship commands to the daemon Arguments: command: e.g., '?WATCH={{'enable':true,'json':true}}'|'?VERSION;'|'?DEVICES;'|'?DEVICE;'|'?POLL;'
def send(self, command): # The POLL command requests data from the last-seen fixes on all active GPS devices. # Devices must previously have been activated by ?WATCH to be pollable. try: self.streamSock.send(bytes(command, encoding='utf-8')) except TypeError: ...
557,068
Return empty unless new data is ready for the client. Arguments: timeout: Default timeout=0 range zero to float specifies a time-out as a floating point number in seconds. Will sit and wait for timeout seconds. When the timeout argument is omitted the function blocks until at leas...
def next(self, timeout=0): try: waitin, _waitout, _waiterror = select.select((self.streamSock,), (), (), timeout) if not waitin: return else: gpsd_response = self.streamSock.makefile() # '.makefile(buffering=4096)' In strictly Python3 ...
557,069
Sets new socket data as DataStream attributes in those initialised dictionaries Arguments: gpsd_socket_response (json object): Provides: self attribute dictionaries, e.g., self.TPV['lat'], self.SKY['gdop'] Raises: AttributeError: 'str' object has no attribute 'keys' w...
def unpack(self, gpsd_socket_response): try: fresh_data = json.loads(gpsd_socket_response) # The reserved word 'class' is popped from JSON object class package_name = fresh_data.pop('class', 'ERROR') # gpsd data package errors are also 'ERROR'. package = getattr(se...
557,072
Ship commands to the daemon Arguments: commands: e.g., '?WATCH={{'enable':true,'json':true}}'|'?VERSION;'|'?DEVICES;'|'?DEVICE;'|'?POLL;'
def send(self, commands): try: self.streamSock.send(bytes(commands, encoding='utf-8')) except TypeError: self.streamSock.send(commands) # 2.7 chokes on 'bytes' and 'encoding=' except (OSError, IOError) as error: # HEY MOE, LEAVE THIS ALONE FOR NOW! ...
557,073
Sets new socket data as DataStream attributes in those initialised dictionaries Arguments: gpsd_socket_response (json object): Provides: self attributes, e.g., self.lat, self.gdop Raises: AttributeError: 'str' object has no attribute 'keys' when the device falls out o...
def unpack(self, gpsd_socket_response): try: fresh_data = json.loads(gpsd_socket_response) # 'class' is popped for iterator lead class_name = fresh_data.pop('class') for key in self.packages[class_name]: # Fudge around the namespace collision with GS...
557,075
Create a :class:`DocumentTemplate` object based on the given document tree and this template configuration Args: document_tree (DocumentTree): tree of the document's contents backend: the backend to use when rendering the document
def document(self, document_tree, backend=None): return self.template(document_tree, configuration=self, backend=backend)
558,044
Return the font matching or closest to the given style If a font with the given weight, slant and width is available, return it. Otherwise, return the font that is closest in style. Args: weight (FontWeight): weight of the font slant (FontSlant): slant of the font ...
def get_font(self, weight='medium', slant='upright', width='normal'): def find_closest_style(style, styles, alternatives): try: return style, styles[style] except KeyError: for option in alternatives[style]: try: ...
558,166
Find a selector mapped to a style in this or a base style sheet. Args: name (str): a style name Returns: :class:`.Selector`: the selector mapped to the style `name` Raises: KeyError: if the style `name` was not found in this or a base style ...
def get_selector(self, name): try: return self.matcher.by_name[name] except (AttributeError, KeyError): if self.base is not None: return self.base.get_selector(name) else: raise KeyError("No selector found for style '{}'".form...
558,220
Initialise a tidal model. Provide constituents, amplitudes and phases OR a model. Arguments: constituents -- list of constituents used in the model. amplitudes -- list of amplitudes corresponding to constituents phases -- list of phases corresponding to constituents model -- an ndarray of type Tide.dtype repr...
def __init__( self, constituents = None, amplitudes = None, phases = None, model = None, radians = False ): if None not in [constituents, amplitudes, phases]: if len(constituents) == len(amplitudes) == len(phases): model = np.zeros(len(phases), dtype=Tide.dtype) model['constituent'] ...
558,405
Return constituent speed and equilibrium argument at a given time, and constituent node factors at given times. Arguments: constituents -- list of constituents to prepare t0 -- time at which to evaluate speed and equilibrium argument for each constituent t -- list of times at which to evaluate node factors for ...
def _prepare(constituents, t0, t = None, radians = True): #The equilibrium argument is constant and taken at the beginning of the #time series (t0). The speed of the equilibrium argument changes very #slowly, so again we take it to be constant over any length of data. The #node factors change more rapidly. ...
558,407
Return the modelled tidal height at given times. Arguments: t -- array of times at which to evaluate the tidal height
def at(self, t): t0 = t[0] hours = self._hours(t0, t) partition = 240.0 t = self._partition(hours, partition) times = self._times(t0, [(i + 0.5)*partition for i in range(len(t))]) speed, u, f, V0 = self.prepare(t0, times, radians = True) H = self.model['amplitude'][:, np.newaxis] p = d2r*self.model['...
558,408
Generator yielding only the high tides. Arguments: see Tide.extrema()
def highs(self, *args): for t in ifilter(lambda e: e[2] == 'H', self.extrema(*args)): yield t
558,409
Generator yielding only the low tides. Arguments: see Tide.extrema()
def lows(self, *args): for t in ifilter(lambda e: e[2] == 'L', self.extrema(*args)): yield t
558,410
A generator for high and low tides. Arguments: t0 -- time after which extrema are sought t1 -- optional time before which extrema are sought (if not given, the generator is infinite) partition -- number of hours for which we consider the node factors to be constant (default: 2400.0)
def extrema(self, t0, t1 = None, partition = 2400.0): if t1: #yield from in python 3.4 for e in takewhile(lambda t: t[0] < t1, self.extrema(t0)): yield e else: #We assume that extrema are separated by at least delta hours delta = np.amin([ 90.0 / c.speed(astro(t0)) for c in self.model['consti...
558,412