docstring
stringlengths
52
499
function
stringlengths
67
35.2k
__index_level_0__
int64
52.6k
1.16M
Get PyPI package names from a list of imports. Args: pkgs (List[str]): List of import names. Returns: List[str]: The corresponding PyPI package names.
def get_pkg_names(pkgs): result = set() with open(join("mapping"), "r") as f: data = dict(x.strip().split(":") for x in f) for pkg in pkgs: # Look up the mapped requirement. If a mapping isn't found, # simply use the package name. result.add(data.get(pkg, pkg)) # Ret...
250,162
Converts data string to iterable. Parameters: ----------- datastring: string, defaults to None \tThe data string to be converted. \tself.get_clipboard() is called if set to None sep: string \tSeparator for columns in datastring
def _convert_clipboard(self, datastring=None, sep='\t'): if datastring is None: datastring = self.get_clipboard() data_it = ((ele for ele in line.split(sep)) for line in datastring.splitlines()) return data_it
250,966
Return list of all positions of event_find_string in MainGrid. Only the code is searched. The result is not searched here. Parameters: ----------- gridpos: 3-tuple of Integer \tPosition at which the search starts find_string: String \tString to find in grid ...
def find_all(self, find_string, flags): code_array = self.grid.code_array string_match = code_array.string_match find_keys = [] for key in code_array: if string_match(code_array(key), find_string, flags) is not None: find_keys.append(key) ...
251,035
Return next position of event_find_string in MainGrid Parameters: ----------- gridpos: 3-tuple of Integer \tPosition at which the search starts find_string: String \tString to find in grid flags: List of strings \tSearch flag out of \t["UP" xor "D...
def find(self, gridpos, find_string, flags, search_result=True): findfunc = self.grid.code_array.findnextmatch if "DOWN" in flags: if gridpos[0] < self.grid.code_array.shape[0]: gridpos[0] += 1 elif gridpos[1] < self.grid.code_array.shape[1]: ...
251,036
Returns a tuple with the position of the next match of find_string Returns None if string not found. Parameters: ----------- startkey: Start position of search find_string:String to be searched for flags: List of strings, out of ["UP" xor "DOW...
def findnextmatch(self, startkey, find_string, flags, search_result=True): assert "UP" in flags or "DOWN" in flags assert not ("UP" in flags and "DOWN" in flags) if search_result: def is_matching(key, find_string, flags): code = self(key) if...
251,264
Constructor. Args: channel: A grpc.Channel.
def __init__(self, channel): self.Login = channel.unary_unary( '/api.Dgraph/Login', request_serializer=api__pb2.LoginRequest.SerializeToString, response_deserializer=api__pb2.Response.FromString, ) self.Query = channel.unary_unary( '/api.Dgraph/Query', reques...
251,338
Semaphore lock. Semaphore logic is implemented in the lua/semaphore.lua script. Individual locks within the semaphore are managed inside a ZSET using scores to track when they expire. Arguments: redis: Redis client name: Name of lock. Used as ZSET key. ...
def __init__(self, redis, name, lock_id, timeout, max_locks=1): self.redis = redis self.name = name self.lock_id = lock_id self.max_locks = max_locks self.timeout = timeout with open(os.path.join(os.path.dirname(os.path.realpath(__file__)), ...
251,449
Set system lock for the semaphore. Sets a system lock that will expire in timeout seconds. This overrides all other locks. Existing locks cannot be renewed and no new locks will be permitted until the system lock expires. Arguments: redis: Redis client n...
def set_system_lock(cls, redis, name, timeout): pipeline = redis.pipeline() pipeline.zadd(name, SYSTEM_LOCK_ID, time.time() + timeout) pipeline.expire(name, timeout + 10) # timeout plus buffer for troubleshooting pipeline.execute()
251,450
Internal method to process a task batch from the given queue. Args: queue: Queue name to be processed Returns: Task IDs: List of tasks that were processed (even if there was an error so that client code can assume the queue is empty ...
def _process_from_queue(self, queue): now = time.time() log = self.log.bind(queue=queue) batch_size = self._get_queue_batch_size(queue) queue_lock, failed_to_acquire = self._get_queue_lock(queue, log) if failed_to_acquire: return [], -1 # Move an ...
251,483
Constructor. Args: channel: A grpc.Channel.
def __init__(self, channel): self.Dump = channel.unary_stream( '/debug.Debug/Dump', request_serializer=client_dot_debug_dot_debug__pb2.DumpRequest.SerializeToString, response_deserializer=google_dot_protobuf_dot_wrappers__pb2.BytesValue.FromString, ) self.Profile = channel.u...
252,002
Constructor. Args: channel: A grpc.Channel.
def __init__(self, channel): self.Health = channel.unary_unary( '/health.Health/Health', request_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString, response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString, )
252,004
Constructor. Args: channel: A grpc.Channel.
def __init__(self, channel): self.Activate = channel.unary_unary( '/auth.API/Activate', request_serializer=client_dot_auth_dot_auth__pb2.ActivateRequest.SerializeToString, response_deserializer=client_dot_auth_dot_auth__pb2.ActivateResponse.FromString, ) self.Deactivate = ch...
252,012
Constructor. Args: channel: A grpc.Channel.
def __init__(self, channel): self.DeployStorageSecret = channel.unary_unary( '/deploy.API/DeployStorageSecret', request_serializer=client_dot_deploy_dot_deploy__pb2.DeployStorageSecretRequest.SerializeToString, response_deserializer=client_dot_deploy_dot_deploy__pb2.DeployStorageSecretR...
252,014
Constructor. Args: channel: A grpc.Channel.
def __init__(self, channel): self.CreateJob = channel.unary_unary( '/pps.API/CreateJob', request_serializer=client_dot_pps_dot_pps__pb2.CreateJobRequest.SerializeToString, response_deserializer=client_dot_pps_dot_pps__pb2.Job.FromString, ) self.InspectJob = channel.unary_una...
252,017
Constructor. Args: channel: A grpc.Channel.
def __init__(self, channel): self.CreateRepo = channel.unary_unary( '/pfs.API/CreateRepo', request_serializer=client_dot_pfs_dot_pfs__pb2.CreateRepoRequest.SerializeToString, response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString, ) self.InspectRepo = chan...
252,020
Constructor. Args: channel: A grpc.Channel.
def __init__(self, channel): self.PutObject = channel.stream_unary( '/pfs.ObjectAPI/PutObject', request_serializer=client_dot_pfs_dot_pfs__pb2.PutObjectRequest.SerializeToString, response_deserializer=client_dot_pfs_dot_pfs__pb2.Object.FromString, ) self.PutObjectSplit = cha...
252,021
Constructor. Args: channel: A grpc.Channel.
def __init__(self, channel): self.Activate = channel.unary_unary( '/enterprise.API/Activate', request_serializer=client_dot_enterprise_dot_enterprise__pb2.ActivateRequest.SerializeToString, response_deserializer=client_dot_enterprise_dot_enterprise__pb2.ActivateResponse.FromString, ...
252,023
Creates a new Repo object in PFS with the given name. Repos are the top level data object in PFS and should be used to store data of a similar type. For example rather than having a single Repo for an entire project you might have separate Repos for logs, metrics, database dumps etc. ...
def create_repo(self, repo_name, description=None): req = proto.CreateRepoRequest(repo=proto.Repo(name=repo_name), description=description) self.stub.CreateRepo(req, metadata=self.metadata)
252,024
Returns info about a specific Repo. Params: * repo_name: Name of the repo.
def inspect_repo(self, repo_name): req = proto.InspectRepoRequest(repo=proto.Repo(name=repo_name)) res = self.stub.InspectRepo(req, metadata=self.metadata) return res
252,025
Deletes a repo and reclaims the storage space it was using. Params: * repo_name: The name of the repo. * force: If set to true, the repo will be removed regardless of errors. This argument should be used with care. * all: Delete all repos.
def delete_repo(self, repo_name=None, force=False, all=False): if not all: if repo_name: req = proto.DeleteRepoRequest(repo=proto.Repo(name=repo_name), force=force) self.stub.DeleteRepo(req, metadata=self.metadata) else: raise Valu...
252,027
Ends the process of committing data to a Repo and persists the Commit. Once a Commit is finished the data becomes immutable and future attempts to write to it with PutFile will error. Params: * commit: A tuple, string, or Commit object representing the commit.
def finish_commit(self, commit): req = proto.FinishCommitRequest(commit=commit_from(commit)) res = self.stub.FinishCommit(req, metadata=self.metadata) return res
252,029
Returns info about a specific Commit. Params: * commit: A tuple, string, or Commit object representing the commit.
def inspect_commit(self, commit): req = proto.InspectCommitRequest(commit=commit_from(commit)) return self.stub.InspectCommit(req, metadata=self.metadata)
252,031
Deletes a commit. Params: * commit: A tuple, string, or Commit object representing the commit.
def delete_commit(self, commit): req = proto.DeleteCommitRequest(commit=commit_from(commit)) self.stub.DeleteCommit(req, metadata=self.metadata)
252,034
SubscribeCommit is like ListCommit but it keeps listening for commits as they come in. This returns an iterator Commit objects. Params: * repo_name: Name of the repo. * branch: Branch to subscribe to. * from_commit_id: Optional. Only commits created since this commit are...
def subscribe_commit(self, repo_name, branch, from_commit_id=None): repo = proto.Repo(name=repo_name) req = proto.SubscribeCommitRequest(repo=repo, branch=branch) if from_commit_id is not None: getattr(req, 'from').CopyFrom(proto.Commit(repo=repo, id=from_commit_id)) ...
252,036
Lists the active Branch objects on a Repo. Params: * repo_name: The name of the repo.
def list_branch(self, repo_name): req = proto.ListBranchRequest(repo=proto.Repo(name=repo_name)) res = self.stub.ListBranch(req, metadata=self.metadata) if hasattr(res, 'branch_info'): return res.branch_info return []
252,037
Sets a commit and its ancestors as a branch. Params: * commit: A tuple, string, or Commit object representing the commit. * branch_name: The name for the branch to set.
def set_branch(self, commit, branch_name): res = proto.SetBranchRequest(commit=commit_from(commit), branch=branch_name) self.stub.SetBranch(res, metadata=self.metadata)
252,038
Deletes a branch, but leaves the commits themselves intact. In other words, those commits can still be accessed via commit IDs and other branches they happen to be on. Params: * repo_name: The name of the repo. * branch_name: The name of the branch to delete.
def delete_branch(self, repo_name, branch_name): res = proto.DeleteBranchRequest(repo=Repo(name=repo_name), branch=branch_name) self.stub.DeleteBranch(res, metadata=self.metadata)
252,039
Puts a file using the content found at a URL. The URL is sent to the server which performs the request. Params: * commit: A tuple, string, or Commit object representing the commit. * path: The path to the file. * url: The url of the file to put. * recursive: allow for re...
def put_file_url(self, commit, path, url, recursive=False): req = iter([ proto.PutFileRequest( file=proto.File(commit=commit_from(commit), path=path), url=url, recursive=recursive ) ]) self.stub.PutFile(req, metadat...
252,041
Returns the contents of a list of files at a specific Commit as a dictionary of file paths to data. Params: * commit: A tuple, string, or Commit object representing the commit. * paths: A list of paths to retrieve. * recursive: If True, will go into each directory in the list ...
def get_files(self, commit, paths, recursive=False): filtered_file_infos = [] for path in paths: fi = self.inspect_file(commit, path) if fi.file_type == proto.FILE: filtered_file_infos.append(fi) else: filtered_file_infos += se...
252,043
Returns info about a specific file. Params: * commit: A tuple, string, or Commit object representing the commit. * path: Path to file.
def inspect_file(self, commit, path): req = proto.InspectFileRequest(file=proto.File(commit=commit_from(commit), path=path)) res = self.stub.InspectFile(req, metadata=self.metadata) return res
252,044
Lists the files in a directory. Params: * commit: A tuple, string, or Commit object representing the commit. * path: The path to the directory. * recursive: If True, continue listing the files for sub-directories.
def list_file(self, commit, path, recursive=False): req = proto.ListFileRequest( file=proto.File(commit=commit_from(commit), path=path) ) res = self.stub.ListFile(req, metadata=self.metadata) file_infos = res.file_info if recursive: dirs = [f for...
252,045
Deletes a file from a Commit. DeleteFile leaves a tombstone in the Commit, assuming the file isn't written to later attempting to get the file from the finished commit will result in not found error. The file will of course remain intact in the Commit's parent. Params: * commit:...
def delete_file(self, commit, path): req = proto.DeleteFileRequest(file=proto.File(commit=commit_from(commit), path=path)) self.stub.DeleteFile(req, metadata=self.metadata)
252,047
Constructor. Args: channel: A grpc.Channel.
def __init__(self, channel): self.GetVersion = channel.unary_unary( '/versionpb.API/GetVersion', request_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString, response_deserializer=client_dot_version_dot_versionpb_dot_version__pb2.Version.FromString, )
252,049
r"""[DEPRECATED] Get descriptors from module. Parameters: mdl(module): module to search Returns: [Descriptor]
def get_descriptors_from_module(mdl, submodule=False): r warnings.warn("use get_descriptors_in_module", DeprecationWarning) __all__ = getattr(mdl, "__all__", None) if __all__ is None: __all__ = dir(mdl) all_functions = (getattr(mdl, name) for name in __all__ if name[:1] != "_") if subm...
252,787
r"""Get descriptors in module. Parameters: mdl(module): module to search submodule(bool): search recursively Returns: Iterator[Descriptor]
def get_descriptors_in_module(mdl, submodule=True): r __all__ = getattr(mdl, "__all__", None) if __all__ is None: __all__ = dir(mdl) all_values = (getattr(mdl, name) for name in __all__ if name[:1] != "_") if submodule: for v in all_values: if is_descriptor_class(v): ...
252,788
Register Descriptors from json descriptor objects. Parameters: obj(list or dict): descriptors to register
def register_json(self, obj): if not isinstance(obj, list): obj = [obj] self.register(Descriptor.from_json(j) for j in obj)
252,790
r"""Register descriptors. Descriptor-like: * Descriptor instance: self * Descriptor class: use Descriptor.preset() method * module: use Descriptor-likes in module * Iterable: use Descriptor-likes in Iterable Parameters: desc(Descriptor-like):...
def register(self, desc, version=None, ignore_3D=False): r if version is None: version = __version__ version = StrictVersion(version) return self._register(desc, version, ignore_3D)
252,795
Output message. Parameters: s(str): message to output file(file-like): output to end(str): end mark of message Return: None
def echo(self, s, file=sys.stdout, end="\n"): p = getattr(self, "_progress_bar", None) if p is not None: p.write(s, file=file, end="\n") return print(s, file=file, end="\n")
252,803
Create Descriptor instance from json dict. Parameters: obj(dict): descriptor dict Returns: Descriptor: descriptor
def _Descriptor_from_json(self, obj): descs = getattr(self, "_all_descriptors", None) if descs is None: from mordred import descriptors descs = { cls.__name__: cls for cls in get_descriptors_in_module(descriptors) } descs[ConstDescriptor.__name__] = ...
252,935
r"""Replace missing value to "value". Parameters: value: value that missing value is replaced Returns: Result
def fill_missing(self, value=np.nan): r return self.__class__( self.mol, [(value if is_missing(v) else v) for v in self.values()], self.keys(), )
253,058
r"""Convert Result to dict. Parameters: rawkey(bool): * True: dict key is Descriptor instance * False: dict key is str Returns: dict
def asdict(self, rawkey=False): r if rawkey: return dict(self.items()) else: return { str(k): v for k, v in self.items() }
253,061
Get parameters for ``crop`` for a random crop. Args: img (PIL Image): Image to be cropped. output_size (tuple): Expected output size of the crop. Returns: tuple: params (i, j, h, w) to be passed to ``crop`` for random crop.
def get_params(img, output_size): w, h, *_ = img.shape th, tw = output_size if w == tw and h == th: return 0, 0, h, w i = random.randint(0, h - th) j = random.randint(0, w - tw) return i, j, th, tw
256,771
Performs a single optimization step. Arguments: closure (callable, optional): A closure that reevaluates the model and returns the loss.
def step(self, closure=None): loss = None if closure is not None: loss = closure() for group in self.param_groups: for p in group['params']: if p.grad is None: continue grad = p.grad.data if gra...
257,046
Rotates an image by deg degrees Arguments: deg (float): degree to rotate.
def rotate_img(im, deg, mode=cv2.BORDER_CONSTANT, interpolation=cv2.INTER_AREA): r,c,*_ = im.shape M = cv2.getRotationMatrix2D((c//2,r//2),deg,1) return cv2.warpAffine(im,M,(c,r), borderMode=mode, flags=cv2.WARP_FILL_OUTLIERS+interpolation)
257,117
Create an IMDB dataset instance given a path and fields. Arguments: path: Path to the dataset's highest level directory text_field: The field that will be used for text data. label_field: The field that will be used for label data. Remaining keyword arguments: Pa...
def __init__(self, path, text_field, label_field, **kwargs): cache_file = os.path.join(path, 'examples_cache.pk') fields = [('text', text_field), ('label', label_field)] if os.path.exists(cache_file): with open(cache_file, 'rb') as fp: examples = pickle.loa...
257,212
Get the type of identifier name from the type environment env. Args: name: The identifier name env: The type environment mapping from identifier names to types non_generic: A set of non-generic TypeVariables Raises: ParseError: Raised if name is an undefined symbol in the type ...
def get_type(name, env, non_generic): if name in env: if isinstance(env[name], MultiType): return clone(env[name]) return fresh(env[name], non_generic) else: print("W: Undefined symbol {0}".format(name)) return TypeVariable()
257,902
Makes a copy of a type expression. The type t is copied. The generic variables are duplicated and the non_generic variables are shared. Args: t: A type to be copied. non_generic: A set of non-generic TypeVariables
def fresh(t, non_generic): mappings = {} # A mapping of TypeVariables to TypeVariables def freshrec(tp): p = prune(tp) if isinstance(p, TypeVariable): if is_generic(p, non_generic): if p not in mappings: mappings[p] = TypeVariable() ...
257,903
Unify the two types t1 and t2. Makes the types t1 and t2 the same. Args: t1: The first type to be made equivalent t2: The second type to be be equivalent Returns: None Raises: InferenceError: Raised if the types cannot be unified.
def unify(t1, t2): a = prune(t1) b = prune(t2) if isinstance(a, TypeVariable): if a != b: if occurs_in_type(a, b): raise InferenceError("recursive unification") a.instance = b elif isinstance(b, TypeVariable): unify(b, a) elif isinstance(...
257,905
Checks whether a type variable occurs in a type expression. Note: Must be called with v pre-pruned Args: v: The TypeVariable to be tested for type2: The type in which to search Returns: True if v occurs in type2, otherwise False
def occurs_in_type(v, type2): pruned_type2 = prune(type2) if pruned_type2 == v: return True elif isinstance(pruned_type2, TypeOperator): return occurs_in(v, pruned_type2.types) return False
257,908
N-Queens solver. Args: queen_count: the number of queens to solve for. This is also the board size. Yields: Solutions to the problem. Each yielded value is looks like (3, 8, 2, 1, 4, ..., 6) where each number is the column position for the queen, and the index into ...
def n_queens(queen_count): out =list() cols = range(queen_count) #for vec in permutations(cols): for vec in permutations(cols,None): if (queen_count == len(set(vec[i]+i for i in cols)) == len(set(vec[i]-i for i in cols))): #yield vec out.appen...
258,476
Matplotlib patch object for this region (`matplotlib.patches.Rectangle`). Parameters: ----------- origin : array_like, optional The ``(x, y)`` pixel position of the origin of the displayed image. Default is (0, 0). kwargs : `dict` All keywords that a ...
def as_artist(self, origin=(0, 0), **kwargs): from matplotlib.patches import Rectangle xy = self._lower_left_xy() xy = xy[0] - origin[0], xy[1] - origin[1] width = self.width height = self.height # From the docstring: MPL expects "rotation in degrees (anti-clockw...
258,584
Matplotlib patch object for this region (`matplotlib.patches.Ellipse`). Parameters: ----------- origin : array_like, optional The ``(x, y)`` pixel position of the origin of the displayed image. Default is (0, 0). kwargs : `dict` All keywords that a `~...
def as_artist(self, origin=(0, 0), **kwargs): from matplotlib.patches import Ellipse xy = self.center.x - origin[0], self.center.y - origin[1] width = self.width height = self.height # From the docstring: MPL expects "rotation in degrees (anti-clockwise)" angle =...
258,592
Matplotlib patch object for this region (`matplotlib.patches.Polygon`). Parameters: ----------- origin : array_like, optional The ``(x, y)`` pixel position of the origin of the displayed image. Default is (0, 0). kwargs : `dict` All keywords that a `~...
def as_artist(self, origin=(0, 0), **kwargs): from matplotlib.patches import Polygon xy = np.vstack([self.vertices.x - origin[0], self.vertices.y - origin[1]]).transpose() mpl_params = self.mpl_properties_default('patch') mpl_params.update(kwargs) ...
258,702
Solve for the value function and associated Markov decision rule by iterating over the value function. Parameters: ----------- model : "dtmscc" model. Must contain a 'felicity' function. grid : grid options dr : decision rule to evaluate Returns: -------- md...
def value_iteration(model, grid={}, tol=1e-6, maxit=500, maxit_howard=20, verbose=False, details=True): transition = model.functions['transition'] felicity = model.functions['felicity'] ...
259,367
Compute value function corresponding to policy ``dr`` Parameters: ----------- model: "dtcscc" model. Must contain a 'value' function. mdr: decision rule to evaluate Returns: -------- decision rule: value function (a function of the space similar to a decision rul...
def evaluate_policy(model, mdr, tol=1e-8, maxit=2000, grid={}, verbose=True, initial_guess=None, hook=None, integration_orders=None, details...
259,369
Get a stream of Transactions for an Account starting from when the request is made. Args: accountID: Account Identifier Returns: v20.response.Response containing the results from submitting the request
def stream( self, accountID, **kwargs ): request = Request( 'GET', '/v3/accounts/{accountID}/transactions/stream' ) request.set_path_param( 'accountID', accountID ) request.set_stream(True) ...
260,658
Fetch a price for an instrument. Accounts are not associated in any way with this endpoint. Args: instrument: Name of the Instrument time: The time at which the desired price is in effect. The current price is returned if no time i...
def price( self, instrument, **kwargs ): request = Request( 'GET', '/v3/instruments/{instrument}/price' ) request.set_path_param( 'instrument', instrument ) request.set_param( 'tim...
260,689
Replace an Order in an Account by simultaneously cancelling it and creating a replacement Order Args: accountID: Account Identifier orderSpecifier: The Order Specifier order: Specification of the replacing Order ...
def replace( self, accountID, orderSpecifier, **kwargs ): request = Request( 'PUT', '/v3/accounts/{accountID}/orders/{orderSpecifier}' ) request.set_path_param( 'accountID', accountID ) ...
260,724
Cancel a pending Order in an Account Args: accountID: Account Identifier orderSpecifier: The Order Specifier Returns: v20.response.Response containing the results from submitting the request
def cancel( self, accountID, orderSpecifier, **kwargs ): request = Request( 'PUT', '/v3/accounts/{accountID}/orders/{orderSpecifier}/cancel' ) request.set_path_param( 'accountID', accountID ) ...
260,725
Shortcut to create a Market Order in an Account Args: accountID : The ID of the Account kwargs : The arguments to create a MarketOrderRequest Returns: v20.response.Response containing the results from submitting the request
def market(self, accountID, **kwargs): return self.create( accountID, order=MarketOrderRequest(**kwargs) )
260,727
Shortcut to create a Limit Order in an Account Args: accountID : The ID of the Account kwargs : The arguments to create a LimitOrderRequest Returns: v20.response.Response containing the results from submitting the request
def limit(self, accountID, **kwargs): return self.create( accountID, order=LimitOrderRequest(**kwargs) )
260,728
Shortcut to replace a pending Limit Order in an Account Args: accountID : The ID of the Account orderID : The ID of the Limit Order to replace kwargs : The arguments to create a LimitOrderRequest Returns: v20.response.Response containing the results from...
def limit_replace(self, accountID, orderID, **kwargs): return self.replace( accountID, orderID, order=LimitOrderRequest(**kwargs) )
260,729
Shortcut to create a Stop Order in an Account Args: accountID : The ID of the Account kwargs : The arguments to create a StopOrderRequest Returns: v20.response.Response containing the results from submitting the request
def stop(self, accountID, **kwargs): return self.create( accountID, order=StopOrderRequest(**kwargs) )
260,730
Shortcut to replace a pending Stop Order in an Account Args: accountID : The ID of the Account orderID : The ID of the Stop Order to replace kwargs : The arguments to create a StopOrderRequest Returns: v20.response.Response containing the results from su...
def stop_replace(self, accountID, orderID, **kwargs): return self.replace( accountID, orderID, order=StopOrderRequest(**kwargs) )
260,731
Shortcut to create a MarketIfTouched Order in an Account Args: accountID : The ID of the Account kwargs : The arguments to create a MarketIfTouchedOrderRequest Returns: v20.response.Response containing the results from submitting the request
def market_if_touched(self, accountID, **kwargs): return self.create( accountID, order=MarketIfTouchedOrderRequest(**kwargs) )
260,732
Shortcut to replace a pending MarketIfTouched Order in an Account Args: accountID : The ID of the Account orderID : The ID of the MarketIfTouched Order to replace kwargs : The arguments to create a MarketIfTouchedOrderRequest Returns: v20.response.Respon...
def market_if_touched_replace(self, accountID, orderID, **kwargs): return self.replace( accountID, orderID, order=MarketIfTouchedOrderRequest(**kwargs) )
260,733
Shortcut to create a Take Profit Order in an Account Args: accountID : The ID of the Account kwargs : The arguments to create a TakeProfitOrderRequest Returns: v20.response.Response containing the results from submitting the request
def take_profit(self, accountID, **kwargs): return self.create( accountID, order=TakeProfitOrderRequest(**kwargs) )
260,734
Shortcut to replace a pending Take Profit Order in an Account Args: accountID : The ID of the Account orderID : The ID of the Take Profit Order to replace kwargs : The arguments to create a TakeProfitOrderRequest Returns: v20.response.Response containing...
def take_profit_replace(self, accountID, orderID, **kwargs): return self.replace( accountID, orderID, order=TakeProfitOrderRequest(**kwargs) )
260,735
Shortcut to create a Stop Loss Order in an Account Args: accountID : The ID of the Account kwargs : The arguments to create a StopLossOrderRequest Returns: v20.response.Response containing the results from submitting the request
def stop_loss(self, accountID, **kwargs): return self.create( accountID, order=StopLossOrderRequest(**kwargs) )
260,736
Shortcut to replace a pending Stop Loss Order in an Account Args: accountID : The ID of the Account orderID : The ID of the Stop Loss Order to replace kwargs : The arguments to create a StopLossOrderRequest Returns: v20.response.Response containing the r...
def stop_loss_replace(self, accountID, orderID, **kwargs): return self.replace( accountID, orderID, order=StopLossOrderRequest(**kwargs) )
260,737
Shortcut to create a Trailing Stop Loss Order in an Account Args: accountID : The ID of the Account kwargs : The arguments to create a TrailingStopLossOrderRequest Returns: v20.response.Response containing the results from submitting the request
def trailing_stop_loss(self, accountID, **kwargs): return self.create( accountID, order=TrailingStopLossOrderRequest(**kwargs) )
260,738
Shortcut to replace a pending Trailing Stop Loss Order in an Account Args: accountID : The ID of the Account orderID : The ID of the Take Profit Order to replace kwargs : The arguments to create a TrailingStopLossOrderRequest Returns: v20.response.Respon...
def trailing_stop_loss_replace(self, accountID, orderID, **kwargs): return self.replace( accountID, orderID, order=TrailingStopLossOrderRequest(**kwargs) )
260,739
Set the token for the v20 context Args: token: The token used to access the v20 REST api
def set_token(self, token): self.token = token self.set_header( 'Authorization', "Bearer {}".format(token) )
260,747
Set the Accept-Datetime-Format header to an acceptable value Args: format: UNIX or RFC3339
def set_datetime_format(self, format): if not format in ["UNIX", "RFC3339"]: return self.datetime_format = format self.set_header("Accept-Datetime-Format", self.datetime_format)
260,748
Perform an HTTP request through the context Args: request: A v20.request.Request object Returns: A v20.response.Response object
def request(self, request): url = "{}{}".format(self._base_url, request.path) timeout = self.poll_timeout if request.stream is True: timeout = self.stream_timeout try: http_response = self._session.request( request.method, ...
260,749
Get a list of all Accounts authorized for the provided token. Args: Returns: v20.response.Response containing the results from submitting the request
def list( self, **kwargs ): request = Request( 'GET', '/v3/accounts' ) response = self.ctx.request(request) if response.content_type is None: return response if not response.content_type.startswith("application...
260,760
Set the client-configurable portions of an Account. Args: accountID: Account Identifier alias: Client-defined alias (name) for the Account marginRate: The string representation of a decimal number. Returns: ...
def configure( self, accountID, **kwargs ): request = Request( 'PATCH', '/v3/accounts/{accountID}/configuration' ) request.set_path_param( 'accountID', accountID ) body = EntityDict() ...
260,762
Fetch the user information for the specified user. This endpoint is intended to be used by the user themself to obtain their own information. Args: userSpecifier: The User Specifier Returns: v20.response.Response containing the results from submi...
def get_info( self, userSpecifier, **kwargs ): request = Request( 'GET', '/v3/users/{userSpecifier}' ) request.set_path_param( 'userSpecifier', userSpecifier ) response = self.ctx.request(requ...
260,765
Pulls tasks from the incoming tasks 0mq pipe onto the internal pending task queue Parameters: ----------- kill_event : threading.Event Event to let the thread know when it is time to die.
def pull_tasks(self, kill_event): logger.info("[TASK PULL THREAD] starting") poller = zmq.Poller() poller.register(self.task_incoming, zmq.POLLIN) # Send a registration message msg = self.create_reg_message() logger.debug("Sending registration message: {}".forma...
260,934
Listens on the pending_result_queue and sends out results via 0mq Parameters: ----------- kill_event : threading.Event Event to let the thread know when it is time to die.
def push_results(self, kill_event): # We set this timeout so that the thread checks the kill_event and does not # block forever on the internal result queue timeout = 0.1 # timer = time.time() logger.debug("[RESULT_PUSH_THREAD] Starting thread") while not kill_...
260,935
Add a stream log handler. Args: - filename (string): Name of the file to write logs to - name (string): Logger name - level (logging.LEVEL): Set the logging level. - format_string (string): Set the format string Returns: - None
def set_file_logger(filename: str, name: str = 'parsl', level: int = logging.DEBUG, format_string: Optional[str] = None): if format_string is None: format_string = "%(asctime)s.%(msecs)03d %(name)s:%(lineno)d [%(levelname)s] %(message)s" logger = logging.getLogger(name) logger.setLevel(loggin...
260,945
Look for inputs of the app that are remote files. Submit stage_in apps for such files and replace the file objects in the inputs list with corresponding DataFuture objects. Args: - executor (str) : executor where the app is going to be launched - args (List) : Positional...
def _add_input_deps(self, executor, args, kwargs): # Return if the task is _*_stage_in if executor == 'data_manager': return args, kwargs inputs = kwargs.get('inputs', []) for idx, f in enumerate(inputs): if isinstance(f, File) and f.is_remote(): ...
260,974
Count the number of unresolved futures on which a task depends. Args: - args (List[args]) : The list of args list to the fn - kwargs (Dict{kwargs}) : The dict of all kwargs passed to the fn Returns: - count, [list of dependencies]
def _gather_all_deps(self, args, kwargs): # Check the positional args depends = [] count = 0 for dep in args: if isinstance(dep, Future): if self.tasks[dep.tid]['status'] not in FINAL_STATES: count += 1 depends.exte...
260,975
Load a DataFlowKernel. Args: - config (Config) : Configuration to load. This config will be passed to a new DataFlowKernel instantiation which will be set as the active DataFlowKernel. Returns: - DataFlowKernel : The loaded DataFlowKernel object.
def load(cls, config: Optional[Config] = None): if cls._dfk is not None: raise RuntimeError('Config has already been loaded') if config is None: cls._dfk = DataFlowKernel(Config()) else: cls._dfk = DataFlowKernel(config) return cls._dfk
260,985
Pull tasks from the incoming tasks 0mq pipe onto the internal pending task queue Parameters: ----------- kill_event : threading.Event Event to let the thread know when it is time to die.
def migrate_tasks_to_internal(self, kill_event): logger.info("[TASK_PULL_THREAD] Starting") task_counter = 0 poller = zmq.Poller() poller.register(self.task_incoming, zmq.POLLIN) while not kill_event.is_set(): try: msg = self.task_incoming.re...
260,991
Start the NeedNameQeueu Parameters: ---------- TODO: Move task receiving to a thread
def start(self, poll_period=None): logger.info("Incoming ports bound") if poll_period is None: poll_period = self.poll_period start = time.time() count = 0 self._kill_event = threading.Event() self._task_puller_thread = threading.Thread(target=self...
260,993
Listens on the pending_result_queue and sends out results via 0mq Parameters: ----------- kill_event : threading.Event Event to let the thread know when it is time to die.
def push_results(self, kill_event): logger.debug("[RESULT_PUSH_THREAD] Starting thread") push_poll_period = max(10, self.poll_period) / 1000 # push_poll_period must be atleast 10 ms logger.debug("[RESULT_PUSH_THREAD] push poll period: {}".format(push_poll_period)) last_bea...
261,000
Initialize the DataManager. Args: - dfk (DataFlowKernel): The DataFlowKernel that this DataManager is managing data for. Kwargs: - max_threads (int): Number of threads. Default is 10. - executors (list of Executors): Executors for which data transfer will be managed.
def __init__(self, dfk, max_threads=10): self._scaling_enabled = False self.label = 'data_manager' self.dfk = dfk self.max_threads = max_threads self.globus = None self.managed = True
261,005
wtime_to_minutes Convert standard wallclock time string to minutes. Args: - Time_string in HH:MM:SS format Returns: (int) minutes
def wtime_to_minutes(time_string): hours, mins, seconds = time_string.split(':') total_mins = int(hours) * 60 + int(mins) if total_mins < 1: logger.warning("Time string '{}' parsed to {} minutes, less than 1".format(time_string, total_mins)) return total_mins
261,019
Peek at the DFK and the executors specified. We assume here that tasks are not held in a runnable state, and that all tasks from an app would be sent to a single specific executor, i.e tasks cannot be specified to go to one of more executors. Args: - tasks (task_ids...
def _strategy_simple(self, tasks, *args, kind=None, **kwargs): for label, executor in self.dfk.executors.items(): if not executor.scaling_enabled: continue # Tasks that are either pending completion active_tasks = executor.outstanding s...
261,046
Terminate the controller process and its child processes. Args: - None
def close(self): if self.reuse: logger.debug("Ipcontroller not shutting down: reuse enabled") return if self.mode == "manual": logger.debug("Ipcontroller not shutting down: Manual mode") return try: pgid = os.getpgid(self.pro...
261,061
Initialize the memoizer. Args: - dfk (DFK obj): The DFK object KWargs: - memoize (Bool): enable memoization or not. - checkpoint (Dict): A checkpoint loaded as a dict.
def __init__(self, dfk, memoize=True, checkpoint={}): self.dfk = dfk self.memoize = memoize if self.memoize: logger.info("App caching initialized") self.memo_lookup_table = checkpoint else: logger.info("App caching disabled for all apps") ...
261,062
Create a hash of the task inputs. This uses a serialization library borrowed from ipyparallel. If this fails here, then all ipp calls are also likely to fail due to failure at serialization. Args: - task (dict) : Task dictionary from dfk.tasks Returns: ...
def make_hash(self, task): # Function name TODO: Add fn body later t = [serialize_object(task['func_name'])[0], serialize_object(task['fn_hash'])[0], serialize_object(task['args'])[0], serialize_object(task['kwargs'])[0], serialize_object(task...
261,063
Updates the memoization lookup table with the result from a task. Args: - task_id (int): Integer task id - task (dict) : A task dict from dfk.tasks - r (Result future): Result future A warning is issued when a hash collision occurs during the update. This...
def update_memo(self, task_id, task, r): if not self.memoize or not task['memoize']: return if task['hashsum'] in self.memo_lookup_table: logger.info('Updating appCache entry with latest %s:%s call' % (task['func_name'], task_id)) sel...
261,065
Get the status of a list of jobs identified by the job identifiers returned from the submit request. Args: - job_ids (list) : A list of job identifiers Returns: - A list of status from ['PENDING', 'RUNNING', 'CANCELLED', 'COMPLETED', 'FAILED', 'TIMEOUT'...
def status(self, job_ids): if job_ids: self._status() return [self.resources[jid]['status'] for jid in job_ids]
261,088
Get the status of a list of jobs identified by their ids. Args: - job_ids (List of ids) : List of identifiers for the jobs Returns: - List of status codes.
def status(self, job_ids): logger.debug("Checking status of: {0}".format(job_ids)) for job_id in self.resources: if self.resources[job_id]['proc']: poll_code = self.resources[job_id]['proc'].poll() if self.resources[job_id]['status'] in ['COMPLETED...
261,090
Cancels the jobs specified by a list of job ids Args: job_ids : [<job_id> ...] Returns : [True/False...] : If the cancel operation fails the entire list will be False.
def cancel(self, job_ids): for job in job_ids: logger.debug("Terminating job/proc_id: {0}".format(job)) # Here we are assuming that for local, the job_ids are the process id's if self.resources[job]['proc']: proc = self.resources[job]['proc'] ...
261,092
Add a stream log handler. Args: - filename (string): Name of the file to write logs to - name (string): Logger name - level (logging.LEVEL): Set the logging level. - format_string (string): Set the format string Returns: - None
def start_file_logger(filename, rank, name='parsl', level=logging.DEBUG, format_string=None): try: os.makedirs(os.path.dirname(filename), 511, True) except Exception as e: print("Caught exception with trying to make log dirs: {}".format(e)) if format_string is None: format_str...
261,118
Reads the json contents from filepath and uses that to compose the engine launch command. Notes: Add this to the ipengine launch for debug logs : --log-to-file --debug Args: filepath (str): Path to the engine file engine_dir (str): CWD for the engines ....
def compose_containerized_launch_cmd(self, filepath, engine_dir, container_image): self.engine_file = os.path.expanduser(filepath) uid = str(uuid.uuid4()) engine_json = None try: with open(self.engine_file, 'r') as f: engine_json = f.read() e...
261,126
Scales out the number of active workers by 1. This method is notImplemented for threads and will raise the error if called. Parameters: blocks : int Number of blocks to be provisioned.
def scale_out(self, blocks=1): r = [] for i in range(blocks): if self.provider: block = self.provider.submit(self.launch_cmd, 1, self.workers_per_node) logger.debug("Launched block {}:{}".format(i, block)) if not block: ...
261,127