Search is not available for this dataset
text
stringlengths
75
104k
def axis_transform(ax, x, y, xlim=None, ylim=None, inverse=False): """ http://stackoverflow.com/questions/29107800 inverse = False : Axis => Data = True : Data => Axis """ xlim = xlim or ax.get_xlim() ylim = ylim or ax.get_ylim() xdelta = xlim[1] - xlim[0] ydelta = ylim[1]...
def get_field(self, field_name, args, kwargs): """ Return an underscore if the attribute is absent. Not all components have the same attributes. """ try: s = super(CustomFormatter, self) return s.get_field(field_name, args, kwargs) except KeyError:...
def convert_field(self, value, conversion): """ Define some extra field conversion functions. """ try: # If the normal behaviour works, do it. s = super(CustomFormatter, self) return s.convert_field(value, conversion) except ValueError: funcs ...
def get_jobs(self, prefix=None): """ 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 querys...
def parse(self, hcl, canonicalize=False): """ Parse a HCL Job file. Returns a dict with the JSON formatted job. This API endpoint is only supported from Nomad version 0.8.3. https://www.nomadproject.io/api/jobs.html#parse-job returns: dict raises: ...
def update_token(self, id, token): """ Update token. https://www.nomadproject.io/api/acl-tokens.html arguments: - AccdesorID - token returns: dict raises: - nomad.api.exceptions.BaseNomadException - no...
def create_policy(self, id, policy): """ Create policy. https://www.nomadproject.io/api/acl-policies.html arguments: - policy returns: request.Response raises: - nomad.api.exceptions.BaseNomadException - nomad.api.exc...
def update_policy(self, id, policy): """ Create policy. https://www.nomadproject.io/api/acl-policies.html arguments: - name - policy returns: request.Response raises: - nomad.api.exceptions.BaseNomadException ...
def get_allocations(self, prefix=None): """ 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 query...
def fail_deployment(self, id): """ 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.h...
def pause_deployment(self, id, pause): """ 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 whet...
def promote_deployment_all(self, id, all=True): """ This endpoint is used to promote task groups that have canaries for a deployment. This should be done when the placed canaries are healthy and the rolling upgrade of the remaining allocations should begin. https://www.nomadproject.io/do...
def promote_deployment_groups(self, id, groups=list()): """ This endpoint is used to promote task groups that have canaries for a deployment. This should be done when the placed canaries are healthy and the rolling upgrade of the remaining allocations should begin. https://www.nomadproje...
def deployment_allocation_health(self, id, healthy_allocations=list(), unhealthy_allocations=list()): """ This endpoint is used to set the health of an allocation that is in the deployment manually. In some use cases, automatic detection of allocation health may not be desired. As such those task gr...
def drain_node(self, id, enable=False): """ Toggle the drain mode of the node. When enabled, no further allocations will be assigned and existing allocations will be migrated. https://www.nomadproject.io/docs/http/node.html arguments: - id (str uuid...
def drain_node_with_spec(self, id, drain_spec, mark_eligible=None): """ This endpoint toggles the drain mode of the node. When draining is enabled, no further allocations will be assigned to this node, and existing allocations will be migrated to new nodes. If an empty dicti...
def eligible_node(self, id, eligible=None, ineligible=None): """ 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 - ineli...
def list_files(self, id=None, path="/"): """ 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.Bas...
def read_file(self, id=None, path="/"): """ 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.excep...
def read_file_offset(self, id, offset, limit, path="/"): """ 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 - li...
def stream(self, id, offset, origin, path="/"): """ This endpoint streams the contents of a file in an allocation directory. https://www.nomadproject.io/api/client.html#stream-file arguments: - id: (str) allocation_id required - offset: (int) required ...
def stream(self, id, task, type, follow=False, offset=0, origin="start", plain=False): """ This endpoint streams a task's stderr/stdout logs. https://www.nomadproject.io/api/client.html#stream-logs arguments: - id: (str) allocation_id required - task: (str) ...
def stat_file(self, id=None, path="/"): """ 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.BaseNomadEx...
def join_agent(self, addresses): """Initiate a join between the agent and target peers. https://www.nomadproject.io/docs/http/agent-join.html returns: dict raises: - nomad.api.exceptions.BaseNomadException - nomad.api.exceptions.URLNotFoundNomadEx...
def update_servers(self, addresses): """Updates the list of known servers to the provided list. Replaces all previous server addresses with the new list. https://www.nomadproject.io/docs/http/agent-servers.html returns: 200 status code raises: - noma...
def force_leave(self, node): """Force a failed gossip member into the left state. https://www.nomadproject.io/docs/http/agent-force-leave.html returns: 200 status code raises: - nomad.api.exceptions.BaseNomadException - nomad.api.exceptions.URLNo...
def get_nodes(self, prefix=None): """ 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 ...
def get_evaluations(self, prefix=None): """ 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 querys...
def get_namespaces(self, prefix=None): """ 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. ...
def register_job(self, id, job): """ 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.ap...
def plan_job(self, id, job, diff=False, policy_override=False): """ 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, boolea...
def dispatch_job(self, id, payload=None, meta=None): """ Dispatches a new instance of a parameterized job. https://www.nomadproject.io/docs/http/job.html arguments: - id - payload - meta returns: dict raises: ...
def revert_job(self, id, version, enforce_prior_version=None): """ This endpoint reverts the job to an older version. https://www.nomadproject.io/docs/http/job.html arguments: - id - version, Specifies the job version to revert to. optional_argume...
def stable_job(self, id, version, stable): """ 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 b...
def deregister_job(self, id, purge=None): """ Deregisters a job, and stops all allocations part of it. https://www.nomadproject.io/docs/http/job.html arguments: - id - purge (bool), optionally specifies whether the job should be stopped and pu...
def get_configuration(self, stale=False): """ Query the status of a client node registered with Nomad. https://www.nomadproject.io/docs/http/operator.html returns: dict optional arguments: - stale, (defaults to False), Specifies if the cluster should respond w...
def delete_peer(self, peer_address, stale=False): """ Remove the Nomad server with given address from the Raft configuration. The return code signifies success or failure. https://www.nomadproject.io/docs/http/operator.html arguments: - peer_address, The addre...
def get_deployments(self, prefix=""): """ This endpoint lists all deployments. https://www.nomadproject.io/docs/http/deployments.html optional_arguments: - prefix, (default "") Specifies a string to filter deployments on based on an index prefix. Th...
def update_namespace(self, id, namespace): """ Update namespace https://www.nomadproject.io/api/namespaces.html arguments: - id - namespace (dict) returns: requests.Response raises: - nomad.api.exceptions.BaseNomadExcepti...
def _get_random(self, obj_type): """ Get a random mutator from a list of mutators """ return self.mutator[obj_type][random.randint(0, self.config.level)]
def get_mutator(self, obj, obj_type): """ Get a random mutator for the given type """ if obj_type == unicode: obj_type = str obj = str(obj) return self._get_random(obj_type)(obj)
def get_string_polyglot_attack(self, obj): """ Return a polyglot attack containing the original object """ return self.polyglot_attacks[random.choice(self.config.techniques)] % obj
def fuzz(self, obj): """ Perform the fuzzing """ buf = list(obj) FuzzFactor = random.randrange(1, len(buf)) numwrites=random.randrange(math.ceil((float(len(buf)) / FuzzFactor)))+1 for j in range(numwrites): self.random_action(buf) return self.s...
def random_action(self, b): """ Perform the actual fuzzing using random strategies """ action = random.choice([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) if len(b) >= 3: pos = random.randint(0, len(b)-2) if action == 1: rbyte = random.randrange(256) ...
def safe_unicode(self, buf): """ Safely return an unicode encoded string """ tmp = "" buf = "".join(b for b in buf) for character in buf: tmp += character return tmp
def run(self): """ Start the servers """ route("/")(self.serve) if self.config.html: route("/<filepath:path>")(self.custom_html) if self.config.fuzz_web: self.request_checker.start() self.httpd.start() self.httpsd.start()
def stop(self): """ Kill the servers """ os.kill(self.httpd.pid, signal.SIGKILL) os.kill(self.httpsd.pid, signal.SIGKILL) self.client_queue.put((0,0)) if self.config.fuzz_web: self.request_checker.join() self.logger.debug("[{0}] - PJFServer suc...
def custom_html(self, filepath): """ Serve custom HTML page """ try: response.headers.append("Access-Control-Allow-Origin", "*") response.headers.append("Accept-Encoding", "identity") response.headers.append("Content-Type", "text/html") ret...
def serve(self): """ Serve fuzzed JSON object """ try: fuzzed = self.json.fuzzed if self.config.fuzz_web: self.client_queue.put((request.environ.get('REMOTE_ADDR'), fuzzed)) response.headers.append("Access-Control-Allow-Origin", "*") ...
def apply_patch(self): """ Fix default socket lib to handle client disconnection while receiving data (Broken pipe) """ if sys.version_info >= (3, 0): # No patch for python >= 3.0 pass else: from .patch.socket import socket as patch ...
def fuzz(self, obj): """ Generic fuzz mutator, use a decorator for the given type """ decorators = self.decorators @decorators.mutate_object_decorate def mutate(): return obj return mutate()
def spawn(self, cmd, stdin_content="", stdin=False, shell=False, timeout=2): """ Spawn a new process using subprocess """ try: if type(cmd) != list: raise PJFInvalidType(type(cmd), list) if type(stdin_content) != str: raise PJFInval...
def get_output(self, stdin_content, stdin): """ Try to get output in a separate thread """ try: if stdin: if sys.version_info >= (3, 0): self.process.stdin.write(bytes(stdin_content, "utf-8")) else: self....
def finish_read(self, timeout=2, stdin_content="", stdin=False): """ Wait until we got output or until timeout is over """ process = Thread(target=self.get_output, args=(stdin_content, stdin)) process.start() if timeout > 0: process.join(timeout) else:...
def close(self): """ Terminate the newly created process """ try: self.process.terminate() self.return_code = self.process.returncode except OSError: pass self.process.stdin.close() self.process.stdout.close() self.proce...
def start(self): """ Parse the command line and start PyJFuzz """ from .pjf_worker import PJFWorker worker = PJFWorker(self) if self.update_pjf: worker.update_library() elif self.browser_auto: worker.browser_autopwn() elif self.fuzz...
def val(val, pre=None, shortest=False): """Build the provided value, while properly handling native Python types, :any:`gramfuzz.fields.Field` instances, and :any:`gramfuzz.fields.Field` subclasses. :param list pre: The prerequisites list :returns: str """ if pre is None: pre = [] ...
def execute(self, obj): """ Perform the actual external fuzzing, you may replace this method in order to increase performance """ try: if self.config.stdin: self.spawn(self.config.command, stdin_content=obj, stdin=True, timeout=1) else: ...
def json_encode(func): """ Decorator used to change the return value from PJFFactory.fuzzed, it makes the structure printable """ def func_wrapper(self, indent, utf8): if utf8: encoding = "\\x%02x" else: encoding = "\\u%04x" ...
def _odds_val(self): """Determine a new random value derived from the defined :any:`gramfuzz.fields.Field.odds` value. :returns: The derived value """ if len(self.odds) == 0: self.odds = [(1.00, [self.min, self.max])] rand_val = rand.random() total =...
def build(self, pre=None, shortest=False): """Build the integer, optionally providing a ``pre`` list that *may* be used to define prerequisites for a Field being built. :param list pre: A list of prerequisites to be collected during the building of a Field. :param bool shortest: Whether...
def build(self, pre=None, shortest=False): """Build the String instance :param list pre: The prerequisites list (optional, default=None) :param bool shortest: Whether or not the shortest reference-chain (most minimal) version of the field should be generated. """ if pre is None:...
def build(self, pre=None, shortest=False): """Build the ``Join`` field instance. :param list pre: The prerequisites list :param bool shortest: Whether or not the shortest reference-chain (most minimal) version of the field should be generated. """ if pre is None: ...
def build(self, pre=None, shortest=False): """Build the ``And`` instance :param list pre: The prerequisites list :param bool shortest: Whether or not the shortest reference-chain (most minimal) version of the field should be generated. """ if pre is None: pre = [] ...
def build(self, pre=None, shortest=False): """Build the ``Quote`` instance :param list pre: The prerequisites list :param bool shortest: Whether or not the shortest reference-chain (most minimal) version of the field should be generated. """ res = super(Q, self).build(pre, short...
def build(self, pre=None, shortest=False): """Build the ``Or`` instance :param list pre: The prerequisites list :param bool shortest: Whether or not the shortest reference-chain (most minimal) version of the field should be generated. """ if pre is None: pre = [] ...
def build(self, pre=None, shortest=False): """Build the current ``Opt`` instance :param list pre: The prerequisites list :param bool shortest: Whether or not the shortest reference-chain (most minimal) version of the field should be generated. """ if pre is None: pre...
def build(self, pre=None, shortest=False): """Build this rule definition :param list pre: The prerequisites list :param bool shortest: Whether or not the shortest reference-chain (most minimal) version of the field should be generated. """ if pre is None: pre...
def build(self, pre=None, shortest=False): """Build the ``Ref`` instance by fetching the rule from the GramFuzzer instance and building it :param list pre: The prerequisites list :param bool shortest: Whether or not the shortest reference-chain (most minimal) version of the field should...
def build(self, pre=None, shortest=False): """Build the STAR field. :param list pre: The prerequisites list :param bool shortest: Whether or not the shortest reference-chain (most minimal) version of the field should be generated. """ if pre is None: pre = [] ...
def shutdown(self, *args): """ Shutdown the running process and the monitor """ try: self._shutdown() if self.process: self.process.wait() self.process.stdout.close() self.process.stdin.close() self.p...
def run_and_monitor(self): """ Run command once and check exit code """ signal.signal(signal.SIGINT, self.shutdown) self.spawn(self.config.process_to_monitor, timeout=0) return self._is_sigsegv(self.return_code)
def start_monitor(self, standalone=True): """ Run command in a loop and check exit status plus restart process when needed """ try: self.start() cmdline = shlex.split(self.config.process_to_monitor) if standalone: signal.signal(signal.S...
def randfloat(a, b=None): """Return a random float :param float a: Either the minimum value (inclusive) if ``b`` is set, or the maximum value if ``b`` is not set (non-inclusive, in which case the minimum is implicitly 0.0) :param float b: The maximum value to generate (non-inclusive) :returns: ...
def load_grammar(self, path): """Load a grammar file (python file containing grammar definitions) by file path. When loaded, the global variable ``GRAMFUZZER`` will be set within the module. This is not always needed, but can be useful. :param str path: The path to the grammar file ...
def set_max_recursion(self, level): """Set the maximum reference-recursion depth (not the Python system maximum stack recursion level). This controls how many levels deep of nested references are allowed before gramfuzz attempts to generate the shortest (reference-wise) rules possible. ...
def preprocess_rules(self): """Calculate shortest reference-paths of each rule (and Or field), and prune all unreachable rules. """ to_prune = self._find_shortest_paths() self._prune_rules(to_prune) self._rules_processed = True
def add_definition(self, cat, def_name, def_val, no_prune=False, gram_file="default"): """Add a new rule definition named ``def_name`` having value ``def_value`` to the category ``cat``. :param str cat: The category to add the rule to :param str def_name: The name of the rule definition...
def add_to_cat_group(self, cat, cat_group, def_name): """Associate the provided rule definition name ``def_name`` with the category group ``cat_group`` in the category ``cat``. :param str cat: The category the rule definition was declared in :param str cat_group: The group within the ca...
def get_ref(self, cat, refname): """Return one of the rules in the category ``cat`` with the name ``refname``. If multiple rule defintions exist for the defintion name ``refname``, use :any:`gramfuzz.rand` to choose a rule at random. :param str cat: The category to look for the rule in....
def gen(self, num, cat=None, cat_group=None, preferred=None, preferred_ratio=0.5, max_recursion=None, auto_process=True): """Generate ``num`` rules from category ``cat``, optionally specifying preferred category groups ``preferred`` that should be preferred at probability ``preferred_ratio`` ove...
def post_revert(self, cat, res, total_num, num, info): """Commit any staged rule definition changes (rule generation went smoothly). """ if self._staged_defs is None: return for cat,def_name,def_value in self._staged_defs: self.defs.setdefault(cat, {}).set...
def fuzz_elements(self, element): """ Fuzz all elements inside the object """ try: if type(element) == dict: tmp_element = {} for key in element: if len(self.config.parameters) > 0: if self.config.exc...
def fuzzed(self): """ Get a printable fuzzed object """ try: if self.config.strong_fuzz: fuzzer = PJFMutators(self.config) if self.config.url_encode: if sys.version_info >= (3, 0): return urllib.parse...
def get_fuzzed(self, indent=False, utf8=False): """ Return the fuzzed object """ try: if "array" in self.json: return self.fuzz_elements(dict(self.json))["array"] else: return self.fuzz_elements(dict(self.json)) except Excep...
def mutate_object_decorate(self, func): """ Mutate a generic object based on type """ def mutate(): obj = func() return self.Mutators.get_mutator(obj, type(obj)) return mutate
def rewrite_redis_url(self): """\ if REDIS_SERVER is just an ip address, then we try to translate it to redis_url, redis://REDIS_SERVER so that it doesn't try to connect to localhost while you try to connect to another server :return: """ if self.REDIS_SERVER.star...
def get_host_identifier(self): """\ we try to return IPADDR:PID form to identify where any singlebeat instance is running. :return: """ if self._host_identifier: return self._host_identifier local_ip_addr = self.get_redis().connection_pool\ ...
def sigterm_handler(self, signum, frame): """ When we get term signal if we are waiting and got a sigterm, we just exit. if we have a child running, we pass the signal first to the child then we exit. :param signum: :param frame: :return: """ asse...
def cli_command_quit(self, msg): """\ kills the child and exits """ if self.state == State.RUNNING and self.sprocess and self.sprocess.proc: self.sprocess.proc.kill() else: sys.exit(0)
def cli_command_pause(self, msg): """\ if we have a running child we kill it and set our state to paused if we don't have a running child, we set our state to paused this will pause all the nodes in single-beat cluster its useful when you deploy some code and don't want your chi...
def cli_command_resume(self, msg): """\ sets state to waiting - so we resume spawning children """ if self.state == State.PAUSED: self.state = State.WAITING
def cli_command_stop(self, msg): """\ stops the running child process - if its running it will re-spawn in any single-beat node after sometime :param msg: :return: """ info = '' if self.state == State.RUNNING and self.sprocess and self.sprocess.proc: ...
def cli_command_restart(self, msg): """\ restart the subprocess i. we set our state to RESTARTING - on restarting we still send heartbeat ii. we kill the subprocess iii. we start again iv. if its started we set our state to RUNNING, else we set it to WAITING :par...
def getEvents(self): """ Retrieve a list of events since the last poll. Multiple calls may be needed to retrieve all events. If no events occur, the API will block for up to 30 seconds, after which an empty list is returned. As soon as an event is received in this time, it is returned...
def setPresence(self, status=SkypeUtils.Status.Online): """ Set the current user's presence on the network. Supports :attr:`.Status.Online`, :attr:`.Status.Busy` or :attr:`.Status.Hidden` (shown as :attr:`.Status.Offline` to others). Args: status (.Status): new availability...
def setMood(self, mood): """ Update the activity message for the current user. Args: mood (str): new mood message """ self.conn("POST", "{0}/users/{1}/profile/partial".format(SkypeConnection.API_USER, self.userId), auth=SkypeConnection.Auth.SkypeTok...
def setAvatar(self, image): """ Update the profile picture for the current user. Args: image (file): a file-like object to read the image from """ self.conn("PUT", "{0}/users/{1}/profile/avatar".format(SkypeConnection.API_USER, self.userId), auth=Sk...
def getUrlMeta(self, url): """ Retrieve various metadata associated with a URL, as seen by Skype. Args: url (str): address to ping for info Returns: dict: metadata for the website queried """ return self.conn("GET", SkypeConnection.API_URL, param...
def cycle(self): """ Request one batch of events from Skype, calling :meth:`onEvent` with each event in turn. Subclasses may override this method to alter loop functionality. """ try: events = self.getEvents() except requests.ConnectionError: retu...