docstring
stringlengths
52
499
function
stringlengths
67
35.2k
__index_level_0__
int64
52.6k
1.16M
Returns the media item with the specified title. Parameters: title (str): Title of the item to return.
def get(self, title): key = '/library/sections/%s/all' % self.key return self.fetchItem(key, title__iexact=title)
402,949
Returns a list of media from this library section. Parameters: sort (string): The sort string
def all(self, sort=None, **kwargs): sortStr = '' if sort is not None: sortStr = '?sort=' + sort key = '/library/sections/%s/all%s' % (self.key, sortStr) return self.fetchItems(key, **kwargs)
402,950
Returns a list of recently added episodes from this library section. Parameters: maxresults (int): Max number of items to return (default 50).
def recentlyAdded(self, libtype='episode', maxresults=50): return self.search(sort='addedAt:desc', libtype=libtype, maxresults=maxresults)
402,961
Returns the :class:`~plexapi.myplex.MyPlexDevice` that matches the name specified. Parameters: name (str): Name to match against.
def device(self, name): for device in self.devices(): if device.name.lower() == name.lower(): return device raise NotFound('Unable to find device %s' % name)
402,975
Returns the :class:`~plexapi.myplex.MyPlexResource` that matches the name specified. Parameters: name (str): Name to match against.
def resource(self, name): for resource in self.resources(): if resource.name.lower() == name.lower(): return resource raise NotFound('Unable to find resource %s' % name)
402,978
Remove the specified user from all sharing. Parameters: user (str): MyPlexUser, username, email of the user to be added.
def removeFriend(self, user): user = self.user(user) url = self.FRIENDUPDATE if user.friend else self.REMOVEINVITE url = url.format(userId=user.id) return self.query(url, self._session.delete)
402,981
Returns the :class:`~plexapi.myplex.MyPlexUser` that matches the email or username specified. Parameters: username (str): Username, email or id of the user to return.
def user(self, username): for user in self.users(): # Home users don't have email, username etc. if username.lower() == user.title.lower(): return user elif (user.username and user.email and user.id and username.lower() in (user.user...
402,983
Returns an instance of :class:`plexapi.sync.SyncList` for specified client. Parameters: client (:class:`~plexapi.myplex.MyPlexDevice`): a client to query SyncItems for. clientId (str): an identifier of a client to query SyncItems for. If both `client` and `clien...
def syncItems(self, client=None, clientId=None): if client: clientId = client.clientIdentifier elif clientId is None: clientId = X_PLEX_IDENTIFIER data = self.query(SyncList.key.format(clientId=clientId)) return SyncList(self, data)
402,992
Yield all paths of the object. Arguments: obj -- An object to get paths from. Keyword Arguments: dirs -- Yield intermediate paths. leaves -- Yield the paths with leaf objects. path -- A list of keys representing the path. skip -- Skip special keys beginning with '+'.
def paths(obj, dirs=True, leaves=True, path=[], skip=False): if isinstance(obj, MutableMapping): # Python 3 support if PY3: iteritems = obj.items() string_class = str else: # Default to PY2 iteritems = obj.iteritems() string_class = basest...
403,026
Match the path with the glob. Arguments: path -- A list of keys representing the path. glob -- A list of globs to match against the path.
def match(path, glob): path_len = len(path) glob_len = len(glob) ss = -1 ss_glob = glob if '**' in glob: ss = glob.index('**') if '**' in glob[ss + 1:]: raise dpath.exceptions.InvalidGlob("Invalid glob. Only one '**' is permitted per glob.") if path_len >= ...
403,027
Get the value of the given path. Arguments: obj -- Object to look in. path -- A list of keys representing the path. Keyword Arguments: view -- Return a view of the object.
def get(obj, path, view=False, afilter=None): index = 0 path_count = len(path) - 1 target = obj head = type(target)() tail = head up = None for pair in path: key = pair[0] target = target[key] if view: if isinstance(tail, MutableMapping): ...
403,029
Returns a response to the user and keeps the current session alive. Expects a response from the user. Arguments: speech {str} -- Text to be pronounced to the user / shown on the screen
def __init__(self, speech, display_text=None, is_ssml=False): super(ask, self).__init__(speech, display_text, is_ssml) self._response["payload"]["google"]["expect_user_response"] = True
403,224
Decorates a function to prompt for an action's required parameter. The wrapped function is called if next_param was not recieved with the given intent's request and is required for the fulfillment of the intent's action. Arguments: next_param {str} -- name of the parameter required...
def prompt_for(self, next_param, intent_name): def decorator(f): prompts = self._intent_prompts.get(intent_name) if prompts: prompts[next_param] = f else: self._intent_prompts[intent_name] = {} self._intent_prompts[int...
403,269
this function will load the functional channel object from a json object and the given groups Args: js(dict): the json object groups(Iterable[Group]): the groups for referencing
def from_json(self, js, groups: Iterable[Group]): self.index = js["index"] self.groupIndex = js["groupIndex"] self.label = js["label"] self.functionalChannelType = FunctionalChannelType.from_str( js["functionalChannelType"], js["functionalChannelType"] ...
406,026
downloads the current configuration and parses it into self Args: clearConfig(bool): if set to true, this function will remove all old objects from self.devices, self.client, ... to have a fresh config instead of reparsing them
def get_current_state(self, clearConfig: bool = False): json_state = self.download_configuration() if "errorCode" in json_state: LOGGER.error( "Could not get the current configuration. Error: %s", json_state["errorCode"], ) ...
406,097
gets the specified functionalHome Args: functionalHome(type): the type of the functionalHome which should be returned Returns: the FunctionalHome or None if it couldn't be found
def get_functionalHome(self, functionalHomeType: type) -> FunctionalHome: for x in self.functionalHomes: if isinstance(x, functionalHomeType): return x return None
406,106
searches a device by given id Args: deviceID(str): the device to search for Returns the Device object or None if it couldn't find a device
def search_device_by_id(self, deviceID) -> Device: for d in self.devices: if d.id == deviceID: return d return None
406,107
searches a group by given id Args: groupID(str): groupID the group to search for Returns the group object or None if it couldn't find a group
def search_group_by_id(self, groupID) -> Group: for g in self.groups: if g.id == groupID: return g return None
406,108
searches a client by given id Args: clientID(str): the client to search for Returns the client object or None if it couldn't find a client
def search_client_by_id(self, clientID) -> Client: for c in self.clients: if c.id == clientID: return c return None
406,109
searches a rule by given id Args: ruleID(str): the rule to search for Returns the rule object or None if it couldn't find a rule
def search_rule_by_id(self, ruleID) -> Rule: for r in self.rules: if r.id == ruleID: return r return None
406,110
activate or deactivate if smoke detectors should "ring" during an alarm Args: activate(bool): True will let the smoke detectors "ring" during an alarm
def set_intrusion_alert_through_smoke_detectors(self, activate: bool = True): data = {"intrusionAlertThroughSmokeDetectors": activate} return self._restCall( "home/security/setIntrusionAlertThroughSmokeDetectors", json.dumps(data) )
406,114
activates the absence mode until the given time Args: endtime(datetime): the time when the absence should automatically be disabled
def activate_absence_with_period(self, endtime: datetime): data = {"endTime": endtime.strftime("%Y_%m_%d %H:%M")} return self._restCall( "home/heating/activateAbsenceWithPeriod", json.dumps(data) )
406,115
activates the absence mode for a given time Args: duration(int): the absence duration in minutes
def activate_absence_with_duration(self, duration: int): data = {"duration": duration} return self._restCall( "home/heating/activateAbsenceWithDuration", json.dumps(data) )
406,116
activates the vatation mode until the given time Args: endtime(datetime): the time when the vatation mode should automatically be disabled temperature(float): the settemperature during the vacation mode
def activate_vacation(self, endtime: datetime, temperature: float): data = { "endtime": endtime.strftime("%Y_%m_%d %H:%M"), "temperature": temperature, } return self._restCall("home/heating/activateVacation", json.dumps(data))
406,117
sets a new pin for the home Args: newPin(str): the new pin oldPin(str): optional, if there is currently a pin active it must be given here. Otherwise it will not be possible to set the new pin Returns: the result of the call
def set_pin(self, newPin: str, oldPin: str = None) -> dict: if newPin == None: newPin = "" data = {"pin": newPin} if oldPin: self._connection.headers["PIN"] = str(oldPin) result = self._restCall("home/setPin", body=json.dumps(data)) if old...
406,118
sets the timezone for the AP. e.g. "Europe/Berlin" Args: timezone(str): the new timezone
def set_timezone(self, timezone: str): data = {"timezoneId": timezone} return self._restCall("home/setTimezone", body=json.dumps(data))
406,122
sets the devices for the security zones Args: internal_devices(List[Device]): the devices which should be used for the internal zone external_devices(List[Device]): the devices which should be used for the external(hull) zone Returns: the result of _re...
def set_zones_device_assignment(self, internal_devices, external_devices) -> dict: internal = [x.id for x in internal_devices] external = [x.id for x in external_devices] data = {"zonesDeviceAssignment": {"INTERNAL": internal, "EXTERNAL": external}} return self._restCall( ...
406,124
sets the color and dimlevel of the lamp Args: channelIndex(int): the channelIndex of the lamp. Use self.topLightChannelIndex or self.bottomLightChannelIndex rgb(RGBColorState): the color of the lamp dimLevel(float): the dimLevel of the lamp. 0.0 = off, 1.0 = MAX Ret...
def set_rgb_dim_level(self, channelIndex: int, rgb: RGBColorState, dimLevel: float): data = { "channelIndex": channelIndex, "deviceId": self.id, "simpleRGBColorState": rgb, "dimLevel": dimLevel, } return self._restCall( "device...
406,281
sets the color and dimlevel of the lamp Args: channelIndex(int): the channelIndex of the lamp. Use self.topLightChannelIndex or self.bottomLightChannelIndex rgb(RGBColorState): the color of the lamp dimLevel(float): the dimLevel of the lamp. 0.0 = off, 1.0 = MAX ...
def set_rgb_dim_level_with_time( self, channelIndex: int, rgb: RGBColorState, dimLevel: float, onTime: float, rampTime: float, ): data = { "channelIndex": channelIndex, "deviceId": self.id, "simpleRGBColorState": rg...
406,282
sets the shutter level Args: level(float): the new level of the shutter. 0.0 = open, 1.0 = closed Returns: the result of the _restCall
def set_shutter_level(self, level=0.0): data = {"channelIndex": 1, "deviceId": self.id, "shutterLevel": level} return self._restCall("device/control/setShutterLevel", body=json.dumps(data))
406,292
sets the slats and shutter level Args: slatsLevel(float): the new level of the slats. 0.0 = open, 1.0 = closed, shutterLevel(float): the new level of the shutter. 0.0 = open, 1.0 = closed, None = use the current value Returns: the result of the _restCall
def set_slats_level(self, slatsLevel=0.0, shutterLevel=None): if shutterLevel is None: shutterLevel = self.shutterLevel data = { "channelIndex": 1, "deviceId": self.id, "slatsLevel": slatsLevel, "shutterLevel": shutterLevel, } ...
406,294
Decrypt a byte message using a RSA private key and the OAEP wrapping algorithm Parameters: public_key - an RSA public key message - a byte string label - a label a per-se PKCS#1 standard hash_class - a Python class for a message digest algorithme respecting the hashli...
def decrypt(private_key, message, label=b'', hash_class=hashlib.sha1, mgf=mgf.mgf1): hash = hash_class() h_len = hash.digest_size k = private_key.byte_size # 1. check length if len(message) != k or k < 2 * h_len + 2: raise ValueError('decryption error') # 2. RSA decrypti...
406,420
Returns a generator that produces a sequence of Entry objects for which the predicate returned True. Args: predicate: A callable that returns a value coercible to bool.
def find_all(self, predicate): for _nid, entry in self._registry.items(): if predicate(entry): yield entry
406,671
This function returns correct YAML representation of a UAVCAN structure (message, request, or response), or a DSDL entity (array or primitive), or a UAVCAN transfer, with comments for human benefit. Args: obj: Object to convert. Returns: Unicode string containing YAML representation of t...
def to_yaml(obj): if not isinstance(obj, CompoundValue) and hasattr(obj, 'transfer'): if hasattr(obj, 'message'): payload = obj.message header = 'Message' elif hasattr(obj, 'request'): payload = obj.request header = 'Request' elif hasattr(...
406,685
Load a lexicon from a JSON file. Args: filename (str): The path to a JSON dump.
def from_json_file(cls, filename): with open(filename, 'r') as fp: return cls(json.load(fp))
407,507
Parse a piece of text and replace any abbreviations with their full word equivalents. Uses the lexicon.abbreviations dictionary to find abbreviations. Args: text (str): The text to parse. Returns: str: The text with abbreviations replaced.
def expand_abbreviations(self, text): if not self.abbreviations: raise LexiconError("No abbreviations in lexicon.") def chunks(data, SIZE=25): it = iter(data) for i in range(0, len(data), SIZE): yield {k: data[k] for k in islice(...
407,510
A slightly easier way to make legends from images. Args: filename (str) components (list) ignore (list): Colours to ignore, e.g. "#FFFFFF" to ignore white. col_offset (Number): If < 1, interpreted as proportion of way across the image. If > 1, int...
def from_image(cls, filename, components, ignore=None, col_offset=0.1, row_offset=2): if ignore is None: ignore = [] rgb = utils.loglike_from_image(filename, offset=col_offset) loglike = np.array([utils.rgb_to_hex(t) ...
407,532
Get the decor for a component. Args: c (component): The component to look up. match_only (list of str): The component attributes to include in the comparison. Default: All of them. Returns: Decor. The matching Decor from the Legend, or None if not found.
def get_decor(self, c, match_only=None): if isinstance(c, Component): if c: if match_only: # Filter the component only those attributes c = Component({k: getattr(c, k, None) for k in match_only}) for decor in self.__lis...
407,536
Get the attribute of a component. Args: c (component): The component to look up. attr (str): The attribute to get. default (str): What to return in the event of no match. match_only (list of str): The component attributes to include in the comparison. ...
def getattr(self, c, attr, default=None, match_only=None): matching_decor = self.get_decor(c, match_only=match_only) try: return getattr(matching_decor, attr) except AttributeError: return default
407,537
Get the component corresponding to a display colour. This is for generating a Striplog object from a colour image of a striplog. Args: colour (str): The hex colour string to look up. tolerance (float): The colourspace distance within which to match. default (component o...
def get_component(self, colour, tolerance=0, default=None): if not (0 <= tolerance <= np.sqrt(195075)): raise LegendError('Tolerance must be between 0 and 441.67') for decor in self.__list: if colour.lower() == decor.colour: return decor.component ...
407,540
Private method. Take a sequence of tops in an arbitrary dimension, and provide a list of intervals from which a striplog can be made. This is only intended to be used by ``from_image()``. Args: tops (iterable). A list of floats. values (iterable). A list of values to lo...
def __intervals_from_tops(self, tops, values, basis, components, field=None, ignore_nan=True): # Scale tops to actual depth...
407,565
Private function. Takes a data dictionary and reconstructs a list of Intervals from it. Args: data_dict (dict) stop (float): Where to end the last interval. points (bool) include (dict) exclude (dict) ignore (list) lexi...
def _build_list_of_Intervals(cls, data_dict, stop=None, points=False, include=None, exclude=None, ignore=None, ...
407,568
Returns a CSV string built from the summaries of the Intervals. Args: use_descriptions (bool): Whether to use descriptions instead of summaries, if available. dlm (str): The delimiter. header (bool): Whether to form a header row. Returns: ...
def to_csv(self, filename=None, as_text=True, use_descriptions=False, dlm=",", header=True): if (filename is None): if (not as_text): raise StriplogError("You must provide a filename or set as_text to...
407,578
Returns an LAS 3.0 section string. Args: use_descriptions (bool): Whether to use descriptions instead of summaries, if available. dlm (str): The delimiter. source (str): The sourse of the data. Returns: str: A string forming Lithology sec...
def to_las3(self, use_descriptions=False, dlm=",", source="Striplog"): data = self.to_csv(use_descriptions=use_descriptions, dlm=dlm, header=False) return templates.section.format(name='Lithology', sh...
407,579
Get the index of the interval at a particular 'depth' (though this might be an elevation or age or anything). Args: d (Number): The 'depth' to query. index (bool): Whether to return the index instead of the interval. Returns: Interval: The interval, or i...
def read_at(self, d, index=False): for i, iv in enumerate(self): if iv.spans(d): return i if index else iv return None
407,588
Private method. Finds gaps and overlaps in a striplog. Called by find_gaps() and find_overlaps(). Args: op (operator): ``operator.gt`` or ``operator.lt`` index (bool): If ``True``, returns indices of intervals with gaps after them. Returns: Strip...
def __find_incongruities(self, op, index): if len(self) == 1: return hits = [] intervals = [] if self.order == 'depth': one, two = 'base', 'top' else: one, two = 'top', 'base' for i, iv in enumerate(self[:-1]): n...
407,592
Find overlaps in a striplog. Args: index (bool): If True, returns indices of intervals with gaps after them. Returns: Striplog: A striplog of all the overlaps as intervals.
def find_overlaps(self, index=False): return self.__find_incongruities(op=operator.gt, index=index)
407,593
Finds gaps in a striplog. Args: index (bool): If True, returns indices of intervals with gaps after them. Returns: Striplog: A striplog of all the gaps. A sort of anti-striplog.
def find_gaps(self, index=False): return self.__find_incongruities(op=operator.lt, index=index)
407,594
Remove intervals below a certain limit thickness. In place. Args: limit (float): Anything thinner than this will be pruned. n (int): The n thinnest beds will be pruned. percentile (float): The thinnest specified percentile will be pruned. keep_end...
def prune(self, limit=None, n=None, percentile=None, keep_ends=False): strip = self.copy() if not (limit or n or percentile): m = "You must provide a limit or n or percentile for pruning." raise StriplogError(m) if limit: prune = [i for i, iv in enum...
407,595
Makes a striplog of all unions. Args: Striplog. The striplog instance to union with. Returns: Striplog. The result of the union.
def union(self, other): if not isinstance(other, self.__class__): m = "You can only union striplogs with each other." raise StriplogError(m) result = [] for iv in deepcopy(self): for jv in other: if iv.any_overlaps(jv): ...
407,598
Makes a striplog of all intersections. Args: Striplog. The striplog instance to intersect with. Returns: Striplog. The result of the intersection.
def intersect(self, other): if not isinstance(other, self.__class__): m = "You can only intersect striplogs with each other." raise StriplogError(m) result = [] for iv in self: for jv in other: try: result.append(i...
407,599
Returns the thickest interval(s) as a striplog. Args: n (int): The number of thickest intervals to return. Default: 1. index (bool): If True, only the indices of the intervals are returned. You can use this to index into the striplog. Returns: Interv...
def thickest(self, n=1, index=False): s = sorted(range(len(self)), key=lambda k: self[k].thickness) indices = s[-n:] if index: return indices else: if n == 1: # Then return an interval. i = indices[0] return...
407,602
Inverts the striplog, changing its order and the order of its contents. Operates in place by default. Args: copy (bool): Whether to operate in place or make a copy. Returns: None if operating in-place, or an inverted copy of the striplog if not.
def invert(self, copy=False): if copy: return Striplog([i.invert(copy=True) for i in self]) else: for i in self: i.invert() self.__sort() o = self.order self.order = {'depth': 'elevation', 'elevation': 'depth'}[o] ...
407,605
Crop to a new depth range. Args: extent (tuple): The new start and stop depth. Must be 'inside' existing striplog. copy (bool): Whether to operate in place or make a copy. Returns: Operates in place by deault; if copy is True, returns a striplog.
def crop(self, extent, copy=False): try: if extent[0] is None: extent = (self.start.z, extent[1]) if extent[1] is None: extent = (extent[0], self.stop.z) except: m = "You must provide a 2-tuple for the new extents. Use None for...
407,606
Run a series of tests and return the corresponding results. Based on curve testing for ``welly``. Args: tests (list): a list of functions. Returns: list. The results. Stick to booleans (True = pass) or ints.
def quality(self, tests, alias=None): # This is hacky... striplog should probably merge with welly... # Ignore aliases alias = alias or {} alias = alias.get('striplog', alias.get('Striplog', [])) # Gather the tests. # First, anything called 'all', 'All', or 'AL...
407,607
Convert hex to a color name, using matplotlib's colour names. Args: hexx (str): A hexadecimal colour, starting with '#'. Returns: str: The name of the colour, or None if not found.
def hex_to_name(hexx): for n, h in defaults.COLOURS.items(): if (len(n) > 1) and (h == hexx.upper()): return n.lower() return None
407,611
Utility function to convert (r,g,b) triples to hex. http://ageo.co/1CFxXpO Args: rgb (tuple): A sequence of RGB values in the range 0-255 or 0-1. Returns: str: The hex code for the colour.
def rgb_to_hex(rgb): r, g, b = rgb[:3] if (r < 0) or (g < 0) or (b < 0): raise Exception("RGB values must all be 0-255 or 0-1") if (r > 255) or (g > 255) or (b > 255): raise Exception("RGB values must all be 0-255 or 0-1") if (0 < r < 1) or (0 < g < 1) or (0 < b < 1): ...
407,612
Take a log-like stream of numbers or strings, and return two arrays: one of the tops (changes), and one of the values from the stream. Args: loglike (array-like): The input stream of loglike data. offset (int): Offset (down) from top at which to get lithology, to be sure of getting ...
def tops_from_loglike(a, offset=0, null=None): a = np.copy(a) try: contains_nans = np.isnan(a).any() except: contains_nans = False if contains_nans: # Find a null value that's not in the log, and apply it if possible. _null = null or -1 while _null in a: ...
407,614
Lists all the jobs registered with Nomad. https://www.nomadproject.io/docs/http/jobs.html arguments: - prefix :(str) optional, specifies a string to filter jobs on based on an prefix. This is specified as a querystring parameter. returns: list ...
def get_jobs(self, prefix=None): params = {"prefix": prefix} return self.request(method="get", params=params).json()
407,653
Update token. https://www.nomadproject.io/api/acl-tokens.html arguments: - AccdesorID - token returns: dict raises: - nomad.api.exceptions.BaseNomadException - nomad.api.exceptions.URLNotFoundNomadException
def update_token(self, id, token): return self.request("token", id, json=token, method="post").json()
407,655
Create policy. https://www.nomadproject.io/api/acl-policies.html arguments: - policy returns: request.Response raises: - nomad.api.exceptions.BaseNomadException - nomad.api.exceptions.URLNotFoundNomadException
def create_policy(self, id, policy): return self.request("policy", id, json=policy, method="post")
407,656
Create policy. https://www.nomadproject.io/api/acl-policies.html arguments: - name - policy returns: request.Response raises: - nomad.api.exceptions.BaseNomadException - nomad.api.exceptions.URLNotFoundNomadEx...
def update_policy(self, id, policy): return self.request("policy", id, json=policy, method="post")
407,657
Lists all the allocations. https://www.nomadproject.io/docs/http/allocs.html arguments: - prefix :(str) optional, specifies a string to filter allocations on based on an prefix. This is specified as a querystring parameter. returns: list ...
def get_allocations(self, prefix=None): params = {"prefix": prefix} return self.request(method="get", params=params).json()
407,658
This endpoint is used to mark a deployment as failed. This should be done to force the scheduler to stop creating allocations as part of the deployment or to cause a rollback to a previous job version. https://www.nomadproject.io/docs/http/deployments.html arguments: -...
def fail_deployment(self, id): fail_json = {"DeploymentID": id} return self.request("fail", id, json=fail_json, method="post").json()
407,661
This endpoint is used to pause or unpause a deployment. This is done to pause a rolling upgrade or resume it. https://www.nomadproject.io/docs/http/deployments.html arguments: - id - pause, Specifies whether to pause or resume the deployment. ...
def pause_deployment(self, id, pause): pause_json = {"Pause": pause, "DeploymentID": id} return self.request("pause", id, json=pause_json, method="post").json()
407,662
Toggle the eligibility of the node. https://www.nomadproject.io/docs/http/node.html arguments: - id (str uuid): node id - eligible (bool): Set to True to mark node eligible - ineligible (bool): Set to True to mark node ineligible returns: di...
def eligible_node(self, id, eligible=None, ineligible=None): payload = {} if eligible is not None and ineligible is not None: raise nomad.api.exceptions.InvalidParameters if eligible is None and ineligible is None: raise nomad.api.exceptions.InvalidParameters ...
407,670
List files in an allocation directory. https://www.nomadproject.io/docs/http/client-fs-ls.html arguments: - id - path returns: list raises: - nomad.api.exceptions.BaseNomadException - nomad.api.exceptions....
def list_files(self, id=None, path="/"): if id: return self.request(id, params={"path": path}, method="get").json() else: return self.request(params={"path": path}, method="get").json()
407,672
Read contents of a file in an allocation directory. https://www.nomadproject.io/docs/http/client-fs-cat.html arguments: - id - path returns: (str) text raises: - nomad.api.exceptions.BaseNomadException - nomad.api.e...
def read_file(self, id=None, path="/"): if id: return self.request(id, params={"path": path}, method="get").text else: return self.request(params={"path": path}, method="get").text
407,673
Read contents of a file in an allocation directory. https://www.nomadproject.io/docs/http/client-fs-cat.html arguments: - id: (str) allocation_id required - offset: (int) required - limit: (int) required - path: (str) optional ...
def read_file_offset(self, id, offset, limit, path="/"): params = { "path": path, "offset": offset, "limit": limit } return self.request(id, params=params, method="get").text
407,674
Stat a file in an allocation directory. https://www.nomadproject.io/docs/http/client-fs-stat.html arguments: - id - path returns: dict raises: - nomad.api.exceptions.BaseNomadException - nomad.api.exceptions.URLNotF...
def stat_file(self, id=None, path="/"): if id: return self.request(id, params={"path": path}, method="get").json() else: return self.request(params={"path": path}, method="get").json()
407,677
Lists all the client nodes registered with Nomad. https://www.nomadproject.io/docs/http/nodes.html arguments: - prefix :(str) optional, specifies a string to filter nodes on based on an prefix. This is specified as a querystring parameter. return...
def get_nodes(self, prefix=None): params = {"prefix": prefix} return self.request(method="get", params=params).json()
407,694
Lists all the evaluations. https://www.nomadproject.io/docs/http/evals.html arguments: - prefix :(str) optional, specifies a string to filter evaluations on based on an prefix. This is specified as a querystring parameter. returns: list ...
def get_evaluations(self, prefix=None): params = {"prefix": prefix} return self.request(method="get", params=params).json()
407,697
Lists all the namespaces registered with Nomad. https://www.nomadproject.io/docs/enterprise/namespaces/index.html arguments: - prefix :(str) optional, specifies a string to filter namespaces on based on an prefix. This is specified as a querystring parameter...
def get_namespaces(self, prefix=None): params = {"prefix": prefix} return self.request(method="get", params=params).json()
407,702
Registers a new job or updates an existing job https://www.nomadproject.io/docs/http/job.html arguments: - id returns: dict raises: - nomad.api.exceptions.BaseNomadException - nomad.api.exceptions.URLNotFoundNomadException
def register_job(self, id, job): return self.request(id, json=job, method="post").json()
407,706
Invoke a dry-run of the scheduler for the job. https://www.nomadproject.io/docs/http/job.html arguments: - id - job, dict - diff, boolean - policy_override, boolean returns: dict raises: - nomad.api.ex...
def plan_job(self, id, job, diff=False, policy_override=False): json_dict = {} json_dict.update(job) json_dict.setdefault('Diff', diff) json_dict.setdefault('PolicyOverride', policy_override) return self.request(id, "plan", json=json_dict, method="post").json()
407,707
Dispatches a new instance of a parameterized job. https://www.nomadproject.io/docs/http/job.html arguments: - id - payload - meta returns: dict raises: - nomad.api.exceptions.BaseNomadException - nomad...
def dispatch_job(self, id, payload=None, meta=None): dispatch_json = {"Meta": meta, "Payload": payload} return self.request(id, "dispatch", json=dispatch_json, method="post").json()
407,708
This endpoint sets the job's stability. https://www.nomadproject.io/docs/http/job.html arguments: - id - version, Specifies the job version to revert to. - stable, Specifies whether the job should be marked as stable or not. returns: dict ...
def stable_job(self, id, version, stable): revert_json = {"JobID": id, "JobVersion": version, "Stable": stable} return self.request(id, "stable", json=revert_json, method="post").json()
407,710
Update namespace https://www.nomadproject.io/api/namespaces.html arguments: - id - namespace (dict) returns: requests.Response raises: - nomad.api.exceptions.BaseNomadException - nomad.api.exceptions.URLNotFoundNoma...
def update_namespace(self, id, namespace): return self.request(id, json=namespace, method="post")
407,722
Ensures the text passed in becomes unicode Args: text (str|unicode) Returns: unicode
def _ensure_unicode(text): if isinstance(text, six.binary_type): return text.decode(sys.getfilesystemencoding(), 'replace') else: return text
407,924
Frequency shift from lowest order diagram is calculated. Args: epslins(list of float): The value to avoid divergence. When multiple values are given frequency shifts for those values are returned.
def get_frequency_shift( self, grid_points, temperatures=np.arange(0, 1001, 10, dtype='double'), epsilons=None, output_filename=None): if self._interaction is None: self.set_phph_interaction() if epsilons is None: ...
408,711
Save stream to the local filesystem. Args: target (str): Path where to save the stream. format (str, optional): The format the stream will be saved as. If None, detects from the ``target`` path. Defaults to None. encoding (str, optional): Saved file encoding....
def save(self, target, format=None, encoding=None, **options): # Get encoding/format if encoding is None: encoding = config.DEFAULT_ENCODING if format is None: _, format = helpers.detect_scheme_and_format(target) # Prepare writer class writer_c...
408,951
Construct the HTTP handler. Args: options (:class:`nyawc.Options`): The settins/options object. queue_item (:class:`nyawc.QueueItem`): The queue item containing the request.
def __init__(self, options, queue_item): self.__options = options self.__queue_item = queue_item self.__queue_item.response = self.__make_request( self.__queue_item.request.url, self.__queue_item.request.method, self.__queue_item.request.data, ...
409,286
Check if the given content type matches one of the available content types. Args: content_type (str): The given content type. available_content_types list(str): All the available content types. Returns: bool: True if a match was found, False otherwise.
def __content_type_matches(self, content_type, available_content_types): if content_type is None: return False if content_type in available_content_types: return True for available_content_type in available_content_types: if available_content_type ...
409,291
Increase the count that determines how many times a URL of a certain route has been crawled. Args: crawled_request (:class:`nyawc.http.Request`): The request that possibly matches a route.
def increase_route_count(self, crawled_request): for route in self.__routing_options.routes: if re.compile(route).match(crawled_request.url): count_key = str(route) + crawled_request.method if count_key in self.__routing_count.keys(): ...
409,293
Check if similar requests to the given requests have already been crawled X times. Where X is the minimum treshold amount from the options. Args: scraped_request (:class:`nyawc.http.Request`): The request that possibly reached the minimum treshold. Returns: bool: True ...
def is_treshold_reached(self, scraped_request): for route in self.__routing_options.routes: if re.compile(route).match(scraped_request.url): count_key = str(route) + scraped_request.method if count_key in self.__routing_count.keys(): ret...
409,294
Constructs a Queue instance. Args: options (:class:`nyawc.Options`): The options to use.
def __init__(self, options): self.__options = options self.count_total = 0 self.items_queued = OrderedDict() self.items_in_progress = OrderedDict() self.items_finished = OrderedDict() self.items_cancelled = OrderedDict() self.items_errored = OrderedDict(...
409,295
Add a request to the queue. Args: request (:class:`nyawc.http.Request`): The request to add. Returns: :class:`nyawc.QueueItem`: The created queue item.
def add_request(self, request): queue_item = QueueItem(request, Response(request.url)) self.add(queue_item) return queue_item
409,296
Check if the given request already exists in the queue. Args: request (:class:`nyawc.http.Request`): The request to check. Returns: bool: True if already exists, False otherwise.
def has_request(self, request): queue_item = QueueItem(request, Response(request.url)) key = queue_item.get_hash() for status in QueueItem.STATUSES: if key in self.__get_var("items_" + status).keys(): return True return False
409,297
Add a request/response pair to the queue. Args: queue_item (:class:`nyawc.QueueItem`): The queue item to add.
def add(self, queue_item): hash_key = queue_item.get_hash() items = self.__get_var("items_" + queue_item.status) if hash_key in items.keys(): return items[queue_item.get_hash()] = queue_item self.count_total += 1
409,298
Move a request/response pair to another status. Args: queue_item (:class:`nyawc.QueueItem`): The queue item to move status (str): The new status of the queue item.
def move(self, queue_item, status): items = self.__get_var("items_" + queue_item.status) del items[queue_item.get_hash()] self.count_total -= 1 queue_item.status = status self.add(queue_item)
409,299
Move a bulk of request/response pairs to another status Args: from_statuses list(str): The statuses to move from to_status (str): The status to move to
def move_bulk(self, from_statuses, to_status): for status in from_statuses: from_status_items = self.__get_var("items_" + status) self.__set_var("items_" + status, OrderedDict()) to_status_items = self.__get_var("items_" + to_status) to_status_items.upd...
409,300
Get the first item in the queue that has the given status. Args: status (str): return the first item with this status. Returns: :class:`nyawc.QueueItem`: The first queue item with the given status.
def get_first(self, status): items = self.get_all(status) if items: return list(items.items())[0][1] return None
409,301
Get a random string for the given html input type Args: input_type (str): The input type (e.g. email). Returns: str: The (cached) random value.
def get_for_type(input_type="text"): if input_type in RandomInputHelper.cache: return RandomInputHelper.cache[input_type] types = { "text": RandomInputHelper.get_random_value, "hidden": RandomInputHelper.get_random_value, "search": RandomInputHe...
409,303
Get a random string with the given length. Args: length (int): The length of the string to return. character_sets list(str): The caracter sets to use. Returns: str: The random string.
def get_random_value(length=10, character_sets=[string.ascii_uppercase, string.ascii_lowercase]): return "".join(random.choice("".join(character_sets)) for i in range(length))
409,304
Get a random email address with the given ltd. Args: ltd (str): The ltd to use (e.g. com). Returns: str: The random email.
def get_random_email(ltd="com"): email = [ RandomInputHelper.get_random_value(6, [string.ascii_lowercase]), "@", RandomInputHelper.get_random_value(6, [string.ascii_lowercase]), ".", ltd ] return "".join(email)
409,305
Get a random url with the given ltd. Args: ltd (str): The ltd to use (e.g. com). Returns: str: The random url.
def get_random_url(ltd="com"): url = [ "https://", RandomInputHelper.get_random_value(8, [string.ascii_lowercase]), ".", ltd ] return "".join(url)
409,307
Patch the given request with the given options (e.g. user agent). Args: request (:class:`nyawc.http.Request`): The request to patch. options (:class:`nyawc.Options`): The options to patch the request with. parent_queue_item (:class:`nyawc.QueueItem`): The parent queue item o...
def patch_with_options(request, options, parent_queue_item=None): request.auth = copy.deepcopy(options.identity.auth) request.cookies = copy.deepcopy(options.identity.cookies) request.headers = copy.deepcopy(options.identity.headers) request.proxies = copy.deepcopy(options.iden...
409,309
Check if the new request complies with the crawling scope. Args: queue_item (:class:`nyawc.QueueItem`): The parent queue item of the new request. new_request (:class:`nyawc.http.Request`): The request to check. scope (:class:`nyawc.Options.OptionsScope`): The scope to check....
def complies_with_scope(queue_item, new_request, scope): if not URLHelper.is_parsable(queue_item.request.url): return False if not URLHelper.is_parsable(new_request.url): return False if scope.request_methods: if not queue_item.request.method in sc...
409,310
Convert a requests cookie jar to a HTTP request cookie header value. Args: queue_item (:class:`nyawc.QueueItem`): The parent queue item of the new request. Returns: str: The HTTP cookie header value.
def get_cookie_header(queue_item): header = [] path = URLHelper.get_path(queue_item.request.url) for cookie in queue_item.request.cookies: root_path = cookie.path == "" or cookie.path == "/" if path.startswith(cookie.path) or root_path: header.a...
409,311
Constructs a QueueItem instance. Args: request (:class:`nyawc.http.Request`): The Request object. response (:class:`nyawc.http.Response`): The Response object (empty object when initialized).
def __init__(self, request, response): self.status = QueueItem.STATUS_QUEUED self.decomposed = False self.__response_soup = None self.__index_hash = None self.request = request self.response = response
409,314