content
stringlengths
22
815k
id
int64
0
4.91M
def _AcosGrad(op, grad): """Returns grad * -1/sqrt(1-x^2).""" x = op.inputs[0] with ops.control_dependencies([grad.op]): x = math_ops.conj(x) x2 = math_ops.square(x) one = constant_op.constant(1, dtype=grad.dtype) den = math_ops.sqrt(math_ops.subtract(one, x2)) inv = math_ops.reciprocal(den) ...
40,500
def test_config(): """Test create_app without passing test config""" assert not create_app().testing assert create_app({"TESTING": True}).testing
40,501
def test_new_client_registration(): """ Should be creating a new client and verify data """ client.new_client_registration(client_request, presenter) new_client = presenter.get_client_view_model() assert new_client.client_id is not None assert new_client.user == user assert new_client.address...
40,502
def converter(n, decimals=0, base=pi): """takes n in base 10 and returns it in any base (default is pi with optional x decimals""" # your code here result = [] # setting list to capture converted digit # check for a proper base if base <= 0: base = pi # if n is zero then set the sta...
40,503
def mediaAddcastInfo(): """ :return: """ reqUrl = req_url('media', "/filmCast/saveFilmCastList") if reqUrl: url = reqUrl else: return "服务host匹配失败" headers = { 'Content-Type': 'application/json', 'X-Region-Id': '2', } body = json.dumps( { ...
40,504
def process_register_fns(): # noqa: WPS210 """Registration in FNS process.""" form = RegisterFnsForm() if form.validate_on_submit(): email = current_user.email name = current_user.username phone = form.telephone.data registration_fns(email, name, phone) flash('Ждите ...
40,505
def validate_args(args): """ Checks if the arguments are valid or not. """ # Is the number of sockets positive ? if not args.number > 0: print("[ERROR] Number of sockets should be positive. Received %d" % args.number) exit(1) # Is a valid IP address or valid name ? try: serve...
40,506
def register(request): """注册""" if request.method == 'GET': # 显示注册页面 return render(request, 'register.html') else: # 进行注册处理 # 1.接收参数 username = request.POST.get('user_name') # None password = request.POST.get('pwd') email = request.POST.get('email') ...
40,507
def triangulation_to_vedo_mesh(tri, **kwargs): """ Transform my triangulation class to Trimesh class :param kwargs: """ coords = tri.coordinates trias = tri.triangulation m = vedo.Mesh([coords, trias], **kwargs) return m
40,508
def build_dropout(cfg, default_args=None): """Builder for drop out layers.""" return build_from_cfg(cfg, DROPOUT_LAYERS, default_args)
40,509
def conv2d_transpose(inputs, num_output_channels, kernel_size, scope, stride=[1, 1], padding='SAME', use_xavier=True, stddev=1e-3, weight_decay=0.0, ...
40,510
def open_py_file(f_name): """ :param f_name: name of the .py file (with extension) :return: a new file with as many (1) as needed to not already exist """ try: f = open(f_name, "x") return f, f_name except IOError: return open_py_file(f_name[:-3] + "(1)" + f_name...
40,511
def cast_rays(rays_o, rays_d, z_vals, r): """shoot viewing rays from camera parameters. Args: rays_o: tensor of shape `[...,3]` origins of the rays. rays_d: tensor of shape `[...,3]` directions of the rays. z_vals: tensor of shape [...,N] segments of the rays r: radius of ray c...
40,512
def ifnone(x: Any, y: Any): """ returns x if x is none else returns y """ val = x if x is not None else y return val
40,513
def get_session(region, default_bucket): """Gets the sagemaker session based on the region. Args: region: the aws region to start the session default_bucket: the bucket to use for storing the artifacts Returns: `sagemaker.session.Session instance """ boto_session = boto3.Ses...
40,514
def xi_einasto_at_r(r, M, conc, alpha, om, delta=200, rhos=-1.): """Einasto halo profile. Args: r (float or array like): 3d distances from halo center in Mpc/h comoving M (float): Mass in Msun/h; not used if rhos is specified conc (float): Concentration alpha (float): Profile ex...
40,515
def _rst_links(contents: str) -> str: """Convert reStructuredText hyperlinks""" links = {} def register_link(m: re.Match[str]) -> str: refid = re.sub(r"\s", "", m.group("id").lower()) links[refid] = m.group("url") return "" def replace_link(m: re.Match[str]) -> str: tex...
40,516
def fibonacci(n: int) -> int: """ Calculate the nth Fibonacci number using naive recursive implementation. :param n: the index into the sequence :return: The nth Fibonacci number is returned. """ if n == 1 or n == 2: return 1 else: return fibonacci(n - 1) + fibonacci(n - 2)
40,517
def validator_msg(msg): """Validator decorator wraps return value in a message container. Usage: @validator_msg('assert len(x) <= 2') def validate_size(x): return len(x) <= 2 Now, if `validate_size` returns a falsy value `ret`, for instance if provided with range(4), we wi...
40,518
def cli(_, source, email_method): """ This is rep. rep is a CLI for generating PDFs of report cards and sending them via email. """ if _.invoked_subcommand is None: generate(source, email_method)
40,519
def RenderHistogramsViewer(histogram_dicts, output_stream, reset_results=False, vulcanized_html='', max_chunk_size_hint_bytes=100000000): """Renders a Histograms viewer to output_stream containing histogram_dicts. Requires a Histograms viewer to have already be...
40,520
def iter_fgsm_t(x_input_t, preds_t, target_labels_t, steps, total_eps, step_eps, clip_min=0.0, clip_max=1.0, ord=np.inf, targeted=False): """ I-FGSM attack. """ eta_t = fgm(x_input_t, preds_t, y=target_labels_t, eps=step_eps, ord=ord, clip_min=clip_min, clip_max=clip_max, tar...
40,521
def list_rbd_volumes(pool): """List volumes names for given ceph pool. :param pool: ceph pool name """ try: out, err = _run_rbd('rbd', '-p', pool, 'ls') except processutils.ProcessExecutionError: # No problem when no volume in rbd pool return [] return [line.strip() for...
40,522
def parse_date(string: Optional[str]) -> Optional[date]: """ Parse a string to a date. """ if not string or not isinstance(string, str): return None try: return isoparse(string[:10]).date() except ValueError: pass try: return datetime.strptime(string[:10], "%Y...
40,523
def xz_write_block(encoder, block_bytes, compression_level): """Write block in "xz" codec.""" data = lzma.compress(block_bytes) encoder.write_long(len(data)) encoder._fo.write(data)
40,524
def test_metadata_extract(): """Should extract pcaxis metadata into a list.""" pc_axis = pyaxis.read( data_path + '14001.px', 'iso-8859-15') metadata_elements, raw_data = pyaxis.metadata_extract(pc_axis) assert type(metadata_elements) == list assert len(metadata_elements) == 28 a...
40,525
def save_dict(file_path, dictonary): """ Saving dictonary as txt, json or csv file :param file_path: Path to file :type file_path: string :param dictonary: dictonary which should be saved :type dictonary: dict :return type: None """ if file_path.endswith('.txt'): with open(f...
40,526
def butter_bandpass(lowcut, highcut, fs, order=5): """ Taken from https://scipy-cookbook.readthedocs.io/items/ButterworthBandpass.html Creates a butterworth bandpass filter of order 'order', over frequency band [lowcut, highcut]. :param lowcut: Lowcut frequency in Hz :param highcut: Highcut...
40,527
def get_current_SSID(): """Helper function to find the WiFi SSID name. Returns: str: Wifi SSID name("" on Exception). """ try: p = subprocess.Popen(["iwgetid", "-r"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() return out.strip().decode("ut...
40,528
def unzip_file (zip_file, output_directory): """ Parameters ---------- zip_file : .ZIP A .zip file that needs to be unzipped. output_directory : STRING The desired output location of the unzipped file. Returns ------- None. """ # unzip the zip dataset ...
40,529
def get_archives_to_prune(archives, hook_data): """Return list of keys to delete.""" files_to_skip = [] for i in ['current_archive_filename', 'old_archive_filename']: if hook_data.get(i): files_to_skip.append(hook_data[i]) archives.sort(key=itemgetter('LastModified'), ...
40,530
def remove_ticket(ticket_name: str, result: bool = None) -> None: """Removes a ticket. Args: ticket_name (str): Name of the ticket. result (bool): Result received from the decorator. Defaults to None. """ if result is not None: if result: Logger().log("The ticket was...
40,531
def tf_pad(tensor, paddings, mode): """ Pads a tensor according to paddings. mode can be 'ZERO' or 'EDGE' (Just use tf.pad for other modes). 'EDGE' padding is equivalent to repeatedly doing symmetric padding with all pads at most 1. Args: tensor (Tensor). paddings (list of lis...
40,532
async def test_get_actions(hass, device_reg, entity_reg): """Test we get the expected actions from a climate.""" config_entry = MockConfigEntry(domain="test", data={}) config_entry.add_to_hass(hass) device_entry = device_reg.async_get_or_create( config_entry_id=config_entry.entry_id, con...
40,533
def get_site_command(): """ Get a specific site by ID """ # Init main vars contents = [] context = {} context_entries = [] title = '' # Get arguments site_id = demisto.args().get('site_id') # Make request and get raw response site = get_site_request(site_id) # Pars...
40,534
def compute_reference_gradient_siemens(duration_ms, bandwidth, csa=0): """ Description: computes the reference gradient for exporting RF files to SIEMENS format, assuming the gradient level curGrad is desired. Theory: the reference gradient is defined as that gradient for which a 1 cm slice is...
40,535
def delete_file(file_name): """Delete a file. Args: file_name (str): The file name. """ try: os.remove(file_name) except: pass
40,536
def schedule_conv2d_NHWC_quantized_native(cfg, outs): """ Interface for native schedule_conv2d_NHWC_quantized""" return _schedule_conv2d_NHWC_quantized(cfg, outs, False)
40,537
def check_fti(ctx, repo, arch, results, open_bug_reports): """Check all Python 2 packages to whether they install""" data = get_data(*ctx.obj['datadirs']) rpms_srpms = pkgs_srpm(data) results = pathlib.Path(results) filtered = {} print('Querying Bugzilla...') bugz = bugzillas() sources_...
40,538
def calc_square_dist(a, b, norm=True): """ Calculating square distance between a and b a: [bs, npoint, c] b: [bs, ndataset, c] """ a = tf.expand_dims(a, axis=2) # [bs, npoint, 1, c] b = tf.expand_dims(b, axis=1) # [bs, 1, ndataset, c] a_square = tf.reduce_sum(tf.square(a), axis=-1) # [bs...
40,539
def read_config(lines): """Read the config into a dictionary""" d = {} current_section = None for i, line in enumerate(lines): line = line.strip() if len(line) == 0 or line.startswith(";"): continue if line.startswith("[") and line.endswith("]"): current_s...
40,540
def get_cert_subject_hash(cert): """ Get the hash value of the cert's subject DN :param cert: the certificate to get subject from :return: The hash value of the cert's subject DN """ try: public_bytes = cert.public_bytes(encoding=serialization.Encoding.PEM) cert_c = crypto.load_...
40,541
async def add_app_role_mapping(appname, role, group, rest_client=None): """ Add a role-group mapping to an application. Args: appname (str): appname ("clientId") of application role (str): application role name group (str): group name """ try: app_data = await app_in...
40,542
def icon_from_url(url: str): """ A very simple attempt at matching up a game URL with its representing icon. We attempt to parse the URL and return the favicon. If that fails, return a pre-determined image based on the URL. """ if not url: return # Allow the user to override icons ...
40,543
def extract_spikes(hd5_file, neuron_num=0): """Extracts the spiking data from the hdf5 file. Returns an array of spike times. Keyword arguments: neuron_num -- the index of the neuron you would like to access. """ with h5py.File(hd5_file, "r+") as f: neuron_list = f['NF']['value']['neuro...
40,544
def symlinkOrCopyFile(src, dst): """ Symlink a file unless GCAM.CopyAllFiles is True, in which case, copy the file. :param src: (str) filename of original file :param dst: (dst) filename of copy :return: none """ if getParamAsBoolean('GCAM.CopyAllFiles'): copyFileOrTree(src, dst) ...
40,545
def do_modular_scale_shifted_adds(gate, input_reg, target_reg, controls): """ Reversibly adds one register, times a constant, into another of the same size, modulo a constant. N: len(input_reg) + len(target_reg) C: len(controls) Size: O(N² lg N + NC) Depth: O(N² + NC) Diagram: c...
40,546
def problem_kinked(x): """Return function with kink.""" return np.sqrt(np.abs(x))
40,547
def test_parse_element(content): """Test the ``parse_element`` method""" assert parse_element(content) == "O"
40,548
def read_dicom(filename): """Read DICOM file and convert it to a decent quality uint8 image. Parameters ---------- filename: str Existing DICOM file filename. """ try: data = dicom.read_file(filename) img = np.frombuffer(data.PixelData, dtype=np.uint16).copy() i...
40,549
def calculate_measure(experiments: List[Experiment], measure: str, verbose: int = 0): """ Given an array of experiments and the name of a measure, calculate the measure for every trial in the experiment. Args: experiments (List[Experiment]): List of experiments to calculate measures for. ...
40,550
def _filter_all_warnings(record) -> bool: """Filter out credential error messages.""" if record.name.startswith("azure.identity") and record.levelno == logging.WARNING: message = record.getMessage() if ".get_token" in message: return not message return True
40,551
def _to_minor_allele_frequency(genotype): """ Use at your own risk """ g_ = copy.deepcopy(genotype) m_ = g_.metadata clause_ = m_.allele_1_frequency > 0.5 F = MetadataTF m_.loc[clause_,[F.K_ALLELE_0, F.K_ALLELE_1]] = m_.loc[clause_,[F.K_ALLELE_1, F.K_ALLELE_0]].values m_.loc[clause_, F.K...
40,552
def ioka(z=0, slope=950, std=None, spread_dist='normal'): """Calculate the contribution of the igm to the dispersion measure. Follows Ioka (2003) and Inoue (2004), with default slope value falling in between the Cordes and Petroff reviews. Args: z (array): Redshifts. slope (float): Slo...
40,553
def test_django_setup_order_and_uniqueness(django_testdir, monkeypatch): """ The django.setup() function shall not be called multiple times by pytest-django, since it resets logging conf each time. """ django_testdir.makeconftest( """ import django.apps assert django.apps.app...
40,554
def preflight(): """Prep a prod push""" test_function([]) make()
40,555
def generic_reader(filename, mode='rt'): """ Returns a file-reader with capability to read line-by-line for both compressed and normal text files. Parameters ----------- filename: string, required The filename for the associated input/output. Can be a compressed (.bz2, .gz, .xz...
40,556
def nn_policy(state_input, policy_arch, dim_action, **kwargs): """ Fully-connected agent policy network """ with tf.variable_scope('policy_net', reuse=tf.AUTO_REUSE): for i, h in enumerate(policy_arch): state_input = layer.Dense(h, activation='tanh', # dtype='float64', ...
40,557
def test_grid5_api_list_filter_two_grid5s(client, gridList): """the grid5 list with a filter for two grid5s should return those those two grid5s, not the third. """ url = reverse("common_api:grid5-list") response = client.get(url + "?lake=HU,ER") assert response.status_code == status.HTTP_200...
40,558
async def connect(args: argparse.Namespace, session: aiohttp.ClientSession) -> None: """Connect to the server.""" async with HomeAssistantClient(args.url, args.token, session) as client: client.register_event_callback(log_events) await asyncio.sleep(360)
40,559
def _check_geom(geom): """Check if a geometry is loaded in. Returns the geometry if it's a shapely geometry object. If it's a wkt string or a list of coordinates, convert to a shapely geometry. """ if isinstance(geom, BaseGeometry): return geom elif isinstance(geom, str): # assume it's ...
40,560
def mtpa(pmrel, i1max, title='', projection='', ax=0): """create a line or surface plot with torque and mtpa curve""" nsamples = 10 i1 = np.linspace(0, i1max, nsamples) iopt = np.array([pmrel.mtpa(x) for x in i1]).T iqmax, idmax = pmrel.iqdmax(i1max) iqmin, idmin = pmrel.iqdmin(i1max) if p...
40,561
def read_csvs_of_program(program: str) -> List[pd.DataFrame]: """ Given the name of an algorithm program, collects the list of CVS benchmarks recorded for that particular program. :param program: name of the program which benchmarks should be retrieved :return: list of benchmark CSV files ...
40,562
def run_bgr_search(project): """Runs DIAMOND classification search on predicted genes""" print('Starting DIAMOND') diamond_args = [project.config.diamond_path, 'blastp', '--db', project.config.get_background_diamond_db(project.options.get_collectio...
40,563
def reload_and_push(url: str, server_data: ServerParse, player_data: PlayerFilter) -> None: """Generates message containing all flagged players and sends the message to the specified webhook URL. """ # Reload data from the server (in case something was changed) an...
40,564
def print_best_metric_found( tuning_status: TuningStatus, metric_names: List[str], mode: str ) -> Tuple[int, float]: """ Prints trial status summary and the best metric found. :param tuning_status: :param metric_names: :param mode: :return: trial-id and value of the best ...
40,565
def get_svn_revision(path = '.', branch = 'HEAD'): """ Returns the SVN revision associated with the specified path and git branch/tag/hash. """ svn_rev = "None" cmd = "git log --grep=^git-svn-id: -n 1 %s" % (branch) result = exec_cmd(cmd, path) if result['err'] == '': for line in result['out'].split...
40,566
def coerce_str_to_bool(val: t.Union[str, int, bool, None], strict: bool = False) -> bool: """ Converts a given string ``val`` into a boolean. :param val: any string representation of boolean :param strict: raise ``ValueError`` if ``val`` does not look like a boolean-like object :return: ``True`` if...
40,567
def test_fleurinp_valid_inpxml(inpxmlfilepath, aiida_env): """ test if inp.xml file is reconnized as valid by fleur """ from aiida.orm import DataFactory fleurinp = DataFactory('fleur.fleurinp') fleurinp_tmp = fleurinp(files=[inpxmlfilepath]) assert fleurinp_tmp._has_schema == True...
40,568
def print_labels_from_csv(request): """ Generates a PDF with labels from a CSV. """ if request.FILES: response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename=labels-from-csv.pdf' canvas = Canvas(response, pagesize=(Roll.widt...
40,569
def get_ucs_node_list(): """ Get UCS nodes """ nodeList = [] api_data = fit_common.rackhdapi('/api/2.0/nodes') for node in api_data['json']: if node["obms"] != [] and node["obms"][0]["service"] == "ucs-obm-service": nodeList.append(node) return nodeList
40,570
def grid_search(fn, grd, fmin=True, nproc=None): """Grid search for optimal parameters of a specified function. Perform a grid search for optimal parameters of a specified function. In the simplest case the function returns a float value, and a single optimum value and corresponding parameter values a...
40,571
def cli(self): """Check the CLI works as intended. """ clickhouse = self.context.nodes[0] create_and_populate_table(node=clickhouse, table_name="cli_table") try: for scenario in loads(current_module(), Scenario, Suite): Scenario(run=scenario) finally: with Finally(...
40,572
def wysiwyg_form_fields(context): """Returns activity data as in field/value pair""" app = context['app_title'] model = context['entity_title'] try: return wysiwyg_config(app, model) except (KeyError, AttributeError): return None
40,573
def test001_get_redisclient_using_port_unixsocket(type): """TC564 Test case for getting redis client using port/unixsocket. **Test scenario** #. Start redis server on port/unixsocket. #. Get redis client using port/unixsocket. #. Try to ping the server, should succeed. """ info(f"Start ...
40,574
def thetagrids(angles=None, labels=None, fmt=None, **kwargs): """ Get or set the theta gridlines on the current polar plot. Call signatures:: lines, labels = thetagrids() lines, labels = thetagrids(angles, labels=None, fmt=None, **kwargs) When called with no arguments, `.thetagrids` simply ...
40,575
def get_ordered_patterns(order, patterns): """ Place the sites in the pattern dictionary into the order that they were added. Input: order: a list of pattern ids providing the order patterns: a dictionary of patterns Output: Nested array with columns for sites, their order, and ampl...
40,576
def extract_pphour(file, fecha, llat, llon): """ """ l_lat = llat l_lon = np.array(llon) % 360 i_lat, i_lon, lat, lon = get_index_lat(fecha, file, llat, llon) tiempos = get_index_time(file, fecha) di = tiempos[1] di_f = (di + dt.timedelta(days=8)).replace(hour=0) i_t1 = [i for i in r...
40,577
def bubble_sort2(array): """冒泡排序的经典实现""" n = len(array) stop = False #子过程运行闭区间的右端点标记定义为i,范围[n-1,1],转换为适合while惯用区间为[n-1,0) i = n-1 while i > 0 and not stop: stop = True #子过程交换位置标记定义为j,范围为[0,i-1],转换为适合while惯用区间为[0,i) #子过程运行区间为[0,i] j = 0 while j < i: if array[j] > array[j+1]: array[j],array[j+1] =...
40,578
def encriptar(texto): """função que recebe um texto e retorna o mesmo criptografado""" #1. Filtro de entrada para evitar erros #1.1 Verifica se texto é uma string #1.1 Se texto é vazio, retorna texto #2. remove os espaços em branco do texto texto = texto.replace(" ","") ...
40,579
def load_spn_json(f: Union[IO, os.PathLike, str], leaves: Optional[List[Type[Leaf]]] = None) -> Node: """ Load SPN from file by using the JSON format. :param f: A file-like object or a filepath of the input JSON file. :param leaves: An optional list of custom leaf classes. Useful when dealing with user...
40,580
def test_get_permissions(): """ Test the permissions used by the view. """ view = views.MediaResourceCoverStyleDetailView() assert test_utils.uses_permission_class(view, DRYPermissions) assert test_utils.uses_permission_class(view, ObjectOwnerHasPremium)
40,581
def extend_enum(*inherited_enums: type[Enum]): """EXPERIMENTAL Join multiple enums into one. Modified version from: https://stackoverflow.com/a/64045773/14748231 """ # All members from all enums which injected in result enum joined_members = {} def _add_item_if_not_exist(item) -> None: ...
40,582
def tsv_reader(): """ read register-like data from government-form-data TSV""" resp = requests.get(url=url) resp.raise_for_status() return csv.DictReader(io.StringIO(resp.text), delimiter=sep)
40,583
def GetMonotime(): """Older tornado doesn't have monotime(); stay compatible.""" if hasattr(tornado.util, 'monotime_impl'): return tornado.util.monotime_impl else: return time.time
40,584
def test_multiplica(): """ Target function returns the sum of the multilica of two given vector. Expect output as np.float object. """ dict_1 = file_read.read_file('../../data/10mM_2,7-AQDS_1M_KOH_25mVs_0.5step_2.txt') data = file_read.data_frame(dict_1, 1) col_x1, col_x2 = baseline.split(da...
40,585
def test_multi_bracket_validation_words_and_brackets(): """Validate words dont affect bracket pattern search.""" assert multi_bracket_validation('hello[]world') is True
40,586
def plot_confusion_matrix(cm, classes, normalize=False, title='Confusion matrix', cmap=plt.cm.Blues): """ This function prints and plots the confusion matrix. Normalization can be applied by setting `normalize=True`. (This function is copied from the scikit docs.) """ plt.figure() plt.imshow...
40,587
def test_atoms_to_xyz(): """Test that writing atoms to xyz format is handled correctly in the presence of tags""" h2o = Atoms('H2O') # pylint: disable=assigning-non-slot h2o[0].charge = -1 h2o[0].tag = 1 h2o[1].tag = 2 xyz = _atoms_to_xyz(h2o) # pylint: disable=protected-access assert...
40,588
def last_name_first(n): """Returns: copy of n in form 'last-name, first-name' Precondition: n string in form 'first-name last-name n has only space, separating first and last.""" assert type(n) == str, str(n) + " is not a string" assert is_two_words(n), n+' has the wrong form' # Compute the va...
40,589
def _proc_msg_flddata(fld, return_dict): """process fieldData""" try: info = {} fld_id = fld.getElementValue(bn.ID) if fld.hasElement(bn.ERR_FLD): raise be.FieldError(fld.getElement(bn.ERR_FLD), fld_id) fld_info = fld.getElement(bn.FLD_INFO) mnemonic...
40,590
def by_count(logger: logging.Logger, once_every: int) -> logging.Logger: """ The returned logger will only permit at most one print every `once_every` logging calls from the code line this function was called from. Usage example:: for i in range(100): log_throttling.by_count(logger...
40,591
def run_script(smc_client, filename, print_only=False, preprocess_only=False, user_variables=None, variable_files=None, ignore_errors=False, delete_mode=False, cleanup_mode=False): """execute a script :param SMCClient smc_client: client to send reques...
40,592
def filter_poi(dst, srcs): """ Filter out the tweets with the place type of POI (JSON version) """ fdst = open(dst, 'w+') k = 0 i = 0 try: for line in fileinput.input(srcs, openhook = fileinput.hook_compressed): i += 1 try: status = json....
40,593
def has_new_code(is_git): """Tests if there are any newer versions of files on the server. Args: - is_git: True if we are working in a git repository. """ os.chdir(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) if not is_git: results, _ = run_cmd(['svn', 'st']) else: ...
40,594
def _error( message: str, trailing_newline: bool = False ) -> None: """ Prints an error message to console. :param (str) message: Message to display. :param (bool) trailing_newline: Whether to add a new line at the start. """ if trailing_newline: rprint("\n[red bold]Er...
40,595
def load_ps_label(frame_id): """ :param frame_id: file name of pseudo label :return gt_box: loaded gt boxes (N, 9) [x, y, z, w, l, h, ry, label, scores] """ if frame_id in PSEUDO_LABELS: gt_box = PSEUDO_LABELS[frame_id]['gt_boxes'] else: raise ValueError('Cannot find pseudo label...
40,596
async def execute( url_path: str, body: dict, codef, service_type: ServiceType, ) -> dict: """ API 요청 실행 함수. 실제 사용자에게 제공되는 함수 내부에서 이 함수를 호출해서 사용할 것을 권장한다. :param url_path: 요청 URL 경로 :param body: post 요청 바디 :param codef: codef 인스턴스 :param service_type: 서비스 타입 ...
40,597
def main() -> int: """ Execute all tasks. """ get_googletest() return 0
40,598
async def async_unload_entry( hass: HomeAssistantType, config_entry: config_entries.ConfigEntry, ) -> bool: """Unload Energosbyt Plus entry""" log_prefix = _make_log_prefix(config_entry, "setup") entry_id = config_entry.entry_id update_delegators: UpdateDelegatorsDataType = hass.data[DA...
40,599