content
stringlengths
22
815k
id
int64
0
4.91M
def learn_a_new_dfa(runner, u, v, predicate): """Given two buffers ``u`` and ``v```, learn a DFA that will allow the shrinker to normalise them better. ``u`` and ``v`` should not currently shrink to the same test case when calling this function.""" from hypothesis.internal.conjecture.shrinker import...
5,317,000
def generate_corrected_profiles (corr_factor, fwd_border_dicts, fwd_profile, plasmid_length, scale): """ Correct the edges of the transcription profiles """ # New profile to hold the normalised data Normalized_fwd_profile = np.ones(plasmid_length)*scale # Cycle through each transcript (no idea why this is a dict) ...
5,317,001
def base_handler(event: Event, loader_cls: type) -> Response: """Handler which is called when accessing the endpoint.""" response: Response = {"statusCode": 200, "body": json.dumps("")} db_helper = DatabaseHelper() try: point = ( Point(event["close_to_lon"], event["close_to_lat"]) ...
5,317,002
def publish_image_dir(): """ checks if publishing of images configured and if so it returns the directory to publish to (full path) or None """ root_dir = publish_root_dir() if root_dir != None: rel_dir = get_value_with_default(['publish', 'package_dir'], 'images') return os....
5,317,003
def transforToManagerProxyObject(manager, data): """将不转换dict中的key 只支持基础数据,dict,list和tuple tuple将会转换成list result = data """ if isinstance(data, dict): result = manager.dict() for key in data: result[key] = transforToManagerProxyObject(manager, data[key]) elif isinstance(data, list) or isinstance(data, tupl...
5,317,004
def get_topo_ip(): """ 获取数据表tj_public_topo中 新增ip @params: 无 @return: [ "1.1.1.1", ... ] """ db = MySqLHelper() sql = """ SELECT ip, d_time FROM t_public_topo ...
5,317,005
def test_is_request_using_sso_false_with_session(): """ Testing the usual case for non-sso requests. """ request = RequestFactory().get('/sso/test') generator.create_request_session(request) eq(is_request_using_sso(request), False)
5,317,006
def compare(code_in, code_out=None): """Compare code before and after an ast/deast conversion.""" if code_out is None: code_out = code_in tree = ast.parse(code_in) deaster = deast.DeAST() deaster.visit(tree) assert deaster.source == code_out
5,317,007
def Install(vm) -> None: """Installs the omb package with specified MPI lib on the VM.""" vm.AuthenticateVm() if FLAGS.mpi_vendor == 'intel': _InstallForIntelMpi(vm) else: _InstallForOpenMpi(vm)
5,317,008
def get_new_account_id(event): """Return account id for new account events.""" create_account_status_id = ( event["detail"] .get("responseElements", {}) .get("createAccountStatus", {})["id"] # fmt: no ) LOG.info("createAccountStatus = %s", create_account_status_id) org = bo...
5,317,009
def bypass_package_install_fixture(): """Bypass package installation.""" with patch("custom_components.pyscript.requirements.async_process_requirements"): yield
5,317,010
def list_opts(): """Returns a list of oslo_config options available in the library. The returned list includes all oslo_config options which may be registered at runtime by the library. Each element of the list is a tuple. The first element is the name of the group under which the list of elements ...
5,317,011
def tokenize_for_t5_advice_training(encoder, subreddit=None, date=None, title=None, selftext=None, body=None): """ Tokenizes the post title / post selftext / comment body. If it's too long we'll cut some paragraphs at random from the selftext. :param subreddit: 'rela...
5,317,012
def hvdisp_plot_records_2d(records, to_pe, config, t_reference, time_stream=None, tools=(x_zoom_wheel(), 'xpan'), default_tools=('save', 'pan', 'box_zoom', 's...
5,317,013
def test_readme_simple(capsys): """The exact scenario showed in the readme""" df = df_mix1() # detect strict deterministic relationships qd_forest = qd_screen(df) print(qd_forest) captured = capsys.readouterr() with capsys.disabled(): # note the u for unicode string in py2, see tes...
5,317,014
def join_url(url, *paths): """ :param url: api url :param paths: endpoint :return: full url """ for path in paths: url = re.sub(r"/?$", re.sub(r"^/?", "/", path), url) return url
5,317,015
def _get_minimum_columns( nrows, col_limits, families, family_counts, random_state ): """If ``col_limits`` has a tuple lower limit then sample columns of the corresponding element of ``families`` as needed to satisfy this bound.""" columns, metadata = [], [] for family, min_limit in zip(families, c...
5,317,016
def sales_order(): """ Seed database with sample sales order transactions """ currPeriod = periodCtr.getCurrent() if currPeriod is None: click.secho("Period must be set first!", fg="red") exit() if so.newSale(item_count=1, created_at=datetime.datetime.now()): click.echo("Seeder executed successfully.") el...
5,317,017
def ensure_callable(x: Union[Any, Function]) -> Function: """ensure a given args is a callable by returning a new callable if not""" if not callable(x): def wrapped(*args: Any, **kwargs: Any) -> Any: return x return cast(Function, wrapped) return cast(Function, x)
5,317,018
def concat_dataframes(dataframes: List[pd.DataFrame], remove_duplicates: bool = True, keep: str = 'first' ) -> pd.DataFrame: """ Concatenate list of dataframes with optional removal of duplicate keys. Args: dataframes (list):...
5,317,019
def __split_pair(number: SnailfishNumber, left: bool) -> int | None: """Splits a number into a pair if the number is >= 10. :param number: Number node from the binary tree. :param left: Boolean if we are inspecting the right or left leaf. :return: 1 if we split else None. """ # Search for the l...
5,317,020
def set_config_value(filePath, section, key, value, alwaysInsert=False): """ This method replaces an exiting key with the value or adds a new one. Also adds the section if it cannot be found. Args: filePath (str) : The path to the file. section (str) : The desired section name. ...
5,317,021
def def_pin_pout(m): # This could be better implemented. # In particular, it should not use m.p directly but m.find_component(name_var) """ Defines power 'in' and 'out' variables :param m: :return: """ assert isinstance(m, Block), f"argument 'm', must be an instance of Block, but i...
5,317,022
def get_user_choice() -> tuple[str, str]: """Returns the headers for the x and y value choices as a tuple.""" while True: # X console_display_choices(X_OPTIONS, "X") x_choice = get_x_y_value(X_OPTIONS, "X") # Y console_display_choices(Y_OPTIONS, "Y") y_choice ...
5,317,023
def exp(args, model_type, vertex_label, b_true, X_train, X_test_ID, X_test_OOD): """Experiment function.""" torch.set_default_dtype(torch.double) np.set_printoptions(precision=3) model, w_est = train( X_train, vertex_label=vertex_label, b_true=b_true, model_type=model_type, args=...
5,317,024
def sliding_window(warped): """ Using sliding window to find the lane line segments. This method will be used at the start of a video or when there is no lane line found on the previous video frame. """ img_height, img_width = warped.shape[0], warped.shape[1] histogram = np.sum(warped[img_heig...
5,317,025
def test_delete_wait_success( fake_cloudformation_client: StubbedClient, stack: cloudformation.Stack ): """Tests Stack.delete(wait=True) successful cases""" stub_describe_stack(fake_cloudformation_client.stub, "MyStack", "UPDATE_COMPLETE") stub_delete_stack(fake_cloudformation_client.stub, "MyStack") ...
5,317,026
def get_config(n_layers, use_auto_acts, fp_quant): """Returns a ConfigDict instance for a WMT transformer. The ConfigDict is wired up so that changing a field at one level of the hierarchy changes the value of that field everywhere downstream in the hierarchy. For example, changing the top-level...
5,317,027
def get_train_loader(transform=None): """ Args: transform (transform): Albumentations transform Returns: trainloader: DataLoader Object """ if transform: trainset = Cifar10SearchDataset(transform=transform) else: trainset = Cifar10SearchDataset(root="~/data/cifar10", train=True, ...
5,317,028
def train_regression(train_data, model, criterion, optimizer, batch_size, device, scheduler=None, collate_fn=None): """Train a Pytorch regresssion model Parameters ---------- train_data : torch.utils.data.Dataset Pytorch dataset model: torch.nn.Module Pytorch Model criterion: fu...
5,317,029
def get_url_content(url): """Performs a HTTP GET on the url. Returns False if the url is invalid or not-found""" res = None if not re.search(r'^http', url): url = 'http://' + url try: req = urllib.request.urlopen(url, None, 30) res = req.read().decode(locale.getlocale()[1]) ...
5,317,030
def _evaluate(cmd, dork): """Parse a command and execute it""" cmd = cmd.strip().split(" ", 1) if cmd[0]: verb, *noun = cmd noun = noun[0] if noun else None call = _CMDS.get(verb, _MOVES.get(verb, _META.get(verb, _ERRS["u"]))) if isinstance(call, dict): method, ...
5,317,031
def test_fm_07_parent_dir_correct_path(): """ Test the parent directory is being returned """ test_path = 'PYTEST_TMPDIR/test_directory/testfile.txt' assert fm.get_parent_dir(test_path) == 'PYTEST_TMPDIR'
5,317,032
def build_input_dict(feature_columns): """ 基于特征列(feature columns)构建输入字典 :param feature_columns: list 特征列 :return: input_dict: dict 输入字典,形如{feature_name: keras.Input()} """ # 1,基于特征列构建输入字典 input_dict = OrderedDict() for fc in feature_columns: if isinstance(fc, DenseFeat):...
5,317,033
def factorial(n): """Calcula el factorial de un numero""" fact = 1 for i in range (1, n+1): fact = fact * i return fact
5,317,034
def sigmoid(x): """ Computes sigmoid of x element-wise. Parameters ---------- x : tensor A Tensor with type float16, float32, float64, complex64, or complex128. Returns ------- A Tensor with the same type as x. """ outputs = P.Sigmoid() return outputs(x)
5,317,035
def conf_serializer(configuration: Configuration) -> str: """Serialize configuration to .conf files.""" lines = [f"{key} {val}" for key, val in configuration.Properties.items()] return "\n".join(lines) + "\n"
5,317,036
def test_init(): """ markup.encoder.text.TextEncoder() inits properly """ inst = _encoder.TextEncoder('foo') assert isinstance(inst, _abstract.Encoder) assert inst.encoding == 'foo'
5,317,037
def send_notifications(handler, persons, notes): """For each note, send a notification to subscriber. Args: notes: List of notes for which to send notification. persons: Dictionary of persons impacted by the notes, indexed by person_record_id. handler: Handler used to send ...
5,317,038
def redness_greenness_response(C, e_s, N_c, N_cb): """ Returns the redness / greenness response :math:`M_{yb}`. Parameters ---------- C : array_like Colour difference signals :math:`C`. e_s : numeric or array_like Eccentricity factor :math:`e_s`. N_c : numeric or array_like ...
5,317,039
def validate_file(file_type, path): """Ensure the data file contains parseable rows data""" match = re.search(r'\.(\w+)$', str(path)) extension = None if match: extension = match.group(1).lower() else: return 'invalid file extension' if extension not in _FILE_TYPE_EXTENSIONS[file...
5,317,040
def send_email(mail_server, port, src, dest, sub, tls): """ Simple email notification Arguments -------- mail_server: str email server hostname/ip port: int port to use src: str email from address dest: str email to address tls: boolean use en...
5,317,041
def upload(bucket_name, key, file_path): """ upload object to bucket """ # create s3 client client = boto3.client("s3") # guess ContentType mime, _ = mimetypes.guess_type(file_path, strict=False) mime = "text/plain" if mime is None else mime with open(file_path, "rb") as file: resp...
5,317,042
def _format_source(src, virtual_cells = None): # type: (Union[str, RuleTarget], str) -> str """ Converts a 'source' to a string that can be used by buck native rules Args: src: Either a string (for a source file), or a RuleTarget that needs converted to a label platform: The platform to us...
5,317,043
def test_vnic_and_assign_vf(ip_addr, free_vnics_ips, backlisted_vfs=()): """ Based on the IP address of an OCI VNIC, ensure that the VNIC is not already assigned to a virtual machine. If that VNIC is available, find a free virtual function on the appropriate physical interface and return the necessa...
5,317,044
def read_config_file_step( info=None, config_file_path=path.join(path.dirname(path.dirname(__file__)), 'config', 'config.yml')): """ 读取配置文件 :param info: :param config_file_path: 配置文件路径 :return: """ if info: res = FileOperate.read_yaml(config_file_path)[info] else:...
5,317,045
def get_player(): """Returns a driver to control the VoiceHat speaker. The aiy modules automatically use this player. So usually you do not need to use this. Instead, use 'aiy.audio.play_wave' if you would like to play some audio. """ global _voicehat_player if not _voicehat_player: ...
5,317,046
def post_user_events(): """Endpoint for users to post the events they want to add to their calendar Returns: Response: JSON with the success status of each event """ body = request.json response = insert_user_calendar_events( session['google-idap']['access_token'], calendar...
5,317,047
def zmq_version(): """return the version of libzmq as a string""" return "%i.%i.%i" % zmq_version_info()
5,317,048
def parse_datetime_interval(period_from: str, period_to: str, strformat: str = None) -> date_tuple: """ Returns given period parameters in datetime format, or next step in back-fill mode along with generated last state for next iteration. Args: period_from: YYYY-MM-DD or relative string support...
5,317,049
def _paths_from_ls(recs): """The xenstore-ls command returns a listing that isn't terribly useful. This method cleans that up into a dict with each path as the key, and the associated string as the value. """ ret = {} last_nm = "" level = 0 path = [] ret = [] for ln in recs.split...
5,317,050
def determine_instcat_work(instcat_list, outfile): """Determine how many sensors each visit will take and the number of objects to simulate. Then output a single json file containing a list of all the work to be done. Args: instcat_list (list): a list of paths to all instance catalog...
5,317,051
def train(args, train_dataset, eval_dataset, model, tokenizer): """ Train the model """ # ===== Setting up # summary writer tb_writer = SummaryWriter() print("DEBUGGING!") print("train_dataset: " + str(len(train_dataset))) print(train_dataset[0]) print("train_batch_size: " + str(ar...
5,317,052
def TRS_between_rounds(X1, X2): """ Calculate the TRS rotor between any pair of rounds of the same grade Bring rounds to origin, line up carriers, calculate scale """ T1 = generate_translation_rotor(-down((X1 * einf * X1)(1))) X1h = (T1 * X1 * ~T1).normal() T2 = generate_translation_rotor(-d...
5,317,053
def col_range_nb(col_arr, n_cols): """Build column range for sorted column array. Creates a 2-dim array with first column being start indices (inclusive) and second column being end indices (exclusive). !!! note Requires `col_arr` to be in ascending order. This can be done by sorting.""" c...
5,317,054
def deploy(*components_with_tokens): """Deploy a component on a host. This is executed on each host to deploy. Rollingpin will pass a list of components with their build tokens as generated by the `build` command. This command is required if you want to run "-d" commands in rollingpin. """ ...
5,317,055
def filterfiles(files, criteria): """Rerturns only the files from filelist that match the criteria. The criteria should be a list of (unit,keyword,function) where the function returns true for desired values of the keyword. For example criteria = ((0,'OPT_ELEM', lambda x: x == 'G130M'), ...
5,317,056
def module_start(ip, port, dev, module): """模块启动 Args: ip(str):ip地址 port(int):端口号 dev(str): 设备名称 module(str):模块名称 Returns: tuple:返回错误码以及对应信息 """ command = "模块启动" AP.__class__.logout("发送{}{}{}指令".format(dev, module, command)) MESSAGE_DICT["mod_start_...
5,317,057
def activate_bgp_neighbor(dut, local_asn, neighbor_ip, family="ipv4", config='yes',vrf='default', **kwargs): """ :param dut: :param local_asn: :param neighbor_ip: :param family: :param config: :param vrf: :return: """ st.log("Activate BGP neigbor") cli_type = get_cfg_cli_ty...
5,317,058
def print_experiment_record_argtable(records): """ Print a table comparing experiment arguments and their results. """ funtion_names = [record.info.get_field(ExpInfoFields.FUNCTION) for record in records] args = [record.get_args() for record in records] common_args, different_args = separate_com...
5,317,059
def test_score_values(x,y,l,r): """ score increases monotonically, score is smaller than board """ g = game.Game(x,y,colors=l) p = g.turn c = next(iter(g.colors_available(p))) old_score = g.players[p].score g.command(p,c) new_score = g.players[p].score assert old_score > 0 assert old_score <= new_score
5,317,060
def key_validator(*args, **kwargs): """Wraps hex_validator generator, to keep makemigrations happy.""" return hex_validator()(*args, **kwargs)
5,317,061
def fuzzy_search(request): """ ajax interface for fuzzy string search :param request: request of the web server :return: json-set with all matched strings """ LOG.debug("Fuzzy String search for AJAX: %s", request.json_body) mode = request.validated['type'] value = request.validated['va...
5,317,062
def create_app(): """ Initialize the core application """ app = Flask(__name__, instance_relative_config=False) app.config.from_object(Config) # Initialize Plugins db.init_app(app) login_manager.init_app(app) with app.app_context(): from . import routes from . import auth ...
5,317,063
def plot_points_3D_mayavi( points: np.ndarray, bird: bool, fig: Figure, per_pt_color_strengths: np.ndarray = None, fixed_color: Optional[Color] = (1, 0, 0), colormap: str = "spectral", ) -> Figure: """Visualize points with Mayavi. Scale factor has no influence on point size rendering whe...
5,317,064
def _unregister(plugin_identity, type_identity): """ Unregisters a plug-in as a specific plug-in type. This unregisters the plug-in here in the plug-ins module, and then calls the unregister function of the plug-in type plug-in in case that plug-in wants to do additional work when unregistering a new plug-in. :p...
5,317,065
def generate(quail_conf_path, name, token, url, init=False): """ Generates a redcap project from which to pull data """ print('Generating new redcap project') config = QuailConfig(quail_conf_path) quail_root = config.get_root() project_path = file_util.join([quail_root, 'sources', name]) ...
5,317,066
def read_binary_integer32_token(file_desc: io.BufferedReader) -> int: """ Get next int32 value from file The carriage moves forward to 5 position. :param file_desc: file descriptor :return: next uint32 value in file """ buffer_size = file_desc.read(1) return get_uint32(file_desc.read(buf...
5,317,067
def pop(key): """ 从缓存队列的后尾读取一条数据 :param key: 缓存key,字符串,不区分大小写 :return: 缓存数据 """ # 将key转换为小写字母 key = str(key).lower() try: value = r.rpop(key) except Exception as e: log_helper.info('读取缓存队列失败:key(' + key + ')' + str(e.args)) value = None return _str_to_jso...
5,317,068
def getUSGSnwis(stationids,starttime,endtime,ncfile): """ Main function for grabbing the data and saving it to a netcdf file """ meta={} meta.update({'Station ID':[]}) meta.update({'StationName':[]}) meta.update({'Latitude':[]}) meta.update({'Longitude':[]}) time=[] ...
5,317,069
def _one_q_pauli_prep(label, index, qubit): """Prepare the index-th eigenstate of the pauli operator given by label.""" if index not in [0, 1]: raise ValueError(f'Bad Pauli index: {index}') if label == 'X': if index == 0: return Program(_RY(pi / 2, qubit)) else: ...
5,317,070
def register_resource(category, resource_type, comm_callback): """ 注册配置接口实例化的方法或者类。 """ if category == "device": _resource_device_mapping[resource_type] = comm_callback elif category == "port": _resource_port_mapping[resource_type] = comm_callback
5,317,071
def merge( left: dask.dataframe.core.DataFrame, right: dask.dataframe.core.DataFrame, how: Literal["left"], on: None, left_index: bool, right_index: bool, ): """ usage.dask: 1 """ ...
5,317,072
def run(camera: Camera): """ Runs the PictogramDetector. :return: the pictogram which had the most hits. """ try: detector = PictogramDetector(camera) stats = detector.detect() logging.debug(stats) result = max(stats, key=stats.get) t2s = pyttsx3.init() ...
5,317,073
def concat_claims_all_documents(index: list, file_name: str): """ Merges all the lists of unique tags and saves the merged version as one pickle file with all unique tags """ list_of_dfs = [] for i in index: location = '{0}{1}_wclaims.pkl'.format(file_name.split('.')[0][:-len(i)], i) ...
5,317,074
def test_execid_parsing_sharr(mocker): """ Verifies correct operation for successful remediation """ automation_exec_info = { "AutomationExecutionId": "795cf453-c41a-48df-aace-fd68fdace188", "DocumentName": "SHARR_Remediation_AFSBP_1.0.0_EC2.7", "DocumentVersion": "1", "A...
5,317,075
def get_movie_data_from_wikidata(slice_movie_set: pd.DataFrame): """ Function that consults the wikidata KG for a slice of the movies set :param slice_movie_set: slice of the movie data set with movie id as index and imdbId, Title, year and imdbUrl as columns :return: JSON with the results of the qu...
5,317,076
def upload_site_survey( client: SymphonyClient, location: Location, name: str, completion_date: datetime, excel_file_path: str, json_file_path: str, ) -> None: """Upload the site survey to the given completion with the data in the given excel file. We use the schema file to validate ...
5,317,077
def test_rescan(node_factory, bitcoind): """Test the rescan option """ l1 = node_factory.get_node() # The first start should start at current_height - 30 = 71, make sure # it's not earlier l1.daemon.wait_for_log(r'Adding block 101') assert not l1.daemon.is_in_log(r'Adding block 70') # ...
5,317,078
def run_dpc( filename, i, j, ref_fx=None, ref_fy=None, start_point=[1, 0], pixel_size=55, focus_to_det=1.46, dx=0.1, dy=0.1, energy=19.5, zip_file=None, roi=None, bad_pixels=[], max_iters=1000, solver="Nelder-Mead", hang=True, reverse_x=1, reve...
5,317,079
def make_build_dir ( build = None ) : """Create proper temporary directory for ROOT builds """ if not build or not writeable ( build ) : from ostap.utils.cleanup import CleanUp build = CleanUp.tempdir ( prefix = 'ostap-build-' ) if not os.path.exists ( build ) : make_dir ( b...
5,317,080
def api_converter(): """ Handler for conversion API request :return: Text of response :rtype: str """ try: parsed_args = parse_request_arguments() conversion_result = convert_core.convert_currency(**parsed_args) except (APIRequestError, CurrencyConversionError) as exc_msg: ...
5,317,081
def handle_flit(data): """ Handle pyproject.toml unserialized into data, using flit build system. """ topdata = data['tool']['flit'] metadata = topdata['metadata'] modname = metadata['module'] sys.path.insert(0, '.') mod = importlib.import_module(modname, '') entry_points = def...
5,317,082
def plot1(ctx): """Do main plotting logic""" df = read_sql(""" SELECT * from sm_hourly WHERE station = %s and valid BETWEEN %s and %s ORDER by valid ASC """, ctx['pgconn'], params=(ctx['station'], ctx['sts'], ctx['ets']), index_col='valid') if df.empty: ...
5,317,083
def test(args): """ 预测 :return: """ data_path = os.path.join(DATA_DIR, args.data_path) data = load_data(data_path) print('=========') # print(data) print(data.get_vocab(Const.INPUT)) data.datasets['test'].set_target('target', 'seq_len', 'sentence_num') data.datasets['test'].s...
5,317,084
def is_royal_flush(hand: Tuple[Card]) -> Optional[Tuple[str, PokerHand, int]]: """ If this hand contains a royal flush, return string representation of it """ straight_flush = is_straight_flush(hand) if straight_flush is not None and "Ten to Ace" in straight_flush[0]: # All royal straights are equal...
5,317,085
def apply_aws_firewall_resources(client, firewall_configs): """Creates/updates AWS Firewall policies and firewalls""" for policy, policy_config in firewall_configs["policies"].items(): policy_response = apply_firewall_policy(client, policy, policy_config) for firewall, firewall_config in firewall_configs["fir...
5,317,086
def createdb(): """Creates the database with all model tables. Migrations are preferred. """ db.create_all()
5,317,087
def test_combatant_count_resetting(): """Given a combatant that has reached max number of minor actions per round, when they try to take another action, block it until the round is reset""" combatant = cbt.Combatant(**input_character) tgt = cbt.Combatant(**target) with pytest.raises(AttributeError):...
5,317,088
def test_generate_name_from_values_empty(variant_with_no_attributes): """Ensure generate a variant name from a variant without any attributes assigned returns an empty string.""" variant = variant_with_no_attributes generate_and_set_variant_name(variant, variant.sku) variant.refresh_from_db() as...
5,317,089
def make_complex_matrix(x, y): """A function that takes two tensors (a REAL (x) and IMAGINARY part (y)) and returns the combine complex tensor. :param x: The real part of your matrix. :type x: torch.doubleTensor :param y: The imaginary part of your matrix. :type y: torch.doubleTensor :...
5,317,090
def array(dtype, ndim): """ :param dtype: the Numba dtype type (e.g. double) :param ndim: the array dimensionality (int) :return: an array type representation """ if ndim == 0: return dtype return minitypes.ArrayType(dtype, ndim)
5,317,091
def ship_hit(ai_settings,stats,screen,sb,ship,aliens,bullets): """响应被外星人撞到的飞船""" if stats.ships_left > 0: # 将ships_left减1 stats.ships_left-=1 # 更新记分牌 sb.prep_ships() # 清空外星人列表和子弹列表 aliens.empty() bullets.empty() # 创建一群新的外星人,并将飞船放到屏...
5,317,092
def as_pandas(data): """Returns a dataframe if possible, an error otherwise""" if isinstance(data, pd.DataFrame): return data elif isinstance(data, dict): return pd.DataFrame(data) else: raise TypeError( f"Expected a DataFrame or dict type, got: {type(data)} insead" ...
5,317,093
async def command_add_to_role(bot: "latexbot.LatexBot", chat: pyryver.Chat, user: pyryver.User, msg_id: str, args: str): # pylint: disable=unused-argument """ Add people to a role. Note that role names work like Ryver usernames, ie they can only contain alphanumeric characters and underscores, and are ...
5,317,094
def flexible_assert_equal(x1, x2, **kw): """ Flexible assertion equality, including support for scimath objects. """ from scimath.units.api import UnitArray, UnitScalar from app_common.scimath.assertion_utils import \ assert_unit_array_almost_equal, \ assert_unit_scalar_almost_equal ...
5,317,095
def scale3(v, s): """ scale3 """ return (v[0] * s, v[1] * s, v[2] * s)
5,317,096
def _get_last_ext_comment_id(connection): """Returns last external comment id. Args: connection: An instance of SQLAlchemy connection. Returns: Integer of last comment id from external model. """ result = connection.execute( sa.text(""" SELECT MAX(id) FROM ...
5,317,097
def is_unit(v: SupportsAbs[float]) -> bool: # <2> """'True' if the magnitude of 'v' is close to 1.""" return math.isclose(abs(v), 1.0)
5,317,098
def query(*args, **kwargs): """ Perform given cypher query, with optional parameters Example: \b neohelper query \\ "unwind \\$jsons as json MERGE (p:Person { name : json.name, age : json.age }) return count(p) as nodes_merged" \\ -j '{"name" : "John Jackso...
5,317,099