content
stringlengths
22
815k
id
int64
0
4.91M
def load_wxbmp(name="", mask=False, image=None, maskpos=(0, 0), f=None, retry=True, can_loaded_scaledimage=True, noscale=False, up_scr=None): """pos(0,0)にある色でマスクしたwxBitmapを返す。""" if sys.platform <> "win32": assert threading.currentThread() <> cw.cwpy if not f and (not cw.binary.i...
39,100
def test_legacy_price_query(): """Test legacy price query""" q = LegacyPriceQuery( name="BTC/USD Current Price", uid="qid-99", legacy_request_id=99, asset="btc", currency="usd", price_type="current", ) exp = ( b"qid-99?what is the current value of...
39,101
def web(name): """ Fabric command to launch a web server with ipython """ path = pj(EXPERIMENT_FOLDER, name) local("jupyter-notebook %(path)s/%(name)s.ipynb" % {"path": path, "name": name})
39,102
def get_xixj(nodes_disjoint, knn, k): """ Get the features of each edge in the graph. Paramters --------- nodes : tf.Tensor shape (None, n_features) knn : tf.Tensor shape (None, k) int32, for each point, the indices of the points that are the nearest neighbors. ...
39,103
def t_returns(inv, pfl, prices, date): """ Computes the total return of a portfolio. Parameters: - `inv` : :class:`list` investment session `db` row - `pfl` : :class:`string` name of the portfolio - `prices` : :class:`dict` latest investment's ticker prices - `date` ...
39,104
def center_crop_pad(img, buffer=0, min_mean=10): """dynamically center crop image, cropping away black space left and right""" g = np.array(img).mean(-1) h, w = g.shape zeros = g.mean(0) zero_inds = np.where(zeros < min_mean)[0] lo, hi = zero_inds[zero_inds < w // 2].max(), zero_inds[zero_inds >...
39,105
def main(): """ Docstring for main """ # ... wn = turtle.Screen() jimmy = turtle.Turtle() jimmy.color("black") # importing the Turtle and screen, applying attributes jimmy.pensize(22) jimmy.speed(15) draw_square(jimmy) # Function to draw the main square jimmy.pen...
39,106
def resolve_settings_file(): """Returns path to buildtest settings file that should be used. If there is a user defined buildtest settings ($HOME/.buildtest/config.yml) it will be honored, otherwise default settings from buildtest will be used. """ # if buildtest settings file exist return it other...
39,107
def main(argv): """Go Main Go""" mlra_id = int(argv[1]) pgconn = get_dbconn("idep") mlraxref = read_sql( """ with m as ( select mlra_id, mlra_name, sum(st_area(geography(geom))) from mlra WHERE mlra_id = %s GROUP by mlra_id, mlra_name), h as ( select mlra_id, sum...
39,108
def DiagPart(a): """ Diag op that returns only the diagonal elements. """ return np.diagonal(a),
39,109
def convert_one_log(filename, after='================'): """ only show the last log entry""" plt.figure(figsize=(7.0,10)) plt.clf() t = open(filename).read() s =t.rfind(after) if s<0: s=0 plt.figtext(0.02,0.98,t[s:],fontsize=8,va='top', fontname='monospace') plt.savefig(filename.replace(...
39,110
def test_config_without_project_fields_config(full_config) -> None: """ A config without Projects/Project/Fields node must raise an exception. """ del full_config["Projects"]["Project"]["Fields"] with pytest.raises(Exception): Config(full_config)
39,111
def prometh_hosts(): """ 从apollo查询prome地址 :return: list """ external = env_file_conf('EXTERNAL', conf_type='bool') if not external: conf_name = 'prome_host' else: conf_name = 'prome_external_host' if external: print('Conneting to apollo from extern...
39,112
def _ensure_webhook_access(func): """Decorate WS function to ensure user owns the webhook ID.""" @callback @wraps(func) def with_webhook_access(hass, connection, msg): # Validate that the webhook ID is registered to the user of the websocket connection config_entry = hass.data[DOMAIN][D...
39,113
def episode_to_examples(episode, histsz): """Converts an episode (list of Parleys) into self-feeding compatible examples WARNING: we no longer require a histz when making a self-feeding file. Shortening of the history is typically done in the teacher file or in interactive mode. """ examples = [] ...
39,114
def generator(samples, batch_size=32): """ Generate batches for train, validation and test dataset. """ num_samples = len(samples) while 1: # Loop forever so the generator never terminates random.shuffle(samples) for offset in range(0, num_samples, batch_size): batch_samp...
39,115
def camera_from_polyhedron(polyhedronFcn, camera_distance=1, to_spherical=False, device='cuda:0'): """ Returns the positions of a camera lying on the vertices of a given polyhedron Parameters ---------- polyhedronFcn : callable the polyhedron creation function camera_distance : float (o...
39,116
def cifar10(args, dataset_paths): """ Loads the CIFAR-10 dataset. Returns: train/valid/test set split dataloaders. """ transf = { 'train': transforms.Compose([ transforms.RandomHorizontalFlip(0.5), transforms.RandomCrop((args.crop_dim, args.crop_dim), padding=args.pad...
39,117
def cleanthread(thread, settings): """ Reset thread parameters in preparation for the next step of aimless shooting after the previous one has completed. Add the next step to the itinerary if appropriate. Also write to history and output files, implement fork if necessary, and terminate the thread if an...
39,118
def read_words(file="words.txt"): """ Reads a list of words from a file. There needs to be one word per line, for this to work properly. Args: file: the file to read from Returns: An array of all the words in the file """ with open(file, "r") as f: return f.read()....
39,119
def get_intersphinx_label(is_map, cur_project_dir): """ The top set of keys in the intersphinx map are shortname labels that intersphinx uses to identify different projects A sub-tuple in the dict (here invdata[1]) is a list of possible locations for the project's objects.inv file This utility checks a...
39,120
async def patch_user(user: User): """update a `user` in the list of users""" try: session = Session() selected_user = session.query( UserTable ).filter( UserTable.key == user.key ).first() selected_user.firstname = user.firstname selected_u...
39,121
def get_test_dataloader(mean, std, batch_size=16, num_workers=2, shuffle=True,task="cifar100",train=False): """ return training dataloader Args: mean: mean of cifar100 test dataset std: std of cifar100 test dataset path: path to cifar100 test python dataset batch_size: dataloader...
39,122
def test_nominal(p_file: str) -> None: """Test the application of the configuration with the parameters. The test file contains all the parameters and is in the correct format. The `multiple_sections.toml` file contains other sections that have nothing to do with the program but the parameters are the ...
39,123
def _init_cache(args: Optional[argparse.Namespace]) -> None: """Initialize the location for the cache.""" typ = QStandardPaths.CacheLocation path = _from_args(typ, args) if path is None: if utils.is_windows: # Local, not Roaming! data_path = _writable_location(QStandardPa...
39,124
def test_wps_ext_proto_m2_invalid_public_key(dev, apdev): """WPS and invalid Public Key in M2""" pin = "12345670" addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin) wps_ext_eap_identity_req(dev[0], hapd, bssid) wps_ext_eap_identity_resp(hapd, dev[0], addr) wps_ext_eap_wsc(dev[0], hapd, b...
39,125
def get(tags: Set[str]): """ get options marked by `tags` Options tagged by wildcard '*' are always returned """ # use specifically tagged options + those tagged with wildcard * return (o for tag in ('*',) + tuple(tags) for o in _options[tag])
39,126
def plot_fft(stream, channels=None, w_size=(1920, 1080)): """ plots fourrier transform of data stream from inlet. one row per channel. Args: stream (neurol.streams object): neurol stream for a data source. channels: channels to plot. list/tuple of channel indices, or dict with i...
39,127
def jitter_boxes(boxes, noise_scale=0.025): """Jitter the box coordinates by some noise distribution. Args: boxes: a tensor whose last dimension is 4 representing the coordinates of boxes in ymin, xmin, ymax, xmax order. noise_scale: a python float which specifies the magnitude of noise. The ru...
39,128
def arcs_kt_android_library(**kwargs): """Wrapper around kt_android_library for Arcs. Args: **kwargs: Set of args to forward to kt_android_library """ disable_lint_checks = kwargs.pop("disable_lint_checks", []) if not IS_BAZEL: kwargs["disable_lint_checks"] = merge_lists(disable_lint_...
39,129
def soil_props(soil_type, depth): """ Parameters c, Ks, n, Beta, s_h, s_w, s_bal, s_fc, bulk_d: Laio et al., 2001, Plants in water-controlled ecosystems: active role in hydrologic processes and response to water stress: II. Probabilistic soil moisture dynamic Parameters p1 through p5: Ezlit et al.,...
39,130
def DoMeshesBelongToSameMainMesh(list_mesh_identifiers: List[str]) -> bool: """checks whether all meshes given a list of mesh identifiers belong to the same main mesh Throws if an mesh identifier does not belong to a mesh """ main_mesh_identifiers = [] for mesh_identifier in list_mesh_identifiers: ...
39,131
def test_ps_push_http(): """ test pushing to http endpoint """ if skip_push_tests: return SkipTest("PubSub push tests don't run in teuthology") zones, ps_zones = init_env() bucket_name = gen_bucket_name() topic_name = bucket_name+TOPIC_SUFFIX # create random port for the http server ...
39,132
def returnPaths(jsonObj): """ takes a json dict with new/old and path, construct paths and return result :param jsonObj: json dict :return: tuple of paths (oldPath, newPath) """ assert isinstance(jsonObj, dict), "In object not a dict" paths = coll.namedtuple("paths", ["oldPath", "newPath"])...
39,133
def test_name() -> None: """Test illud.modes.replace.Replace.name.""" assert Replace.name == 'Replace'
39,134
def create_traces(numsamples, minlength, maxlength, benignp=0.9, benigndir='/zfs/home/yacin/work/oreilly/hands-on-adversarial-machine-learning/data/01-monotonic-classifiers/benign-traces', maldir='/zfs/home/yacin/work/oreilly/hands-on-adversarial-machine-learning/da...
39,135
def func1(): """docstring of func1""" pass
39,136
def active_roles(account, days_back): """ Returns query for finding active roles (since days_back value). """ query_string = f"""SELECT DISTINCT useridentity.sessioncontext.sessionissuer.arn FROM behold WHERE account = '{account}' AND useridentity.type = 'AssumedRole' AND from_is...
39,137
def sample_user(email='user@test.com', password='Test123'): """ Helper method to create a sample user for our test cases! :param email: Email address of the sample user :param password: A password for account creation. This can be a weak password as well since this is restricted to our testing e...
39,138
async def run_command(*args, **kwargs): """Shortcut for asyncronous running of a command""" fn = asyncio.subprocess.create_subprocess_exec if kwargs.pop("shell", False): fn = asyncio.subprocess.create_subprocess_shell check = kwargs.pop("check", False) process = await fn(*args, **kwargs) ...
39,139
def scaled_dot_product_attention(q, k, v, mask=None): """ #计算注意力权重。 q, k, v 必须具有匹配的前置维度。 且dq=dk k, v 必须有匹配的倒数第二个维度,例如:seq_len_k = seq_len_v。 #虽然 mask 根据其类型(填充或前瞻)有不同的形状, #但是 mask 必须能进行广播转换以便求和。 #参数: q: 请求的形状 == (..., seq_len_q, depth) k: 主键的形状 == (..., seq_len_k, depth) ...
39,140
def _get_parent_entity(entities, entity_id): """ Gets the parent entity from the collection, or throws ParentDoesNotExist. """ try: return entities[entity_id] except KeyError: raise ParentDoesNotExist(object_type='Entity', key=entity_id)
39,141
def make_plot_double(index, data1, data2, color1="#17BECF", color2="#BA1244", width=3, name1="chart1", name2="chart2"): """Makes a 2d scatter plot using index and two data sources.""" table1 = go.Scatter(x=index, y=data1, line=dict(color=color1, width=width), name=name1) table2 = g...
39,142
def tstop(f): """ Dust stopping time """ units = sutil.get_all_units(f) grainSize = f['u_dustGrainSize'] grainDensity = SimArray(sutil.get_snap_param(f, 'dDustGrainDensity'), units['rho_unit']) if sutil.is_isothermal(f): gamma = 1. else: gamma = sutil.get_snap_gamma(...
39,143
def solve_2d_discrete_observations_continuous_modelling( cond_xy0s_list: tp.List[tp.Tuple[float, float]], cond_xytGammas_list: tp.List[tp.Tuple[float, float, float]], cond_f0s_list: tp.List[float], cond_fGammas_list: tp.List[float], a: float, b: float, c: float, ...
39,144
def log_calls_on_exception( logger: logging.Logger, log_exception: bool = True ) -> GenericDecorator: """ Log calls to the decorated function, when exceptions are raised. Can also decorate classes to log calls to all its methods. :param logger: object to log to :param log_exception: True, ...
39,145
def _minimize_lbfgs( fun: Callable, x0: Array, maxiter: Optional[float] = None, norm=jnp.inf, maxcor: int = 10, ftol: float = 2.220446049250313e-09, gtol: float = 1e-05, maxfun: Optional[float] = None, maxgrad: Optional[float] = None, maxls: int = 20, ): """ Minimize a functi...
39,146
def shutdown_all_gpfs(): """Shuts down GPFS on ALL nodes""" #run('mmshutdown -a') return
39,147
def convert_2d_list_to_string(data): """Utility function.""" s = '' for row in data: c = '{' for e in row: c += str(e) + ',' s += c[:-1] + '},\n' return s[:-2]
39,148
def test_zu_mandelbaum15b(): """ """ halocat = FakeSim() model = PrebuiltHodModelFactory('zu_mandelbaum15', prim_haloprop_key='halo_mvir') model.populate_mock(halocat)
39,149
def _setup_argparser(): """Setup the command line arguments""" # Description parser = argparse.ArgumentParser( description="N-CREATE", usage="ncreate [options] peer port dcmfile-in") # Parameters req_opts = parser.add_argument_group('Parameters') req_opts.add_argument("peer", he...
39,150
def get_info(sheet, row_num, percentage, sheet_name, mandatory_tables): """ Function is used to create a dictionary that contains the number of flawed records for a particular site. :param sheet (dataframe): pandas dataframe to traverse. Represents a sheet with numbers indicati...
39,151
def get_structural_topology_reactions(filename, dset_path="readdy/config/structural_topology_reactions"): """ Construct a dictionary where the keys are reaction ids and value is corresponding name. :param filename: the file name :param dset_path: path to the dataset :return: dictionary of reactions...
39,152
def PyMapping_Keys(space, w_obj): """On success, return a list of the keys in object o. On failure, return NULL. This is equivalent to the Python expression o.keys().""" return space.call_function(space.w_list, space.call_method(w_obj, "keys"))
39,153
async def safebooru(ctx, tag, page='1'): """Searches safebooru. Usage: safebooru [tags]""" async with aiohttp.ClientSession() as session: invoker = ctx.message.author post = await fetch(session, "https://safebooru.org/index.php?page=dapi&s=post&q=index&limit=1&tags={}&pid={}&json=1".format(tag, ...
39,154
def is_arabicrange(text): """ Checks for an Arabic Unicode block characters @param text: input text @type text: unicode @return: True if all charaters are in Arabic block @rtype: Boolean """ if re.search(u"([^\u0600-\u06ff\ufb50-\ufdff\ufe70-\ufeff\u0750-\u077f])", text): return Fal...
39,155
def del_pool(batch_client, config, pool_id=None): # type: (azure.batch.batch_service_client.BatchServiceClient, dict, # str) -> bool """Delete a pool :param batch_client: The batch client to use. :type batch_client: `azure.batch.batch_service_client.BatchServiceClient` :param dict config:...
39,156
def _time_to_timestamp(timestamp, time_seconds): """Convert result of time.time() to Timestamp.""" timestamp.seconds = int(time_seconds) timestamp.nanos = int((time_seconds - timestamp.seconds) * 10**9)
39,157
def str_repeat(space, s, repeat): """Repeat a string.""" return space.newstr(s * repeat)
39,158
def alarm(duration=250): """ Red alarm; flashing bright red to dark red. :param int duration: The duration between hi/lo brightness,in milliseconds. :returns: An infinite Flow consisting of 2 transitions. :rtype: Flow """ return Flow(count=0, action=Action.recover, transitions=transitions....
39,159
def mkvc(x, numDims=1): """Creates a vector with the number of dimension specified e.g.:: a = np.array([1, 2, 3]) mkvc(a, 1).shape > (3, ) mkvc(a, 2).shape > (3, 1) mkvc(a, 3).shape > (3, 1, 1) """ if type(x) == np.matrix: ...
39,160
def _block_while_terminating(instance, conn): """ """ eprint(' terminating instance:', instance) assert get_instance_by_id(instance.id, conn) is not None conn.terminate_instances([instance.id]) time.sleep(2) while get_instance_by_id(instance.id, conn): eprint(' polling for terminate co...
39,161
def change(imagepath): """ Changes the desktop wallpaper ``imagepath``: an absolute path to the image """ if sys.platform in ["win32", "cygwin"]: windows.setwallpaper(imagepath) else: linux.setwallpaper(imagepath)
39,162
def location_distance_meters(a: Location, b: Location) -> float: """Calculates the distance between two points. Returns: A number of meters between two points. """ return location_distance_kilometers(a, b).m
39,163
def file_to_dict(file: str): """Dump json file to dictionary""" try: with open(file) as json_file: return json.load(json_file) except json.decoder.JSONDecodeError: print(f'File {file} is not a valid json file. Returning empty dict') return {} except FileNotFoundError:...
39,164
def fieldtype(field): """Return classname""" return field.__class__.__name__
39,165
def dataset_to_hdf(ds: xr.Dataset, filename: str, key: str, mode: str = 'a', compress: bool = False, format: str = None, save_attrs: bool = True): """Store an xarray Dataset in an HDF5 file using PyTabl...
39,166
def basic_extractor( data: Dict, ) -> list: """ Returns list of the total_recieved token, the total sent token and the number of transactions the wallet participated in. """ return [data["total_received"],data["total_sent"],data["n_tx"]]
39,167
def expand_stages_cfg(stage_cfgs): """ For a list of stages """ assert isinstance(stage_cfgs, list) ret = [] for x in stage_cfgs: ret.append(expand_stage_cfg(x)) return ret
39,168
def find_team(): """find a team by using filters from request arguments""" # partial -> allow skipping of required fields ts = TeamSchema( partial=True, only=( "name", "event_id", "team_identifier", "payment_status", "single", ...
39,169
def clusterbased_permutation_1d_1samp_1sided(results, level=0, p_threshold=0.05, clusterp_threshold=0.05, n_threshold=2, iter=1000): """ 1-sample & 1-sided cluster based permutation test for 2-D results Parameters ---------- results : array A re...
39,170
def getObjectsContainers(mQueryObject = []): """ Return a list of containers that the passed in objects reside in. @param [] mQueryObject: list of objects you are wanting to know, in which container they exists. @return: key = container name, value = container MObject. @rtype: {} """ contai...
39,171
def make(parser): """ Start deploying a new cluster, and write a CLUSTER.conf and keyring for it. """ parser.add_argument( 'mon', metavar='MON', nargs='+', help='initial monitor hostname, fqdn, or hostname:fqdn pair', type=arg_validators.Hostname(), ) ...
39,172
def test_recordip(create_app, open_record, singleip_record): """Test Generator RecordIp.""" generator = RecordIp() open_record = open_record singleiprec = singleip_record assert generator.needs(record=None) == [] assert generator.needs(record=open_record) == [any_user] assert generator.need...
39,173
def dump_dot(graph: Graph, name: Optional[str] = None) -> str: # pragma: no cover """ Dumps graph into dot language for visualization. Args: graph: Target graph name: Returns: source code of dot language. """ dot_source = "" dot_source += "digraph webdnn_ir {\n" ...
39,174
def depthmap2pointclouds_perspective(depth_map, rgb_image, cam_int_param, output_path, rgb_image_path=None): """Convert the depth map to 3D mesh and export to file. The input numpy array is [height, width, x]. :param depth_map: depth map :type depth_map: numpy :param rgb_image: rgb image data ...
39,175
def RPL_LUSERCLIENT(sender, receipient, message): """ Reply Code 251 """ return "<" + sender + ">: " + message
39,176
def multiply_inv_gaussians_batch(mus, lambdas): """Multiplies a series of Gaussians that is given as a list of mean vectors and a list of precision matrices. mus: list of mean with shape [..., d] lambdas: list of precision matrices with shape [..., d, d] Returns the mean vector, covariance matrix, and p...
39,177
def replace_if_present_else_append( objlist, obj, cmp=lambda a, b: a == b, rename=None): """ Add an object to a list of objects, if that obj does not already exist. If it does exist (`cmp(A, B) == True`), then replace the property in the property_list. The names are c...
39,178
def rating_value(value): """Check that given value is integer and between 1 and 5.""" if 1 <= int(value) <= 5: return int(value) raise ValueError("Expected rating between 1 and 5, but got %s" % value)
39,179
def test_awg5014_context_view(exopy_qtbot): """Test displaying the context view. """ root = RootSequence() context = AWG5014Context(sequence_name='Test') root.context = context show_and_close_widget(exopy_qtbot, AWG5014ContextView(context=context, sequence=root))
39,180
def hsc_to_hs(ctx): """Process all hsc files into Haskell source files. Args: ctx: Rule context. Returns: list of File: New Haskell source files to use. """ ghc_defs_dump = _make_ghc_defs_dump(ctx) sources = [] for f in ctx.files.srcs: if f.extension == "hsc": sources.append(_process_h...
39,181
def calculate_iou_box(pts1, pts2): """ Measure the two list of points IoU :param pts1: ann.geo coordinates :param pts2: ann.geo coordinates :return: `float` how Intersection over Union of tho shapes """ try: from shapely.geometry import Polygon except (ImportError, ModuleNotFound...
39,182
def nextafter(x, direction, dtype, itemsize): """Return the next representable neighbor of x in the appropriate direction.""" assert direction in [-1, 0, +1] assert dtype.kind == "S" or type(x) in (bool, float, int) if direction == 0: return x if dtype.kind == "S": return stri...
39,183
def test_expected_tops_bases(): """Test the computation of tops/bases from `depth_range`s and `col_height`s.""" depth_range, col_height = [1.0, 2.5], 1.0 tops, bases = CoreSegmenter.expected_tops_bases(depth_range, col_height) assert tops == [1.0, 2.0] and bases == [2.0, 3.0], "Simple case." depth...
39,184
def integrated_circular_gaussian(X=None, Y=None, sigma=0.8): """Create a circular Gaussian that is integrated over pixels This is typically used for the model PSF, working well with the default parameters. Parameters ---------- X, Y: `numpy.ndarray` The x,y-coordinates to evaluate the ...
39,185
def nPairsToFracPairs(hd_obj, all_pairs_vs_rp, redshift_limit = 2): """ Function to convert the number of pairs into a fractional number density per shell @redshift_limit :: the initial redshift limit set on the sample (needed for opening dir) """ num_pairs = all_pairs_vs_rp[1:] - all_pairs_vs_rp[:-...
39,186
def test_list_nodes(): """Test listing the nodes existing in the database. """ database = TaskDatabase() database.set_value('root', 'val1', 1) database.create_node('root', 'node1') database.set_value('root/node1', 'val2', 'a') database.create_node('root', 'node2') database.set_value('ro...
39,187
def is_valid_image(arg): """ Verifies that a given argument is a valid image files arg: string representing filepath Returns ------- img : A W*H*3 array representing a color image """ if not os.path.isfile(arg): raise argparse.ArgumentTypeError(f"{arg} does not exi...
39,188
def default_decode(events, mode='full'): """Decode a XigtCorpus element.""" event, elem = next(events) root = elem # store root for later instantiation while (event, elem.tag) not in [('start', 'igt'), ('end', 'xigt-corpus')]: event, elem = next(events) igts = None if event == 'start' a...
39,189
def attention_guide(dec_lens, enc_lens, N, T, g, dtype=None): """Build that W matrix. shape(B, T_dec, T_enc) W[i, n, t] = 1 - exp(-(n/dec_lens[i] - t/enc_lens[i])**2 / (2g**2)) See also: Tachibana, Hideyuki, Katsuya Uenoyama, and Shunsuke Aihara. 2017. “Efficiently Trainable Text-to-Speech System Base...
39,190
def flex_load(file_path: Union[str, os.PathLike, PurePath], default_serializer=None, default_is_gzipped=False) -> Union[dict, list]: """ Determines which serializer is needed to open the file and whether it's compressed by looking at the file extension. Supports `.pickle`, `.yaml...
39,191
def two_step_colormap(left_max, left, center='transparent', right=None, right_max=None, name='two-step'): """Colormap using lightness to extend range Parameters ---------- left_max : matplotlib color Left end of the colormap. left : matplotlib color Left middle of the colormap. ...
39,192
def _broadcast_arg(U, arg, argtype, name): """Broadcasts plotting option `arg` to all factors. Args: U : KTensor arg : argument provided by the user argtype : expected type for arg name : name of the variable, used for error handling Returns: iterable version of arg...
39,193
def _exec_command(command, use_shell=None, use_tee = None, **env): """ Internal workhorse for exec_command(). """ if use_shell is None: use_shell = os.name=='posix' if use_tee is None: use_tee = os.name=='posix' if os.name == 'posix' and use_shell: # On POSIX, subprocess...
39,194
def check_args_errors(): """Check command-line arguments.""" # checks for updating and/or starting if not args.update and not args.start: logging.info("--update/--start not specified, doing both.") args.start = True args.update = True # make sure only one game is chosen if a...
39,195
async def username(client, message, **kwargs): """Set your Challonge username Required Argument: username -- If you don't have one, you can sign up here for free https://challonge.com/users/new """ db.set_username(message.author, kwargs.get('username')) await client.send_message(message.channel,...
39,196
def xkcd_line(x, y, xlim=None, ylim=None, mag=1.0, f1=30, f2=0.05, f3=15): """ Mimic a hand-drawn line from (x, y) data Definition ---------- def xkcd_line(x, y, xlim=None, ylim=None, mag=1.0, f1=30, f2=0.05, f3=15): Input ----- x, y array_like; a...
39,197
def generate_mutation() -> str: """ Retrieve staged instances and generate the mutation query """ staged = Node._get_staged() # localns = {x.__name__: x for x in Node._nodes} # localns.update({"List": List, "Union": Union, "Tuple": Tuple}) # annotations = get_type_hints(Node, globalns...
39,198
def start(fund: Fund, start_date: datetime) -> Fund: """ Starts the fund by setting the added USD and the market value of the manager as the current market value. Meaning that at the beginning there is only the manager's positions. :param fund: The fund to start :param start_date: The date to ca...
39,199