Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
11,800
def nmap_smb_vulnscan(): service_search = ServiceSearch() services = service_search.get_services(ports=[], tags=[], up=True) services = [service for service in services] service_dict = {} for service in services: service.add_tag() service_dict[str(service.address)] = service ...
Scans available smb services in the database for smb signing and ms17-010.
11,801
def main(command_line=True, **kwargs): def fix_separation(filename, new_filename): old_file = open(filename, ) data = old_file.readlines() new_data = [] for line in data: new_line = line.replace(, ) new_line = new_line.replace(, ) new_data.a...
NAME iodp_jr6_magic.py DESCRIPTION converts shipboard .jr6 format files to magic_measurements format files SYNTAX iodp_jr6_magic.py [command line options] OPTIONS -h: prints the help message and quits. -f FILE: specify input file, or -F FILE: specify outpu...
11,802
def use(cls, ec): if isinstance(ec, (str, unicode)): m = get_model(cls._alias, ec, signal=False) else: m = cls._use(ec) return m
use will duplicate a new Model class and bind ec ec is Engine name or Sesstion object
11,803
def is_orderable(cls): if not getattr(settings, , None): return False labels = resolve_labels(cls) if labels[] in settings.ORDERABLE_MODELS: return settings.ORDERABLE_MODELS[labels[]] return False
Checks if the provided class is specified as an orderable in settings.ORDERABLE_MODELS. If it is return its settings.
11,804
def ensure_matplotlib_figure(obj): import matplotlib from matplotlib.figure import Figure if obj == matplotlib.pyplot: obj = obj.gcf() elif not isinstance(obj, Figure): if hasattr(obj, "figure"): obj = obj.figure if not isinstance(obj, Figure): ...
Extract the current figure from a matplotlib object or return the object if it's a figure. raises ValueError if the object can't be converted.
11,805
def set( self, key, value, loader_identifier=None, tomlfy=False, dotted_lookup=True, is_secret=False, ): if "." in key and dotted_lookup is True: return self._dotted_set( key, value, loader_identifier=loader_identi...
Set a value storing references for the loader :param key: The key to store :param value: The value to store :param loader_identifier: Optional loader name e.g: toml, yaml etc. :param tomlfy: Bool define if value is parsed by toml (defaults False) :param is_secret: Bool define if...
11,806
def _write_init_models(self, filenames): self.write(destination=self.output_directory, filename="__init__.py", template_name="__init_model__.py.tpl", filenames=self._prepare_filenames(filenames), class_prefix=self._class_prefix, product_accronym...
Write init file Args: filenames (dict): dict of filename and classes
11,807
def link(self, stream_instance): if isinstance(stream_instance, collections.Iterable): self.input_stream = stream_instance elif getattr(stream_instance, , None): self.input_stream = stream_instance.output_stream else: raise RuntimeError( % type(stream...
Set my input stream
11,808
def _is_gs_folder(cls, result): return (cls.is_key(result) and result.size == 0 and result.name.endswith(cls._gs_folder_suffix))
Return ``True`` if GS standalone folder object. GS will create a 0 byte ``<FOLDER NAME>_$folder$`` key as a pseudo-directory place holder if there are no files present.
11,809
def buttonbox(msg="", title=" ", choices=("Button[1]", "Button[2]", "Button[3]"), image=None, root=None, default_choice=None, cancel_choice=None): global boxRoot, __replyButtonText, buttonsFrame if default_choice is None: default_choice = choices[0] __replyButtonText = cho...
Display a msg, a title, an image, and a set of buttons. The buttons are defined by the members of the choices list. :param str msg: the msg to be displayed :param str title: the window title :param list choices: a list or tuple of the choices to be displayed :param str image: Filename of image to d...
11,810
def draw_flat_samples(**kwargs): nsamples = kwargs.get(, 1) min_mass = kwargs.get(, 1.) max_mass = kwargs.get(, 2.) m1 = np.random.uniform(min_mass, max_mass, nsamples) m2 = np.random.uniform(min_mass, max_mass, nsamples) return np.maximum(m1, m2), np.minimum(m1, m2)
Draw samples for uniform in mass Parameters ---------- **kwargs: string Keyword arguments as model parameters and number of samples Returns ------- array The first mass array The second mass
11,811
def safe_urlencode(params, doseq=0): if IS_PY3: return urlencode(params, doseq) if hasattr(params, "items"): params = params.items() new_params = [] for k, v in params: k = k.encode("utf-8") if isinstance(v, (list, tuple)): new_params.append((k, [forc...
UTF-8-safe version of safe_urlencode The stdlib safe_urlencode prior to Python 3.x chokes on UTF-8 values which can't fail down to ascii.
11,812
def handle_json_GET_routepatterns(self, params): schedule = self.server.schedule route = schedule.GetRoute(params.get(, None)) if not route: self.send_error(404) return time = int(params.get(, 0)) date = params.get(, "") sample_size = 3 pattern_id_trip_dict = route.GetPat...
Given a route_id generate a list of patterns of the route. For each pattern include some basic information and a few sample trips.
11,813
def start(self): self._events_to_write = [] self._new_contracts_to_write = [] @events.on(SmartContractEvent.CONTRACT_CREATED) @events.on(SmartContractEvent.CONTRACT_MIGRATED) def call_on_success_event(sc_event: SmartContractEvent): self.on_smart_contract_cre...
Handle EventHub events for SmartContract decorators
11,814
def update_table(self, tablename, throughput=None, global_indexes=None, index_updates=None): kwargs = { : tablename } all_attrs = set() if throughput is not None: kwargs[] = throughput.schema() if index_updates is not None: ...
Update the throughput of a table and/or global indexes Parameters ---------- tablename : str Name of the table to update throughput : :class:`~dynamo3.fields.Throughput`, optional The new throughput of the table global_indexes : dict, optional ...
11,815
def getChecked(self): attrs = [] layout = self.layout() for i in range(layout.count()): w = layout.itemAt(i).widget() if w.isChecked(): attrs.append(str(w.text())) return attrs
Gets the checked attributes :returns: list<str> -- checked attribute names
11,816
def get_passage(self, objectId, subreference): passage = self.resolver.getTextualNode( textId=objectId, subreference=subreference, metadata=True ) return passage
Retrieve the passage identified by the parameters :param objectId: Collection Identifier :type objectId: str :param subreference: Subreference of the passage :type subreference: str :return: An object bearing metadata and its text :rtype: InteractiveTextualNode
11,817
def stage_name(self): if in self.data and self.data.stage_name: return self.data.get() else: return self.stage.data.name
Get stage name of current job instance. Because instantiating job instance could be performed in different ways and those return different results, we have to check where from to get name of the stage. :return: stage name.
11,818
def _write_family(family, filename): with open(filename, ) as f: for detection in family.detections: det_str = for key in detection.__dict__.keys(): if key == and detection.__dict__[key] is not None: value = str(detection.event.resource_id) ...
Write a family to a csv file. :type family: :class:`eqcorrscan.core.match_filter.Family` :param family: Family to write to file :type filename: str :param filename: File to write to.
11,819
def _get_MAP_spikes(F, c_hat, theta, dt, tol=1E-6, maxiter=100, verbosity=0): npix, nt = F.shape sigma, alpha, beta, lamb, gamma = theta alpha_ss = np.dot(alpha, alpha) c = np.dot(alpha, F) - np.dot(alpha, beta) scale_var = 1. / (2 * sigma * sigma) lD = lamb * dt ...
Used internally by deconvolve to compute the maximum a posteriori spike train for a given set of fluorescence traces and model parameters. See the documentation for deconvolve for the meaning of the arguments Returns: n_hat_best, c_hat_best, LL_best
11,820
def _socket_reconnect_and_wait_ready(self): logger.info("Start connecting: host={}; port={};".format(self.__host, self.__port)) with self._lock: self._status = ContextStatus.Connecting ret, msg, conn_id = self._net_mgr.connect((self.__host, self.__port), sel...
sync_socket & async_socket recreate :return: (ret, msg)
11,821
def pick(self, filenames: Iterable[str]) -> str: filenames = sorted(filenames, reverse=True) for priority in sorted(self.rules.keys(), reverse=True): patterns = self.rules[priority] for pattern in patterns: for filename in filenames: ...
Pick one filename based on priority rules.
11,822
def solveConsKinkedR(solution_next,IncomeDstn,LivPrb,DiscFac,CRRA,Rboro,Rsave, PermGroFac,BoroCnstArt,aXtraGrid,vFuncBool,CubicBool): s one period problem. IncomeDstn : [np.array] A list containing three arrays of floats, representing a discrete approximation t...
Solves a single period consumption-saving problem with CRRA utility and risky income (subject to permanent and transitory shocks), and different interest factors on borrowing and saving. Restriction: Rboro >= Rsave. Currently cannot construct a cubic spline consumption function, only linear. Can gen- ...
11,823
def main(argv=None): arguments = cli_common(__doc__, argv=argv) es_export = ESExporter(arguments[], arguments[]) es_export.export() if argv is not None: return es_export
ben-elastic entry point
11,824
def get_sources(src_dir=, ending=): return [os.path.join(src_dir, fnm) for fnm in os.listdir(src_dir) if fnm.endswith(ending)]
Function to get a list of files ending with `ending` in `src_dir`.
11,825
def command_gen(self, *names): if not names: sys.exit() for name in names: name, count = name, 0 if in name: name, count = name.split(, 1) count = int(count) create = self.generators[name] print(.format(nam...
Runs generator functions. Run `docs` generator function:: ./manage.py sqla:gen docs Run `docs` generator function with `count=10`:: ./manage.py sqla:gen docs:10
11,826
def pdftojpg(filehandle, meta): resolution = meta.get(, 300) width = meta.get(, 1080) bgcolor = Color(meta.get(, )) stream = BytesIO() with Image(blob=filehandle.stream, resolution=resolution) as img: img.background_color = bgcolor img.alpha_channel = False img.format =...
Converts a PDF to a JPG and places it back onto the FileStorage instance passed to it as a BytesIO object. Optional meta arguments are: * resolution: int or (int, int) used for wand to determine resolution, defaults to 300. * width: new width of the image for resizing, defaults to 1080 ...
11,827
def filter(self, query: Query, entity: type) -> Tuple[Query, Any]: new_query = query c_filter_list = [] for child in self._childs: new_query, f_list = child.filter(new_query, entity) c_filter_list.append(f_list) return ( new_query, ...
Apply the `_method` to all childs of the node. :param query: The sqlachemy query. :type query: Query :param entity: The entity model of the query. :type entity: type :return: A tuple with in first place the updated query and in second place the list of filt...
11,828
def clear(self): self.grid = [[EMPTY for dummy_col in range(self.grid_width)] for dummy_row in range(self.grid_height)]
Clears grid to be EMPTY
11,829
def writeRunSetInfoToLog(self, runSet): runSetInfo = "\n\n" if runSet.name: runSetInfo += runSet.name + "\n" runSetInfo += "Run set {0} of {1} with options and propertyfile \n\n".format( runSet.index, len(self.benchmark.run_sets), " ".join(r...
This method writes the information about a run set into the txt_file.
11,830
def dmp_path(regex, kwargs=None, name=None, app_name=None): dmp_pageprocess_request return PagePattern(regex, kwargs, name, app_name)
Creates a DMP-style, convention-based pattern that resolves to various view functions based on the 'dmp_page' value. The following should exist as 1) regex named groups or 2) items in the kwargs dict: dmp_app Should resolve to a name in INSTALLED_APPS. If missing, de...
11,831
def ex6_2(n): x = np.zeros(len(n)) for k, nn in enumerate(n): if nn >= -2 and nn <= 5: x[k] = 8 - nn return x
Generate a triangle pulse as described in Example 6-2 of Chapter 6. You need to supply an index array n that covers at least [-2, 5]. The function returns the hard-coded signal of the example. Parameters ---------- n : time index ndarray covering at least -2 to +5. Returns ...
11,832
def addResource(self, key, filePath, text): url = self.root + "/addresource" params = { "f": "json", "token" : self._securityHandler.token, "key" : key, "text" : text } files = {} files[] = filePath res = self._post(url=url, ...
The add resource operation allows the administrator to add a file resource, for example, the organization's logo or custom banner. The resource can be used by any member of the organization. File resources use storage space from your quota and are scanned for viruses. Inputs: ...
11,833
def reading_order(e1, e2): b1 = e1.bbox b2 = e2.bbox if round(b1[y0]) == round(b2[y0]) or round(b1[y1]) == round(b2[y1]): return float_cmp(b1[x0], b2[x0]) return float_cmp(b1[y0], b2[y0])
A comparator to sort bboxes from top to bottom, left to right
11,834
def _adjustSyllabification(adjustedPhoneList, syllableList): i = 0 retSyllableList = [] for syllableNum, syllable in enumerate(syllableList): j = len(syllable) if syllableNum == len(syllableList) - 1: j = len(adjustedPhoneList) - i tmpPhoneList = adjustedPhoneList[i:...
Inserts spaces into a syllable if needed Originally the phone list and syllable list contained the same number of phones. But the adjustedPhoneList may have some insertions which are not accounted for in the syllableList.
11,835
def publish(self, topic, obj, reference_message=None): logging.debug("Publishing topic (%s): \n%s" % (topic, obj)) e = Event( data=obj, type=topic, ) if hasattr(obj, "sender"): e.sender = obj.sender if reference_message: o...
Sends an object out over the pubsub connection, properly formatted, and conforming to the protocol. Handles pickling for the wire, etc. This method should *not* be subclassed.
11,836
def _getch_unix(_getall=False): import sys, termios fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) chars = [] try: newattr = list(old_settings) newattr[3] &= ~termios.ICANON newattr[3] &= ~termios.ECHO newattr[6][te...
# --- current algorithm --- # 1. switch to char-by-char input mode # 2. turn off echo # 3. wait for at least one char to appear # 4. read the rest of the character buffer (_getall=True) # 5. return list of characters (_getall on) # or a single char (_getall off)
11,837
async def send_nym(self, did: str, verkey: str = None, alias: str = None, role: Role = None) -> None: LOGGER.debug( , did, verkey, alias, role) if not ok_did(did): LOGGER.debug(, did) raise BadIdentifier(.format(did)) req_json = await ledger.build_...
Send input anchor's cryptonym (including DID, verification key, plus optional alias and role) to the distributed ledger. Raise BadLedgerTxn on failure, BadIdentifier for bad DID, or BadRole for bad role. :param did: anchor DID to send to ledger :param verkey: optional anchor verificati...
11,838
def parse_legacy_argstring(argstring): arg1arg2item1item2 argstring = argstring.replace(, ) argstring = argstring.replace(, ) argstring = argstring.replace(, ) argbits = shlex.split(argstring) args = [] arg_buff = [] list_buff = [] in_list = False for bit in argbits: i...
Preparses CLI input: ``arg1,arg2`` => ``['arg1', 'arg2']`` ``[item1, item2],arg2`` => ``[['item1', 'item2'], arg2]``
11,839
def handle_read(self): if self.state == STATE_DEAD: return global nr_handle_read nr_handle_read += 1 new_data = self._handle_read_chunk() if self.debug: self.print_debug(b + new_data) if self.handle_read_fast_case(self.read_buffer): ...
We got some output from a remote shell, this is one of the state machine
11,840
def config_diff(args): config_1 = config_get(args).splitlines() args.project = args.Project args.workspace = args.Workspace cfg_1_name = args.config if args.Config is not None: args.config = args.Config if args.Namespace is not None: args.namespace = args.Namespace confi...
Compare method configuration definitions across workspaces. Ignores methodConfigVersion if the verbose argument is not set
11,841
def create_build(self, tarball_url, env=None, app_name=None): data = { : { : tarball_url } } if env: data[] = {: env} if app_name: data[] = {: app_name} return self.api_request(, , data=data)
Creates an app-setups build. Returns response data as a dict. :param tarball_url: URL of a tarball containing an ``app.json``. :param env: Dict containing environment variable overrides. :param app_name: Name of the Heroku app to create. :returns: Response data as a ``dict``.
11,842
def compact_interval_string(value_list): if not value_list: return value_list.sort() interval_list = [] curr = [] for val in value_list: if curr and (val > curr[-1] + 1): interval_list.append((curr[0], curr[-1])) curr = [val] else: curr.append(val) if curr: inter...
Compact a list of integers into a comma-separated string of intervals. Args: value_list: A list of sortable integers such as a list of numbers Returns: A compact string representation, such as "1-5,8,12-15"
11,843
def write(self, inline): frame = inspect.currentframe().f_back if frame: mod = frame.f_globals.get() else: mod = sys._getframe(0).f_globals.get() if not mod in self.modulenames: self.stdout.write(inline)
Write a line to stdout if it isn't in a blacklist Try to get the name of the calling module to see if we want to filter it. If there is no calling module, use current frame in case there's a traceback before there is any calling module
11,844
def rollout(self, batch_info: BatchInfo, model: RlModel, number_of_steps: int) -> Rollout: assert not model.is_recurrent, "Replay env roller does not support recurrent models" accumulator = TensorAccumulator() episode_information = [] for step_idx in range(number_of_steps): ...
Calculate env rollout
11,845
def _sendline(self, line): self.lines = [] try: self._read() except socket.error: logging.debug() logger.debug(, line) self._write(line + ) time.sleep(0.5)
Send exactly one line to the device Args: line str: data send to device
11,846
def decorate(decorator_cls, *args, **kwargs): global _wrappers wrapper_cls = _wrappers.get(decorator_cls, None) if wrapper_cls is None: class PythonWrapper(decorator_cls): pass wrapper_cls = PythonWrapper wrapper_cls.__name__ = decorator_cls.__name__ + "PythonWrap...
Creates a decorator function that applies the decorator_cls that was passed in.
11,847
def import_orm(self): orm = {} data_source = self.config[][] mv_grid_districts_name = self.config[data_source][] mv_stations_name = self.config[data_source][] lv_load_areas_name = self.config[data_source][] lv_grid_district_name = self.config[data_sour...
Import ORM classes for oedb access depending on input in config in self.config which is loaded from 'config_db_tables.cfg' Returns ------- int Descr #TODO check type
11,848
def dumps(self): r string = "" if self.row_height is not None: row_height = Command(, arguments=[ NoEscape(r), self.row_height]) string += row_height.dumps() + if self.col_space is not None: col_space = Command(, arg...
r"""Turn the Latex Object into a string in Latex format.
11,849
def visit_List(self, node: ast.List) -> List[Any]: if isinstance(node.ctx, ast.Store): raise NotImplementedError("Can not compute the value of a Store on a list") result = [self.visit(node=elt) for elt in node.elts] self.recomputed_values[node] = result return resu...
Visit the elements and assemble the results into a list.
11,850
def reindex_like(self, other, method=None, tolerance=None, copy=True): indexers = alignment.reindex_like_indexers(self, other) return self.reindex(indexers=indexers, method=method, copy=copy, tolerance=tolerance)
Conform this object onto the indexes of another object, filling in missing values with NaN. Parameters ---------- other : Dataset or DataArray Object with an 'indexes' attribute giving a mapping from dimension names to pandas.Index objects, which provides coordin...
11,851
def get(self, url=None, delimiter="/"): params = {: delimiter} bucket, obj_key = _parse_url(url) if bucket: params[] = bucket else: return self.call("ListBuckets", response_data_key="Buckets") if obj_key: params[] = obj_key ...
Path is an s3 url. Ommiting the path or providing "s3://" as the path will return a list of all buckets. Otherwise, all subdirectories and their contents will be shown.
11,852
def get_id_constraints(pkname, pkey): if isinstance(pkname, str): return {pkname: pkey} else: return dict(zip(pkname, pkey))
Returns primary key consraints. :pkname: if a string, returns a dict with pkname=pkey. pkname and pkey must be enumerables of matching length.
11,853
def _get_lane_properties(self, node): lane_name = self.get_lane(node.get()) lane_data = {: lane_name} for a in self.xpath(".//bpmn:lane[@name=]/*/*/" % lane_name): lane_data[a.attrib[]] = a.attrib[].strip() return lane_data
Parses the given XML node Args: node (xml): XML node. .. code-block:: xml <bpmn2:lane id="Lane_8" name="Lane 8"> <bpmn2:extensionElements> <camunda:properties> <camunda:property value="foo,bar" name="perms"/> ...
11,854
def get_volume_object_info(self, location): param = {: location} data = self._api.get(url=self._URL[].format( id=self.id), params=param).json() return VolumeObject(api=self._api, **data)
Fetches information about single volume object - usually file :param location: object location :return:
11,855
def start(self, exceptions): if not self._interval: return False self._running.set() with self._lock: self._threshold = 0 self._reads_since_check = 0 self._writes_since_check = 0 self._exceptions = exceptions LOGGER.debug()...
Start the Heartbeat Checker. :param list exceptions: :return:
11,856
def GetFormattedMessages(self, event): event_formatter = self.GetEventFormatter(event) if not event_formatter: return None, None return event_formatter.GetMessages(self._formatter_mediator, event)
Retrieves the formatted messages related to the event. Args: event (EventObject): event. Returns: tuple: containing: str: full message string or None if no event formatter was found. str: short message string or None if no event formatter was found.
11,857
def generic_visit(self, node): if (isinstance(node, ast.stmt) and not isinstance(node, ast.FunctionDef)): new_node = self.wrap_with_try(node) if isinstance(node, self.ast_try_except): self.try_except_handler(node) re...
Surround node statement with a try/except block to catch errors. This method is called for every node of the parsed code, and only changes statement lines. Args: node (ast.AST): node statement to surround.
11,858
def calculate(self, **state): T = state[] y = state[] x = amount_fractions(y) return super().calculate(T=T, x=x)
Calculate dynamic viscosity at the specified temperature and composition: :param T: [K] temperature :param y: [mass fraction] composition dictionary , e.g. \ {'SiO2': 0.25, 'CaO': 0.25, 'MgO': 0.25, 'FeO': 0.25} :returns: [Pa.s] dynamic viscosity The **state parameter ...
11,859
def search_directory(self, **kwargs): search_response = self.request(, kwargs) result = {} items = { "account": zobjects.Account.from_dict, "domain": zobjects.Domain.from_dict, "dl": zobjects.DistributionList.from_dict, "cos": zobjects.C...
SearchAccount is deprecated, using SearchDirectory :param query: Query string - should be an LDAP-style filter string (RFC 2254) :param limit: The maximum number of accounts to return (0 is default and means all) :param offset: The starting offset (0, 25, etc) :param dom...
11,860
def update(self, obj, **kwargs): "Update the tree item when the object name changes" child = self.tree.FindItem(self.root, kwargs[]) if DEBUG: print "update child", child, kwargs if child: self.tree.ScrollTo(child) self.tree.SetCurrentItem(child) ...
Update the tree item when the object name changes
11,861
def mtie_phase_fast(phase, rate=1.0, data_type="phase", taus=None): rate = float(rate) phase = np.asarray(phase) k_max = int(np.floor(np.log2(len(phase)))) phase = phase[0:pow(2, k_max)] assert len(phase) == pow(2, k_max) taus = [ pow(2,k) for k in range(k_max)] ...
fast binary decomposition algorithm for MTIE See: STEFANO BREGNI "Fast Algorithms for TVAR and MTIE Computation in Characterization of Network Synchronization Performance"
11,862
def trust_key(keyid=None, fingerprint=None, trust_level=None, user=None): s keychain to access, defaults to user Salt is running as. Passing the user as ``salt`` will set the GnuPG home directory to the ``/etc/salt/gpgkeys``. CLI Example: .. code-b...
Set the trust level for a key in GPG keychain keyid The keyid of the key to set the trust level for. fingerprint The fingerprint of the key to set the trust level for. trust_level The trust level to set for the specified key, must be one of the following: expired, ...
11,863
def _block(self, rdd, bsize, dtype): return rdd.mapPartitions(lambda x: _block_tuple(x, dtype, bsize))
Execute the blocking process on the given rdd. Parameters ---------- rdd : pyspark.rdd.RDD Distributed data to block bsize : int or None The desired size of the blocks Returns ------- rdd : pyspark.rdd.RDD Blocked rdd.
11,864
def _pop_import_LOAD_ATTRs(module_name, queue): popped = popwhile(is_a(instrs.LOAD_ATTR), queue, side=) if popped: expected = module_name.split(, maxsplit=1)[1] actual = .join(map(op.attrgetter(), popped)) if expected != actual: raise DecompilationError( ...
Pop LOAD_ATTR instructions for an import of the form:: import a.b.c as d which should generate bytecode like this:: 1 0 LOAD_CONST 0 (0) 3 LOAD_CONST 1 (None) 6 IMPORT_NAME 0 (a.b.c.d) 9...
11,865
def on_all_ok(self): out_ddb = self.merge_ddb_files() return self.Results(node=self, returncode=0, message="DDB merge done")
This method is called when all tasks reach S_OK Ir runs `mrgddb` in sequential on the local machine to produce the final DDB file in the outdir of the `Work`.
11,866
def linear_reaction_coefficients(model, reactions=None): linear_coefficients = {} reactions = model.reactions if not reactions else reactions try: objective_expression = model.solver.objective.expression coefficients = objective_expression.as_coefficients_dict() except AttributeErro...
Coefficient for the reactions in a linear objective. Parameters ---------- model : cobra model the model object that defined the objective reactions : list an optional list for the reactions to get the coefficients for. All reactions if left missing. Returns ------- ...
11,867
def describe_alarms(self, action_prefix=None, alarm_name_prefix=None, alarm_names=None, max_records=None, state_value=None, next_token=None): params = {} if action_prefix: params[] = action_prefix if alarm_name_prefix: ...
Retrieves alarms with the specified names. If no name is specified, all alarms for the user are returned. Alarms can be retrieved by using only a prefix for the alarm name, the alarm state, or a prefix for any action. :type action_prefix: string :param action_name: The action na...
11,868
def _check_hla_alleles( alleles, valid_alleles=None): require_iterable_of(alleles, string_types, "HLA alleles") missing_alleles = [ allele for allele in alleles if allele not in valid_alleles ] ...
Given a list of HLA alleles and an optional list of valid HLA alleles, return a set of alleles that we will pass into the MHC binding predictor.
11,869
def which(program, add_win_suffixes=True): def is_exe(fpath): return os.path.isfile(fpath) and os.access(fpath, os.X_OK) fpath, fname = os.path.split(program) if add_win_suffixes and platform.system().lower() == and not ( fname.endswith() or fname.endswith()): fna...
Mimic 'which' command behavior. Adapted from https://stackoverflow.com/a/377028
11,870
def prettify_json_file(file_list): for json_file in set(file_list): if not json_file.endswith(".json"): logger.log_warning("Only JSON file format can be prettified, skip: {}".format(json_file)) continue logger.color_print("Start to prettify JSON file: {}".format(json_fi...
prettify JSON testcase format
11,871
def latexify(obj, **kwargs): if hasattr(obj, ): return obj.__pk_latex__(**kwargs) if isinstance(obj, text_type): from .unicode_to_latex import unicode_to_latex return unicode_to_latex(obj) if isinstance(obj, bool): raise ValueError( % obj) if isinstance(o...
Render an object in LaTeX appropriately.
11,872
def _asarray(self, vec): shape = self.domain[0, 0].shape + self.pshape arr = np.empty(shape, dtype=self.domain.dtype) for i, xi in enumerate(vec): for j, xij in enumerate(xi): arr[..., i, j] = xij.asarray() return arr
Convert ``x`` to an array. Here the indices are changed such that the "outer" indices come last in order to have the access order as `numpy.linalg.svd` needs it. This is the inverse of `_asvector`.
11,873
def file_download(context, id, file_id, target): dci_file.download(context, id=id, file_id=file_id, target=target)
file_download(context, id, path) Download a job file >>> dcictl job-download-file [OPTIONS] :param string id: ID of the job to download file [required] :param string file_id: ID of the job file to download [required] :param string target: Destination file [required]
11,874
def add(addon, dev, interactive): application = get_current_application() application.add( addon, dev=dev, interactive=interactive )
Add a dependency. Examples: $ django add dynamic-rest==1.5.0 + dynamic-rest == 1.5.0
11,875
def get_locale(): * ret = lc_ctl = salt.utils.systemd.booted(__context__) if lc_ctl and not (__grains__[] in [] and __grains__[] in [12]): ret = (_parse_dbus_locale() if dbus is not None else _localectl_status()[]).get(, ) else: if in __grains__[]: cmd = ...
Get the current system locale CLI Example: .. code-block:: bash salt '*' locale.get_locale
11,876
def libvlc_media_list_player_new(p_instance): f = _Cfunctions.get(, None) or \ _Cfunction(, ((1,),), class_result(MediaListPlayer), ctypes.c_void_p, Instance) return f(p_instance)
Create new media_list_player. @param p_instance: libvlc instance. @return: media list player instance or NULL on error.
11,877
def cv(params, dtrain, num_boost_round=10, nfold=3, stratified=False, folds=None, metrics=(), obj=None, feval=None, maximize=False, early_stopping_rounds=None, fpreproc=None, as_pandas=True, verbose_eval=None, show_stdv=True, seed=0, callbacks=None, shuffle=True): if stratified is Tru...
Cross-validation with given parameters. Parameters ---------- params : dict Booster params. dtrain : DMatrix Data to be trained. num_boost_round : int Number of boosting iterations. nfold : int Number of folds in CV. stratified : bool Perform stratifi...
11,878
def resample_melody_series(times, frequencies, voicing, times_new, kind=): if times.shape == times_new.shape and np.allclose(times, times_new): return frequencies, voicing.astype(np.bool) if not (np.allclose(np.diff(times), np.diff(times).mean()) or ...
Resamples frequency and voicing time series to a new timescale. Maintains any zero ("unvoiced") values in frequencies. If ``times`` and ``times_new`` are equivalent, no resampling will be performed. Parameters ---------- times : np.ndarray Times of each frequency value frequencies ...
11,879
def set_eol_chars(self, text): if not is_text_string(text): text = to_text_string(text) eol_chars = sourcecode.get_eol_chars(text) is_document_modified = eol_chars is not None and self.eol_chars is not None self.eol_chars = eol_chars if is_document_mod...
Set widget end-of-line (EOL) characters from text (analyzes text)
11,880
def flip(self): self._load() groups = self.config.keys() tabular = {} for g in groups: config = self.config[g] for k in config: r = tabular.get(k, {}) r[g] = config[k] tabular[k] = r return tabular
Provide flip view to compare how key/value pair is defined in each environment for administrative usage. :rtype: dict
11,881
def contains_rva(self, rva): if (self.next_section_virtual_address is not None and self.next_section_virtual_address > self.VirtualAddress and VirtualAddress_adj + size > self.next_section_virtual_address): size = self.next_section_vir...
Check whether the section contains the address provided.
11,882
def find_best_root(self, force_positive=True, slope=None): self._calculate_averages() best_root = {"chisq": np.inf} for n in self.tree.find_clades(): if n==self.tree.root: continue tv = self.tip_value(n) bv = self.branch_value(n) ...
determine the position on the tree that minimizes the bilinear product of the inverse covariance and the data vectors. Returns ------- best_root : (dict) dictionary with the node, the fraction `x` at which the branch is to be split, and the regression parameters
11,883
def pipe_dateformat(context=None, _INPUT=None, conf=None, **kwargs): conf = DotDict(conf) loop_with = kwargs.pop(, None) date_format = conf.get(, **kwargs) for item in _INPUT: _with = item.get(loop_with, **kwargs) if loop_with else item try: date_stri...
Formats a datetime value. Loopable. Parameters ---------- context : pipe2py.Context object _INPUT : pipedatebuilder pipe like object (iterable of date timetuples) conf : { 'format': {'value': <'%B %d, %Y'>}, 'timezone': {'value': <'EST'>} } Yields ------ _OUTPUT : f...
11,884
def add(self, device): if not isinstance(device, Device): raise TypeError() self.__devices.append(device)
Add device.
11,885
def connect(self, From, to, protocolName, clientFactory, chooser): publicIP = self._determinePublicIP() A = dict(From=From, to=to, protocol=protocolName) if self.service.dispatcher is not None: ...
Issue an INBOUND command, creating a virtual connection to the peer, given identifying information about the endpoint to connect to, and a protocol factory. @param clientFactory: a *Client* ProtocolFactory instance which will generate a protocol upon connect. @return: a Deferre...
11,886
def pickle_dump(self): with open(os.path.join(self.workdir, self.PICKLE_FNAME), mode="wb") as fh: pickle.dump(self, fh)
Save the status of the object in pickle format.
11,887
def mcp_als(X, rank, mask, random_state=None, init=, **options): optim_utils._check_cpd_inputs(X, rank) U, _ = optim_utils._get_initial_ktensor(init, X, rank, random_state, scale_norm=False) result = FitResult(U, , **options) normX = np.linalg.norm((X * mask)) while result.sti...
Fits CP Decomposition with missing data using Alternating Least Squares (ALS). Parameters ---------- X : (I_1, ..., I_N) array_like A tensor with ``X.ndim >= 3``. rank : integer The `rank` sets the number of components to be computed. mask : (I_1, ..., I_N) array_like A bi...
11,888
def display_task_progress( self, instance, project, region, request_id=None, user=None, poll_interval=60): total_completed = 0 while True: task_results = self.client.get_task_data( instance, project, region, request_id=request_id, user=user) tasks = {task[]: task for task...
Displays the overall progress of tasks in a Turbinia job. Args: instance (string): The name of the Turbinia instance project (string): The project containing the disk to process region (string): Region where turbinia is configured. request_id (string): The request ID provided by Turbinia. ...
11,889
def is_valid_filename(filename, return_ext=False): ext = Path(filename).suffixes if len(ext) > 2: logg.warn( .format(ext, ext[-2:])) ext = ext[-2:] if len(ext) == 2 and ext[0][1:] in text_exts and ext[1][1:] in (, ): return ext[0][1:] if return_ext else ...
Check whether the argument is a filename.
11,890
def fuzzy_get_value(obj, approximate_key, default=None, **kwargs): dict_obj = OrderedDict(obj) try: return dict_obj[list(dict_obj.keys())[int(approximate_key)]] except (ValueError, IndexError): pass return fuzzy_get(dict_obj, approximate_key, key_and_value=False, **kwargs)
Like fuzzy_get, but assume the obj is dict-like and return the value without the key Notes: Argument order is in reverse order relative to `fuzzywuzzy.process.extractOne()` but in the same order as get(self, key) method on dicts Arguments: obj (dict-like): object to run the get method on u...
11,891
def render(self, template, context=None, at_paths=None, at_encoding=anytemplate.compat.ENCODING, **kwargs): kwargs = self.filter_options(kwargs, self.render_valid_options()) paths = anytemplate.utils.mk_template_paths(template, at_paths) if context is None: co...
:param template: Template file path :param context: A dict or dict-like object to instantiate given template file :param at_paths: Template search paths :param at_encoding: Template encoding :param kwargs: Keyword arguments passed to the template engine to render ...
11,892
def covar(X, remove_mean=False, modify_data=False, weights=None, sparse_mode=, sparse_tol=0.0): w, s, M = moments_XX(X, remove_mean=remove_mean, weights=weights, modify_data=modify_data, sparse_mode=sparse_mode, sparse_tol=sparse_tol) return M / float(w)
Computes the covariance matrix of X Computes .. math: C_XX &=& X^\top X while exploiting zero or constant columns in the data matrix. WARNING: Directly use moments_XX if you can. This function does an additional constant-matrix multiplication and does not return the mean. Parameters ...
11,893
def asset_path(path, format_kwargs={}, keep_slash=False): if format_kwargs: path = path.format_map(format_kwargs) has_slash = path.endswith(os.sep) if in path: package_name, *rel_path = path.split(, 1) else: package_name, rel_path = path, () try: package = im...
Get absolute path to asset in package. ``path`` can be just a package name like 'package' or it can be a package name and a relative file system path like 'package:util'. If ``path`` ends with a slash, it will be stripped unless ``keep_slash`` is set (for use with ``rsync``, for example). >>> fil...
11,894
def price_options(S=100.0, K=100.0, sigma=0.25, r=0.05, days=260, paths=10000): import numpy as np from math import exp,sqrt h = 1.0/days const1 = exp((r-0.5*sigma**2)*h) const2 = sigma*sqrt(h) stock_price = S*np.ones(paths, dtype=) stock_price_sum = np.zeros(paths, dtype=) for...
Price European and Asian options using a Monte Carlo method. Parameters ---------- S : float The initial price of the stock. K : float The strike price of the option. sigma : float The volatility of the stock. r : float The risk free interest rate. days : int...
11,895
def _add_constraints(self, relation): expression = relation.expression constr_count = sum(True for _ in expression.value_sets()) if constr_count == 0: return [] row_indices = count(swiglpk.glp_add_rows(self._p, constr_count)) names = [] for i, valu...
Add the given relation as one or more constraints. Return a list of the names of the constraints added.
11,896
def format_path(path): localhost:30000managercomp0.rtclocalhost:30000/manager/comp0.rtclocalhostmanagercomp0.rtcinlocalhost/manager/comp0.rtc:in/localhostmanagercomp0.rtc/localhost/manager/comp0.rtc/localhostmanagercomp0.rtcin/localhost/manager/comp0.rtc:inmanagercomp0.rtcmanager/comp0.rtccomp0.rtccomp0.rtc i...
Formats a path as a string, placing / between each component. @param path A path in rtctree format, as a tuple with the port name as the second component. Examples: >>> format_path((['localhost:30000', 'manager', 'comp0.rtc'], None)) 'localhost:30000/manager/comp0.rtc' ...
11,897
def add_pegasus_profile(self, namespace, key, value): self.__pegasus_profile.append((str(namespace),str(key),str(value)))
Add a Pegasus profile to this job which will be written to the dax as <profile namespace="NAMESPACE" key="KEY">VALUE</profile> This can be used to add classads to particular jobs in the DAX @param namespace: A valid Pegasus namespace, e.g. condor. @param key: The name of the attribute. @param value:...
11,898
def repackage_to_staging(output_path): import google.datalab.ml as ml package_root = os.path.join(os.path.dirname(__file__), ) setup_py = os.path.join(os.path.dirname(__file__), ) staging_package_url = os.path.join(output_path, , ) ml.package_and_copy(package_root, setup_py, staging_package_url) ...
Repackage it from local installed location and copy it to GCS.
11,899
def create_qualification_type(Name=None, Keywords=None, Description=None, QualificationTypeStatus=None, RetryDelayInSeconds=None, Test=None, AnswerKey=None, TestDurationInSeconds=None, AutoGranted=None, AutoGrantedValue=None): pass
The CreateQualificationType operation creates a new Qualification type, which is represented by a QualificationType data structure. See also: AWS API Documentation :example: response = client.create_qualification_type( Name='string', Keywords='string', Description='string', ...