code
stringlengths
51
2.34k
docstring
stringlengths
11
171
def setup_dns(endpoint): print("Setting up DNS...") yass = Yass(CWD) target = endpoint.lower() sitename = yass.sitename if not sitename: raise ValueError("Missing site name") endpoint = yass.config.get("hosting.%s" % target) if not endpoint: raise ValueError( "%s endpoint is missing in the hosting config" % target.upper()) if target == "s3": p = publisher.S3Website(sitename=sitename, aws_access_key_id=endpoint.get("aws_access_key_id"), aws_secret_access_key=endpoint.get("aws_secret_access_key"), region=endpoint.get("aws_region")) print("Setting AWS Route53 for: %s ..." % p.sitename) p.setup_dns() print("") print("Yass! Route53 setup successfully!") print("You can now visit the site at :") print(p.sitename_endpoint) footer()
Setup site domain to route to static site
def unhide_selected(): hidden_state = current_representation().hidden_state selection_state = current_representation().selection_state res = {} for k in selection_state: visible = hidden_state[k].invert() visible_and_selected = visible.add(selection_state[k]) res[k] = visible_and_selected.invert() current_representation().hide(res)
Unhide the selected objects
def num_discarded(self): if not self._data: return 0 n = 0 while n < len(self._data): if not isinstance(self._data[n], _TensorValueDiscarded): break n += 1 return n
Get the number of values discarded due to exceeding both limits.
def finalize(self): self.model().sigItemChanged.disconnect(self.repoTreeItemChanged) selectionModel = self.selectionModel() selectionModel.currentChanged.disconnect(self.currentItemChanged)
Disconnects signals and frees resources
def _flatten_list(self, data): 'Flattens nested lists into strings.' if data is None: return '' if isinstance(data, types.StringTypes): return data elif isinstance(data, (list, tuple)): return '\n'.join(self._flatten_list(x) for x in data)
Flattens nested lists into strings.
def build(self, n, vec): for i in range(-self.maxDisplacement, self.maxDisplacement+1): next = vec + [i] if n == 1: print '{:>5}\t'.format(next), " = ", printSequence(self.encodeMotorInput(next)) else: self.build(n-1, next)
Recursive function to help print motor coding scheme.
def eval(e, amplitude, e_0, alpha): xx = e / e_0 return amplitude * xx ** (-alpha)
One dimensional power law model function
def _classify_move_register(self, regs_init, regs_fini, mem_fini, written_regs, read_regs): matches = [] regs_init_inv = self._invert_dictionary(regs_init) for dst_reg, dst_val in regs_fini.items(): if dst_reg not in written_regs: continue for src_reg in regs_init_inv.get(dst_val, []): if src_reg not in read_regs: continue if self._arch_regs_size[src_reg] != self._arch_regs_size[dst_reg]: continue if src_reg == dst_reg: continue if regs_init[dst_reg] == regs_init[src_reg]: continue src_reg_ir = ReilRegisterOperand(src_reg, self._arch_regs_size[src_reg]) dst_reg_ir = ReilRegisterOperand(dst_reg, self._arch_regs_size[dst_reg]) matches.append({ "src": [src_reg_ir], "dst": [dst_reg_ir] }) return matches
Classify move-register gadgets.
def _get_url_hashes(path): urls = _read_text_file(path) def url_hash(u): h = hashlib.sha1() try: u = u.encode('utf-8') except UnicodeDecodeError: logging.error('Cannot hash url: %s', u) h.update(u) return h.hexdigest() return {url_hash(u): True for u in urls}
Get hashes of urls in file.
def save_objective_bank(self, objective_bank_form, *args, **kwargs): if objective_bank_form.is_for_update(): return self.update_objective_bank(objective_bank_form, *args, **kwargs) else: return self.create_objective_bank(objective_bank_form, *args, **kwargs)
Pass through to provider ObjectiveBankAdminSession.update_objective_bank
def keys_with_value(dictionary, value): "Returns a subset of keys from the dict with the value supplied." subset = [key for key in dictionary if dictionary[key] == value] return subset
Returns a subset of keys from the dict with the value supplied.
def freeze(self): self.app.disable() self.clear.disable() self.nod.disable() self.led.disable() self.dummy.disable() self.readSpeed.disable() self.expose.disable() self.number.disable() self.wframe.disable(everything=True) self.nmult.disable() self.frozen = True
Freeze all settings so they cannot be altered
def cleanup(self): self._processing_stop = True self._wakeup_processing_thread() self._processing_stopped_event.wait(3)
Stop backgroud thread and cleanup resources
def select(self, names): return PolicyCollection( [p for p in self.policies if p.name in names], self.options)
return the named subset of policies
def builds(self, request, pk=None): builds = self.get_object().builds.prefetch_related('test_runs').order_by('-datetime') page = self.paginate_queryset(builds) serializer = BuildSerializer(page, many=True, context={'request': request}) return self.get_paginated_response(serializer.data)
List of builds for the current project.
def _check_satisfy_constraints(self, label, xmin, ymin, xmax, ymax, width, height): if (xmax - xmin) * (ymax - ymin) < 2: return False x1 = float(xmin) / width y1 = float(ymin) / height x2 = float(xmax) / width y2 = float(ymax) / height object_areas = self._calculate_areas(label[:, 1:]) valid_objects = np.where(object_areas * width * height > 2)[0] if valid_objects.size < 1: return False intersects = self._intersect(label[valid_objects, 1:], x1, y1, x2, y2) coverages = self._calculate_areas(intersects) / object_areas[valid_objects] coverages = coverages[np.where(coverages > 0)[0]] return coverages.size > 0 and np.amin(coverages) > self.min_object_covered
Check if constrains are satisfied
def load_pickle(filename): try: if pd: return pd.read_pickle(filename), None else: with open(filename, 'rb') as fid: data = pickle.load(fid) return data, None except Exception as err: return None, str(err)
Load a pickle file as a dictionary
def _trim_files(files, trim_output): count = 100 if not isinstance(trim_output, bool): count = trim_output if not(isinstance(trim_output, bool) and trim_output is False) and len(files) > count: files = files[:count] files.append("List trimmed after {0} files.".format(count)) return files
Trim the file list for output.
def _parse_script(list, line, line_iter): ifIdx = 0 while (True): line = next(line_iter) if line.startswith("fi"): if ifIdx == 0: return ifIdx -= 1 elif line.startswith("if"): ifIdx += 1
Eliminate any bash script contained in the grub v2 configuration
def bind_addr(self, value): if isinstance(value, tuple) and value[0] in ('', None): raise ValueError( "Host values of '' or None are not allowed. " "Use '0.0.0.0' (IPv4) or '::' (IPv6) instead " 'to listen on all active interfaces.', ) self._bind_addr = value
Set the interface on which to listen for connections.
def on_terminate(func): def exit_function(*args): func() exit(0) signal.signal(signal.SIGTERM, exit_function)
Register a signal handler to execute when Maltego forcibly terminates the transform.
def add_ingredients(self): for ingredient in self.recipe._cauldron.values(): if hasattr(ingredient.meta, 'anonymizer'): anonymizer = ingredient.meta.anonymizer if isinstance(anonymizer, basestring): kwargs = {} anonymizer_locale = getattr( ingredient.meta, 'anonymizer_locale', None ) anonymizer_postprocessor = getattr( ingredient.meta, 'anonymizer_postprocessor', None ) if anonymizer_postprocessor is not None: kwargs['postprocessor'] = anonymizer_postprocessor if anonymizer_locale is not None: kwargs['locale'] = anonymizer_locale anonymizer = FakerAnonymizer(anonymizer, **kwargs) ingredient.formatters = [ f for f in ingredient.formatters if not isinstance(f, FakerAnonymizer) ] if self._anonymize: if ingredient.meta.anonymizer not in ingredient.formatters: ingredient.formatters.append(anonymizer) else: if ingredient.meta.anonymizer in ingredient.formatters: ingredient.formatters.remove(anonymizer)
Put the anonymizers in the last position of formatters
def interact(self): lines = "" for line in self.read(): lines += line try: self.eval(lines) except ValueError: pass except KeyboardInterrupt as e: raise e except: self.terminal.error(traceback.format_exc()) break else: break
Get a command from the user and respond to it.
async def settings(dev: Device): settings_tree = await dev.get_settings() for module in settings_tree: await traverse_settings(dev, module.usage, module.settings)
Print out all possible settings.
def ms_cutlo(self, viewer, event, data_x, data_y): if not self.cancut: return True x, y = self.get_win_xy(viewer) if event.state == 'move': self._cutlow_xy(viewer, x, y) elif event.state == 'down': self._start_x, self._start_y = x, y self._loval, self._hival = viewer.get_cut_levels() else: viewer.onscreen_message(None) return True
An interactive way to set the low cut level.
def ext_pillar(hyper_id, pillar, name, key): vk = salt.utils.virt.VirtKey(hyper_id, name, __opts__) ok = vk.accept(key) pillar['virtkey'] = {name: ok} return {}
Accept the key for the VM on the hyper, if authorized.
def upgrade(self, flag): for pkg in self.binary: try: subprocess.call("upgradepkg {0} {1}".format(flag, pkg), shell=True) check = pkg[:-4].split("/")[-1] if os.path.isfile(self.meta.pkg_path + check): print("Completed!\n") else: raise SystemExit() except subprocess.CalledProcessError: self._not_found("Can't upgrade", self.binary, pkg) raise SystemExit(1)
Upgrade Slackware binary packages with new
def register_value_proxy(namespace, value_proxy, help_text): namespace.register_proxy(value_proxy) config.config_help.add( value_proxy.config_key, value_proxy.validator, value_proxy.default, namespace.get_name(), help_text)
Register a value proxy with the namespace, and add the help_text.
def OnMouse(self, event): self.SetGridCursor(event.Row, event.Col) self.EnableCellEditControl(True) event.Skip()
Reduces clicks to enter an edit control
def oauth_logout_handler(sender_app, user=None): oauth = current_app.extensions['oauthlib.client'] for remote in oauth.remote_apps.values(): token_delete(remote) db.session.commit()
Remove all access tokens from session on logout.
def saveLogs(self, filename) : f = open(filename, 'wb') cPickle.dump(self.logs, f) f.close()
dumps logs into a nice pickle
def __call_stream(self, uri, params=None, method="get"): try: resp = self.__get_response(uri, params, method, True) assert resp.ok except AssertionError: raise BadRequest(resp.status_code) except Exception as e: log.error("Bad response: {}".format(e), exc_info=True) else: return resp
Returns an stream response
def cena_tau(imt, mag, params): if imt.name == "PGV": C = params["PGV"] else: C = params["SA"] if mag > 6.5: return C["tau3"] elif (mag > 5.5) and (mag <= 6.5): return ITPL(mag, C["tau3"], C["tau2"], 5.5, 1.0) elif (mag > 5.0) and (mag <= 5.5): return ITPL(mag, C["tau2"], C["tau1"], 5.0, 0.5) else: return C["tau1"]
Returns the inter-event standard deviation, tau, for the CENA case
def gather_facts_list(self, file): facts = [] contents = utils.file_to_string(os.path.join(self.paths["role"], file)) contents = re.sub(r"\s+", "", contents) matches = self.regex_facts.findall(contents) for match in matches: facts.append(match.split(":")[1]) return facts
Return a list of facts.
def WSGIHandler(self): sdm = werkzeug_wsgi.SharedDataMiddleware(self, { "/": config.CONFIG["AdminUI.document_root"], }) return werkzeug_wsgi.DispatcherMiddleware(self, { "/static": sdm, })
Returns GRR's WSGI handler.
def add_context( self, name, cluster_name=None, user_name=None, namespace_name=None, **attrs ): if self.context_exists(name): raise KubeConfError("context with the given name already exists.") contexts = self.get_contexts() new_context = {'name': name, 'context':{}} attrs_ = new_context['context'] if cluster_name is not None: attrs_['cluster'] = cluster_name if user_name is not None: attrs_['user'] = user_name if namespace_name is not None: attrs_['namespace'] = namespace_name attrs_.update(attrs) contexts.append(new_context)
Add a context to config.
def _extract_rev(self, line1, line2): try: if line1.startswith('--- ') and line2.startswith('+++ '): l1 = line1[4:].split(None, 1) old_filename = l1[0].lstrip('a/') if len(l1) >= 1 else None old_rev = l1[1] if len(l1) == 2 else 'old' l2 = line2[4:].split(None, 1) new_filename = l2[0].lstrip('b/') if len(l1) >= 1 else None new_rev = l2[1] if len(l2) == 2 else 'new' filename = old_filename if (old_filename != 'dev/null') else new_filename return filename, new_rev, old_rev except (ValueError, IndexError): pass return None, None, None
Extract the filename and revision hint from a line.
def _thread_init(cls): if not hasattr(cls._local, '_in_order_futures'): cls._local._in_order_futures = set() cls._local._activated = False
Ensure thread local is initialized.
def build_model_from_xy(self, x_values, y_values): self.init_ace(x_values, y_values) self.run_ace() self.build_interpolators()
Construct the model and perform regressions based on x, y data.
def form_valid(self, form): form.send_email(to=self.to_addr) return super(EmailView, self).form_valid(form)
Praise be, someone has spammed us.
def home(request): polls = [] for row in curDB.execute('SELECT id, title FROM Poll ORDER BY title'): polls.append({'id': row[0], 'name': row[1]}) return {'polls': polls}
Show the home page. Send the list of polls
def stop_all_tensorboards(): for process in Process.instances: print("Process '%s', running %d" % (process.command[0], process.is_running())) if process.is_running() and process.command[0] == "tensorboard": process.terminate()
Terminate all TensorBoard instances.
def tilequeue_stuck_tiles(cfg, peripherals): store = _make_store(cfg) format = lookup_format_by_extension('zip') layer = 'all' assert peripherals.toi, 'Missing toi' toi = peripherals.toi.fetch_tiles_of_interest() for coord in store.list_tiles(format, layer): coord_int = coord_marshall_int(coord) if coord_int not in toi: print serialize_coord(coord)
Check which files exist on s3 but are not in toi.
def addDataset(self): self._openRepo() dataset = datasets.Dataset(self._args.datasetName) dataset.setDescription(self._args.description) dataset.setAttributes(json.loads(self._args.attributes)) self._updateRepo(self._repo.insertDataset, dataset)
Adds a new dataset into this repo.
def template_thinning(self, inj_filter_rejector): if not inj_filter_rejector.enabled or \ inj_filter_rejector.chirp_time_window is None: return injection_parameters = inj_filter_rejector.injection_params.table fref = inj_filter_rejector.f_lower threshold = inj_filter_rejector.chirp_time_window m1= self.table['mass1'] m2= self.table['mass2'] tau0_temp, _ = pycbc.pnutils.mass1_mass2_to_tau0_tau3(m1, m2, fref) indices = [] for inj in injection_parameters: tau0_inj, _ = \ pycbc.pnutils.mass1_mass2_to_tau0_tau3(inj.mass1, inj.mass2, fref) inj_indices = np.where(abs(tau0_temp - tau0_inj) <= threshold)[0] indices.append(inj_indices) indices_combined = np.concatenate(indices) indices_unique= np.unique(indices_combined) self.table = self.table[indices_unique]
Remove templates from bank that are far from all injections.
def _get_env(self): env = {} for k, v in os.environ.items(): k = k.decode() if isinstance(k, bytes) else k v = v.decode() if isinstance(v, bytes) else v env[k] = v return list(env.items())
loads the environment variables as unicode if ascii
def cleanup(self): for actor in self.actors: if actor.skip: continue actor.cleanup() super(ActorHandler, self).cleanup()
Destructive finishing up after execution stopped.
def fetch(table, cols="*", where=(), group="", order=(), limit=(), **kwargs): return select(table, cols, where, group, order, limit, **kwargs).fetchall()
Convenience wrapper for database SELECT and fetch all.
def _check_pkgin(): ppath = salt.utils.path.which('pkgin') if ppath is None: try: localbase = __salt__['cmd.run']( 'pkg_info -Q LOCALBASE pkgin', output_loglevel='trace' ) if localbase is not None: ppath = '{0}/bin/pkgin'.format(localbase) if not os.path.exists(ppath): return None except CommandExecutionError: return None return ppath
Looks to see if pkgin is present on the system, return full path
def update(self): with self._lock: devices = self._request_devices(MINUT_DEVICES_URL, 'devices') if devices: self._state = { device['device_id']: device for device in devices } _LOGGER.debug("Found devices: %s", list(self._state.keys())) homes = self._request_devices(MINUT_HOMES_URL, 'homes') if homes: self._homes = homes return self.devices
Update all devices from server.
def tags(self, extra_params=None): params = { 'per_page': settings.MAX_PER_PAGE, } if extra_params: params.update(extra_params) return self.api._get_json( Tag, space=self, rel_path=self.space._build_rel_path( 'tickets/%s/tags' % self['number'] ), extra_params=params, get_all=True, )
All Tags in this Ticket
def bulk_history_create(self, objs, batch_size=None): historical_instances = [ self.model( history_date=getattr(instance, "_history_date", now()), history_user=getattr(instance, "_history_user", None), history_change_reason=getattr(instance, "changeReason", ""), history_type="+", **{ field.attname: getattr(instance, field.attname) for field in instance._meta.fields if field.name not in self.model._history_excluded_fields } ) for instance in objs ] return self.model.objects.bulk_create( historical_instances, batch_size=batch_size )
Bulk create the history for the objects specified by objs
def from_wc(cls, wc): return cls(wcdict=wc.dict, scale=wc.scale, eft=wc.eft, basis=wc.basis)
Return a `Wilson` instance initialized by a `wcxf.WC` instance
def drain(self): data = self._stream.getvalue() if len(data): yield from self._protocol.send(data) self._stream = io.BytesIO(b'')
Let the write buffer of the underlying transport a chance to be flushed.
def defaultMachine(use_rpm_default=True): if use_rpm_default: try: rmachine = subprocess.check_output(['rpm', '--eval=%_target_cpu'], shell=False).rstrip() rmachine = SCons.Util.to_str(rmachine) except Exception as e: return defaultMachine(False) else: rmachine = platform.machine() if rmachine in arch_canon: rmachine = arch_canon[rmachine][0] return rmachine
Return the canonicalized machine name.
def cache(self, con): try: if self._reset == 2: con.reset() else: if self._reset or con._transaction: try: con.rollback() except Exception: pass self._cache.put(con, 0) except Full: con.close() if self._connections: self._connections.release()
Put a connection back into the pool cache.
def exchange_code_for_token(self, authorization_code): if authorization_code not in self.authorization_codes: raise InvalidAuthorizationCode('{} unknown'.format(authorization_code)) authz_info = self.authorization_codes[authorization_code] if authz_info['used']: logger.debug('detected already used authz_code=%s', authorization_code) raise InvalidAuthorizationCode('{} has already been used'.format(authorization_code)) elif authz_info['exp'] < int(time.time()): logger.debug('detected expired authz_code=%s, now=%s > exp=%s ', authorization_code, int(time.time()), authz_info['exp']) raise InvalidAuthorizationCode('{} has expired'.format(authorization_code)) authz_info['used'] = True access_token = self._create_access_token(authz_info['sub'], authz_info[self.KEY_AUTHORIZATION_REQUEST], authz_info['granted_scope']) logger.debug('authz_code=%s exchanged to access_token=%s', authorization_code, access_token.value) return access_token
Exchanges an authorization code for an access token.
def scan_path(executable="mongod"): for path in os.environ.get("PATH", "").split(":"): path = os.path.abspath(path) executable_path = os.path.join(path, executable) if os.path.exists(executable_path): return executable_path
Scan the path for a binary.
def polygon_from_points(points): polygon = [] for pair in points.split(" "): x_y = pair.split(",") polygon.append([float(x_y[0]), float(x_y[1])]) return polygon
Constructs a numpy-compatible polygon from a page representation.
def INIT_LIST_EXPR(self, cursor): values = [self.parse_cursor(child) for child in list(cursor.get_children())] return values
Returns a list of literal values.
def unregister_signal_handlers(): signal.signal(SIGNAL_STACKTRACE, signal.SIG_IGN) signal.signal(SIGNAL_PDB, signal.SIG_IGN)
set signal handlers to default
def reset(self): self.scene = cocos.scene.Scene() self.z = 0 palette = config.settings['view']['palette'] r, g, b = palette['bg'] self.scene.add(cocos.layer.ColorLayer(r, g, b, 255), z=self.z) self.z += 1 message_layer = MessageLayer() self.scene.add(message_layer, z=self.z) self.z += 1 self.world_layer = WorldLayer(self.mode_id, fn_show_message=message_layer.show_message) self.scene.add(self.world_layer, z=self.z) self.z += 1 self.director._set_scene(self.scene) self.step() return self.world_layer.get_state()
Attach a new engine to director
def redirect_stdout(self): self.hijacked_stdout = sys.stdout self.hijacked_stderr = sys.stderr sys.stdout = open(self.hitch_dir.driverout(), "ab", 0) sys.stderr = open(self.hitch_dir.drivererr(), "ab", 0)
Redirect stdout to file so that it can be tailed and aggregated with the other logs.
def _MigrateArtifact(artifact): name = Text(artifact.name) try: logging.info("Migating %s", name) data_store.REL_DB.WriteArtifact(artifact) logging.info(" Wrote %s", name) except db.DuplicatedArtifactError: logging.info(" Skipped %s, because artifact already exists.", name)
Migrate one Artifact from AFF4 to REL_DB.
def scan_line(self, line, regex): return bool(re.search(regex, line, flags=re.IGNORECASE))
Checks if regex is in line, returns bool
def pprint(self): items = sorted(self.items()) return u"\n".join(u"%s=%s" % (k, v.pprint()) for k, v in items)
Return tag key=value pairs in a human-readable format.
def _ufunc_wrapper(ufunc, name=None): if not isinstance(ufunc, np.ufunc): raise TypeError('{} is not a ufunc'.format(ufunc)) ufunc_name = ufunc.__name__ ma_ufunc = getattr(np.ma, ufunc_name, None) if ufunc.nin == 2 and ufunc.nout == 1: func = _dual_input_fn_wrapper('np.{}'.format(ufunc_name), ufunc, ma_ufunc, name) elif ufunc.nin == 1 and ufunc.nout == 1: func = _unary_fn_wrapper('np.{}'.format(ufunc_name), ufunc, ma_ufunc, name) else: raise ValueError('Unsupported ufunc {!r} with {} input arrays & {} ' 'output arrays.'.format(ufunc_name, ufunc.nin, ufunc.nout)) return func
A function to generate the top level biggus ufunc wrappers.
def parse(self, text): tags, results = [], [] text = self.re_tag.sub(lambda m: self.sub_tag(m, tags, results), text) if self.strict and tags: markup = "%s%s%s" % (self.tag_sep[0], tags.pop(0), self.tag_sep[1]) raise MismatchedTag('opening tag "%s" has no corresponding closing tag' % markup) if self.always_reset: if not text.endswith(Style.RESET_ALL): text += Style.RESET_ALL return text
Return a string with markup tags converted to ansi-escape sequences.
def remove(self): if self.rc_file: self.rc_file.close() if self.env_file: self.env_file.close() shutil.rmtree(self.root_dir)
Removes the sprinter directory, if it exists
def count_cookies(self, domain): cookies = self.cookie_jar._cookies if domain in cookies: return sum( [len(cookie) for cookie in cookies[domain].values()] ) else: return 0
Return the number of cookies for the given domain.
def generate_subplots(self): _, axes = plt.subplots(len(self.models), sharex=True, sharey=True) return axes
Generates the subplots for the number of given models.
def _count_extra_actions(self, game_image): proportional = self._bonus_tools['extra_action_region'] t, l, b, r = proportional.region_in(game_image) token_region = game_image[t:b, l:r] game_h, game_w = game_image.shape[0:2] token_h = int(round(game_h * 27.0 / 960)) token_w = int(round(game_w * 22.0 / 1280)) sizes = (token_h, token_w), finder = v.TemplateFinder(pq_data.extra_action_template, sizes=sizes, acceptable_threshold=0.1, immediate_threshold=0.1) found_tokens = finder.locate_multiple_in(token_region) return len(found_tokens)
Count the number of extra actions for player in this turn.
def make_response(obj): if obj is None: raise TypeError("Handler return value cannot be None.") if isinstance(obj, Response): return obj return Response(200, body=obj)
Try to coerce an object into a Response object.
def _rewrite_error_path(self, error, offset=0): if error.is_logic_error: self._rewrite_logic_error_path(error, offset) elif error.is_group_error: self._rewrite_group_error_path(error, offset)
Recursively rewrites the error path to correctly represent logic errors
def draw_lines(): r = numpy.random.randn(200) fig = pyplot.figure() ax = fig.add_subplot(111) ax.plot(r) ax.grid(True) pyplot.savefig(lines_filename)
Draws a line between a set of random values
def terminate(self, arg): instance = self.get(arg) with self.msg("Terminating %s (%s): " % (instance.name, instance.id)): instance.rename("old-%s" % instance.name) instance.terminate() while instance.state != 'terminated': time.sleep(5) self.log(".", end='') instance.update()
Terminate instance with given EC2 ID or nametag.
def _read(self): stream = self.path.read_text() data = yaml.load(stream) return data
Read the kube config file.
def remove(community_id, record_id): c = Community.get(community_id) assert c is not None c.remove_record(record_id) db.session.commit() RecordIndexer().index_by_id(record_id)
Remove a record from community.
def concatenate_json(source_folder, destination_file): matches = [] for root, dirnames, filenames in os.walk(source_folder): for filename in fnmatch.filter(filenames, '*.json'): matches.append(os.path.join(root, filename)) with open(destination_file, "wb") as f: f.write("[\n") for m in matches[:-1]: f.write(open(m, "rb").read()) f.write(",\n") f.write(open(matches[-1], "rb").read()) f.write("\n]")
Concatenate all the json files in a folder to one big JSON file.
def _load_pil_image(self, filename): self._channel_data = [] self._original_channel_data = [] im = Image.open(filename) self._image = ImageOps.grayscale(im) im.load() file_data = np.asarray(im, float) file_data = file_data / file_data.max() if( len(file_data.shape) == 3 ): num_channels = file_data.shape[2] for i in range(num_channels): self._channel_data.append( file_data[:, :, i]) self._original_channel_data.append( file_data[:, :, i] )
Load image using PIL.
def main(search, query): url = search.search(query) print(url) search.open_page(url)
main function that does the search
def close(self): try: if not self._closed and not self._owned: self._dispose() finally: self.detach()
Close this object and do any required clean-up actions.
def _compute_site_scaling(self, C, vs30): site_term = np.zeros(len(vs30), dtype=float) site_term[vs30 < 760.0] = C["e"] return site_term
Returns the site scaling term as a simple coefficient
def _extract_axes(self, data, axes, **kwargs): return [self._extract_axis(self, data, axis=i, **kwargs) for i, a in enumerate(axes)]
Return a list of the axis indices.
def new( name, bucket, timeout, memory, description, subnet_ids, security_group_ids ): config = {} if timeout: config['timeout'] = timeout if memory: config['memory'] = memory if description: config['description'] = description if subnet_ids: config['subnet_ids'] = subnet_ids if security_group_ids: config['security_group_ids'] = security_group_ids lambder.create_project(name, bucket, config)
Create a new lambda project
def show_osm_downloader(self): from safe.gui.tools.osm_downloader_dialog import OsmDownloaderDialog dialog = OsmDownloaderDialog(self.iface.mainWindow(), self.iface) dialog.setAttribute(Qt.WA_DeleteOnClose, True) dialog.show()
Show the OSM buildings downloader dialog.
def hset(self, key, field, value): return self.execute(b'HSET', key, field, value)
Set the string value of a hash field.
def read_recipe(self, filename): Global.LOGGER.debug(f"reading recipe {filename}") if not os.path.isfile(filename): Global.LOGGER.error(filename + " recipe not found, skipping") return config = configparser.ConfigParser(allow_no_value=True, delimiters="=") config.read(filename) for section in config.sections(): self.sections[section] = config[section] Global.LOGGER.debug("Read recipe " + filename)
Read a recipe file from disk
def uppercase_percent_encoding(text): if '%' not in text: return text return re.sub( r'%[a-f0-9][a-f0-9]', lambda match: match.group(0).upper(), text)
Uppercases percent-encoded sequences.
def authenticate(self): if self.apiKey: return loginResponse = self._curl_bitmex( api="user/login", postdict={'email': self.login, 'password': self.password, 'token': self.otpToken}) self.token = loginResponse['id'] self.session.headers.update({'access-token': self.token})
Set BitMEX authentication information.
def subject(self): if self.application_name and self.application_version: return 'Crash Report - {name} (v{version})'.format(name=self.application_name, version=self.application_version) else: return 'Crash Report'
Return a string to be used as the email subject line.
def _format_summary_node(self, task_class): modulename = task_class.__module__ classname = task_class.__name__ nodes = [] nodes.append( self._format_class_nodes(task_class)) nodes.append( self._format_config_nodes(modulename, classname) ) methods = ('run', 'runDataRef') for method in methods: if hasattr(task_class, method): method_obj = getattr(task_class, method) nodes.append( self._format_method_nodes(method_obj, modulename, classname)) return nodes
Format a section node containg a summary of a Task class's key APIs.
def _get_output_cwl_keys(fnargs): for d in utils.flatten(fnargs): if isinstance(d, dict) and d.get("output_cwl_keys"): return d["output_cwl_keys"] raise ValueError("Did not find output_cwl_keys in %s" % (pprint.pformat(fnargs)))
Retrieve output_cwl_keys from potentially nested input arguments.
def beginningPage(R): p = R['PG'] if p.startswith('suppl '): p = p[6:] return p.split(' ')[0].split('-')[0].replace(';', '')
As pages may not be given as numbers this is the most accurate this function can be
def agent_list(self, deep_sorted=False): ag_list = [] for ag_name in self._agent_order: ag_attr = getattr(self, ag_name) if isinstance(ag_attr, Concept) or ag_attr is None: ag_list.append(ag_attr) elif isinstance(ag_attr, list): if not all([isinstance(ag, Concept) for ag in ag_attr]): raise TypeError("Expected all elements of list to be Agent " "and/or Concept, but got: %s" % {type(ag) for ag in ag_attr}) if deep_sorted: ag_attr = sorted_agents(ag_attr) ag_list.extend(ag_attr) else: raise TypeError("Expected type Agent, Concept, or list, got " "type %s." % type(ag_attr)) return ag_list
Get the canonicallized agent list.
def read(config_values): if not config_values: raise RheaError('Cannot read config_value: `{}`'.format(config_values)) config_values = to_list(config_values) config = {} for config_value in config_values: config_value = ConfigSpec.get_from(value=config_value) config_value.check_type() config_results = config_value.read() if config_results and isinstance(config_results, Mapping): config = deep_update(config, config_results) elif config_value.check_if_exists: raise RheaError('Cannot read config_value: `{}`'.format(config_value)) return config
Reads an ordered list of configuration values and deep merge the values in reverse order.
def resize_state_port_meta(state_m, factor, gaphas_editor=True): if not gaphas_editor and isinstance(state_m, ContainerStateModel): port_models = state_m.input_data_ports[:] + state_m.output_data_ports[:] + state_m.scoped_variables[:] else: port_models = state_m.input_data_ports[:] + state_m.output_data_ports[:] + state_m.outcomes[:] port_models += state_m.scoped_variables[:] if isinstance(state_m, ContainerStateModel) else [] _resize_port_models_list(port_models, 'rel_pos' if gaphas_editor else 'inner_rel_pos', factor, gaphas_editor) resize_income_of_state_m(state_m, factor, gaphas_editor)
Resize data and logical ports relative positions
def tarbell_switch(command, args): with ensure_settings(command, args) as settings: projects_path = settings.config.get("projects_path") if not projects_path: show_error("{0} does not exist".format(projects_path)) sys.exit() project = args.get(0) args.remove(project) project_path = os.path.join(projects_path, project) if os.path.isdir(project_path): os.chdir(project_path) puts("\nSwitching to {0}".format(colored.red(project))) tarbell_serve(command, args) else: show_error("{0} isn't a tarbell project".format(project_path))
Switch to a project.
def standardize_shapes(features, batch_size=None): for fname in ["inputs", "targets"]: if fname not in features: continue f = features[fname] while len(f.get_shape()) < 4: f = tf.expand_dims(f, axis=-1) features[fname] = f if batch_size: for _, t in six.iteritems(features): shape = t.get_shape().as_list() shape[0] = batch_size t.set_shape(t.get_shape().merge_with(shape)) t.get_shape().assert_is_fully_defined() return features
Set the right shapes for the features.
def _merge_buckets(self, bucket_list: Set[DependenceBucket]) -> DependenceBucket: variables = [] conditions = [] for bucket in bucket_list: self.buckets.remove(bucket) variables += bucket.variables conditions += bucket.conditions new_bucket = DependenceBucket(variables, conditions) self.buckets.append(new_bucket) return new_bucket
Merges the buckets in bucket list