content
stringlengths
22
815k
id
int64
0
4.91M
def deploy_droplet(token): """ deploy a new droplet. return the droplet infos so that it can be used to further provision. """ droplet_info = { 'name': 'marian', 'region': 'sfo2', 'size': '4gb', 'image': 'ubuntu-18-04-x64', 'ssh_keys[]': get_key_fingerprints(...
5,344,200
def annotate_repos(repos, roster): """Annotate repo['login'] with the login of the student who generated the repo Find the longest common prefix of the repository names. """ common_prefix = longest_prefix([r["name"] for r in repos]) for r in repos: login = r["name"][len(common_prefix) :] ...
5,344,201
def _convert_run_describer_v1_like_dict_to_v0_like_dict( new_desc_dict: Dict[str, Any]) -> Dict[str, Any]: """ This function takes the given dict which is expected to be representation of `RunDescriber` with `InterDependencies_` (underscore!) object and without "version" field, and converts it t...
5,344,202
def currentGUIusers(): """Gets a list of GUI users by parsing the output of /usr/bin/who""" gui_users = [] proc = subprocess.Popen('/usr/bin/who', shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) output = proc.com...
5,344,203
def download_sequences(request): """Download the selected and/or user uploaded protein sequences.""" selected_values = request.session.get("list_names", []) list_nterminal = request.session.get("list_nterminal", []) list_middle = request.session.get("list_middle", []) list_cterminal = request.sessi...
5,344,204
def resize_to_fill(image, size): """ Resize down and crop image to fill the given dimensions. Most suitable for thumbnails. (The final image will match the requested size, unless one or the other dimension is already smaller than the target size) """ resized_image = resize_to_min(image, size) ...
5,344,205
def display_warning(warning_msg): """ Displays warning message in Maya :param warning_msg: str, warning text to display """ warning_msg = warning_msg.replace('\n', '\ntp:\t\t') maya.OpenMaya.MGlobal.displayWarning('tp:\t\t' + warning_msg) LOGGER.warning('\n{}'.format(warning_msg))
5,344,206
def _iterate_examples( file_in, version, ): """Reads examples from TSV file.""" if version == Version.V_02: for line in file_in: fields = line.rstrip().split('\t') qid = fields[0] question = fields[1] wtq_table_id = fields[2] answers = fields[3:] yield qid, question, ...
5,344,207
def extract_dual_coef(num_classes, sv_ind_by_clf, sv_coef_by_clf, labels): """ Construct dual coefficients array in SKLearn peculiar layout, as well corresponding support vector indexes """ sv_ind_by_class = group_indices_by_class( num_classes, sv_ind_by_clf, labels) sv_ind_mapping = map_sv_...
5,344,208
def test_setattr_context(): """Test of the setattr_context() function""" class Foo(object): pass f = Foo() f.attr = "abc" with utils.setattr_context(f, attr="123"): assert_equal(f.attr, "123") assert_equal(f.attr, "abc") try: with utils.setattr_context(f, attr="123")...
5,344,209
def extract(func): """ Decorator function. Open and extract data from CSV files. Return list of dictionaries. :param func: Wrapped function with *args and **kwargs arguments. """ def _wrapper(*args): out = [] instance, prefix = args for fname in glob.glob(os.path.join(getat...
5,344,210
def namespaces_of(name): """ utility to determine namespaces of a name @raises ValueError @raises TypeError """ if name is None: raise ValueError('name') try: if not isinstance(name, basestring): raise TypeError('name') except NameError: if not isinst...
5,344,211
def create_c3d_sentiment_model(): """ C3D sentiment Keras model definition :return: """ model = Sequential() input_shape = (16, 112, 112, 3) model.add(Conv3D(64, (3, 3, 3), activation='relu', padding='same', name='conv1', input_shape=input_shape)) ...
5,344,212
def list_all_projects(path): """lists all projects from a folder""" project_names = [] for file in os.listdir(path): if not os.path.isfile(os.path.join(path, file)): continue project_names.append(file.split('.')[0]) return project_names
5,344,213
def notch_filter(data: FLOATS_TYPE, sampling_freq_hz: float, notch_freq_hz: float, quality_factor: float) -> FLOATS_TYPE: """ Design and use a notch (band reject) filter to filter the data. Args: data: time series of the data sampling_freq_...
5,344,214
def get_trail_max(self, rz_array=None): """ Return the position of the blob maximum. Either in pixel or in (R,Z) coordinates if rz_array is passed. """ if (rz_array is None): return self.xymax # Remember xycom[:,1] is the radial (X) index which corresponds to R return rz_array[self....
5,344,215
def create_action_type(request): """ Create a new action type """ # check name uniqueness if ActionType.objects.filter(name=request.data['name']).exists(): raise SuspiciousOperation(_('An action with a similar name already exists')) description = request.data.get("description") labe...
5,344,216
def ec_chi_sq(params,w,y,weights,model,normalize='deg'): """ Chi squared for equivalent circuit model. Parameters: ----------- params: dict of model parameters w: frequencies y: measured impedance data: nx2 matrix of Zreal, Zimag weights: weights for squared residuals (n-vector) model: equivalent circuit mo...
5,344,217
def delete_demo(collection_id): """Deletes a single demo collection. Args: collection_id: str. ID of the demo collection to be deleted. """ if not collection_domain.Collection.is_demo_collection_id(collection_id): raise Exception('Invalid demo collection id %s' % collection_id) col...
5,344,218
def plot_regressors_scores(r_list, r_str, x_test, y_true, fig_dir, txt): """Given a list of fitted regressor objects, compare their skill on a variety of tests""" mse = [] r2_u = [] r2_w = [] exp_var_u = [] exp_var_w = [] for reg in r_list: y_pred = reg.predict(x_test) ms...
5,344,219
def declare_eq_p_balance_dc_approx(model, index_set, bus_p_loads, gens_by_bus, bus_gs_fixed_shunts, inlet_branches_by_bus, outlet_branches_by_bus, ...
5,344,220
def synthesize_genre_favs(xn_train_df): """ Making synthetic user-genre favorite interactions We're going to just count the genres watched by each user. Subsample from a random top percentile of genres and consider those the user's favorites. We will then subsample again -- simulating the volun...
5,344,221
def mfa_to_challenge(mfa): """ Convert MFA from bastion to internal Challenge param mfa: MFA from bastion :rtype: Challenge :return: a converted Challenge """ if not mfa.fields: return None message_list = [] echos = [False for x in mfa.fields] fields = mfa.fields if hasa...
5,344,222
def override_stdouts(): """Override `sys.stdout` and `sys.stderr` with `StringIO`.""" prev_out, prev_err = sys.stdout, sys.stderr mystdout, mystderr = StringIO(), StringIO() sys.stdout = sys.__stdout__ = mystdout sys.stderr = sys.__stderr__ = mystderr yield mystdout, mystderr sys.stdout = ...
5,344,223
def put_vns3_controller_api_password( api_client, vns3_controller_id, api_password=None, **kwargs ): # noqa: E501 """Update VNS3 Controller API password # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> respo...
5,344,224
def create_pod(interface_type=None, pvc_name=None, desired_status=constants.STATUS_RUNNING, wait=True): """ Create a pod Args: interface_type (str): The interface type (CephFS, RBD, etc.) pvc (str): The PVC that should be attached to the newly created pod desired_status (str): The s...
5,344,225
def main(): """TODO: Docstring for main. :returns: TODO """ s_task = select([t_task.c.id, t_task.c.dname, t_task.c.addresses]).where(t_task.c.status == 'new').limit(1000) s_result = select([t_result.c.id, t_result.c.dname]) u_task = t_task.update().where(t_task.c.id == bindparam('_id')).values(...
5,344,226
def before_feature(context, feature): """ feature hook before running """ GlobalContext.process("before_feature_processor", context, feature)
5,344,227
def _hash(item: str, maxsize=sys.maxsize) -> int: """An unsalted hash function with a range between 0 and maxsize :param item: string or string like object that is accepted by builtin function `str` :type item: str param maxsize: maximum value of returned integer :type maxsize: int :return:...
5,344,228
def _wait_for_query_to_complete(search_id, qradar_client, timeout, polling_interval): """ Poll QRadar until search execution finishes """ start_time = time.time() search_status = qradar_client.get_search_status(search_id) if not search_status: # Sometimes it takes a little while to be able to qu...
5,344,229
def create_annotation(annotation_id: int, image_id: int, category_id: int, is_crowd: int, area: int, bounding_box: Tuple[int, int, int, int], segmentation: List[Tuple[int, int]]) -> dict: """ Converts input data to COCO annotation information storing format. :param int annotation_id: ...
5,344,230
def generate_heatmap(correlation_frame, p_values, x_axes, y_axes, filename='heatmap'): """Creates an heat map @:param correlation_frame: pandas frame that contains the values to plot @:param p_values: the pandas frame that contains the p-values @:param x_axes: the axes to render to the x axis @:para...
5,344,231
def check_sequence_is_valid(seq, alignment=False): """ Parameters -------------- seq : str Amino acid sequence alignment : bool Flag that defines if this alignment sequence rules should be applied or not. Returns ------------ Tuple Returns a tuple of si...
5,344,232
def get_device(): """Pick GPU if available, else CPU""" if torch.cuda.is_available(): return torch.device('cuda') else: return torch.device('cpu')
5,344,233
def extension_chisquare(x, y=None, lower=True): """Calculates a one-way chi square test for file extensions. :param x: Paths to compare with y. :type x: list, tuple, array of WindowsFilePath or PosixFilePath objects :param y: Paths to compare with x. :type y: list, tuple, array of WindowsFilePath o...
5,344,234
def cprint( fmt, fg=None, bg=None, style=None ): """ Colour-printer. cprint( 'Hello!' ) # normal cprint( 'Hello!', fg='g' ) # green cprint( 'Hello!', fg='r', bg='w', style='bx' ) # bold red blinking on white List of col...
5,344,235
def kuster_toksoz_moduli( k1, mu1, k2, mu2, frac2, inclusion_shape="spheres", alpha=None ): """Kuster-Toksoz Moduli for an inclusion to a material. Best used for low-porosity materials. To add multiple inclusions to a model use this function recursively substituting the output for k1 and mu1 afte...
5,344,236
def fetchResearchRadius(chatId: str, reachableByFoot: bool) -> tuple: """Given a chat id and a distance type, returns the user distance preference. Args: chatId (str) - the chat_id of which the language is required reachableByFoot (bool) - true if the preferred_distance_on_foot param has to be ...
5,344,237
def build_train_valid_test_datasets(tokenizer, data_class, data_prefix, data_impl, splits_string, train_valid_test_num_samples, enc_seq_length, dec_seq_length, seed, skip_warmup, prompt_config): """Build train, valid, and test datasets.""" ...
5,344,238
async def uvm_do_on_with(seq_obj, SEQ_OR_ITEM, SEQR, *CONSTRAINTS): """ This is the same as `uvm_do_with` except that it also sets the parent sequence to the sequence in which the macro is invoked, and it sets the sequencer to the specified ~SEQR~ argument. The user must supply the constraints using...
5,344,239
def test_images_default(fake_bar): """Test BatteryIcon() with the default theme_path Ensure that the default images are successfully loaded. """ batt = BatteryIcon() batt.fontsize = 12 batt.bar = fake_bar batt.setup_images() assert len(batt.surfaces) == len(BatteryIcon.icon_names) f...
5,344,240
def _scal_sub_fp(x, scal): """Subtract a scalar scal from a vector or matrix x.""" if _type_of(x) == 'vec': return [a - scal for a in x] else: return [[a - scal for a in x_row] for x_row in x]
5,344,241
def write_source_file_test(name, in_file, out_file): """Stamp a write_source_files executable and a test to run against it""" _write_source_file( name = name + "_updater", in_file = in_file, out_file = out_file, diff_test = False, ) # Note that for testing we update the...
5,344,242
def asset_name(aoi_model, model, fnf=False): """return the standard name of your asset/file""" prefix = "kc_fnf" if fnf else "alos_mosaic" filename = f"{prefix}_{aoi_model.name}_{model.year}" if model.filter != "NONE": filename += f"_{model.filter.lower()}" if model.rfdi: filename...
5,344,243
def create_joint_fusion_workflow( WFname, onlyT1, master_config, runFixFusionLabelMap=True ): """ This function... :param WFname: :param onlyT1: :param master_config: :param runFixFusionLabelMap: :return: """ from nipype.interfaces import ants if onlyT1: n_modality =...
5,344,244
def do_ktools_mem_limit(max_process_id ,filename): """ Set each Ktools pipeline to trap and terminate on hitting its memory allocation limit Limit: Maximum avalible memory / max_process_id """ cmd_mem_limit = 'ulimit -v $(ktgetmem {})'.format(max_process_id) print_command(filena...
5,344,245
def get_partition_info_logic(cluster_name): """ GET 请求集群隔离区信息 :return: resp, status resp: json格式的响应数据 status: 响应码 """ data = '' status = '' message = '' resp = {"status": status, "data": data, "message": message} partition_info = SfoPartitionsInfo.query.fi...
5,344,246
def choice_group_name(identifier: Identifier) -> Identifier: """ Generate the XML group name for the interface of the given class ``identifier``. >>> choice_group_name(Identifier("something")) 'something_choice' >>> choice_group_name(Identifier("URL_to_something")) 'urlToSomething_choice' ...
5,344,247
def init_all_sources_wavelets(observation, centers, min_snr=50, bulge_grow=5, disk_grow=5, use_psf=True, bulge_slice=slice(None,2), disk_slice=slice(2, -1), scales=5, wavelets=None): """Initialize all sources using wavelet detection images. This does not initialize the SED and morpholgy parameters, so ...
5,344,248
def init_coreg_conversion_wf(name: str = "coreg_conversion_wf") -> pe.Workflow: """ Initiate a workflow to convert input files to NIfTI format for ease of use Parameters ---------- name : str, optional Workflow's name, by default "nii_conversion_wf" Returns ------- pe.Workflow...
5,344,249
def rgb2hex(rgb_color): """ 'rgb(180, 251, 184)' => '#B4FBB8' """ rgb = [int(i) for i in rgb_color.strip('rgb()').split(',')] return '#{:02x}{:02x}{:02x}'.format(rgb[0], rgb[1], rgb[2])
5,344,250
def test_process_recipient_list_with_valid_phone_strings(): """Test ability to process recipient list with valid phone numbers.""" data = sms.process_recipient_list("+1-212-555-0001", 2) assert len(data) == 1 data = sms.process_recipient_list("+1-212-555-0001|+1-212-555-0002", 2) assert len(data) =...
5,344,251
def my_script(arg1: int, arg2: str): """Test script""" for i in range(10): log('Dummy', float(i), global_step=i)
5,344,252
def validate_tax_request(tax_dict): """Return the sales tax that should be collected for a given order.""" client = get_client() if not client: return try: tax_data = client.tax_for_order(tax_dict) except taxjar.exceptions.TaxJarResponseError as err: frappe.throw(_(sanitiz...
5,344,253
def test_model_design_integration_risky(model): """Tests integration of model and design. Basically conducts Parameter Estimation""" D = DesignSpaceBuilder( DA=[0.0], DB=[0.0], PA=[1.0], PB=list(np.linspace(0.01, 0.99, 91)), RA=list(100 * np.linspace(0.05, 0.95, 19))...
5,344,254
def union_with(array, *others, **kargs): """This method is like :func:`union` except that it accepts comparator which is invoked to compare elements of arrays. Result values are chosen from the first array in which the value occurs. Args: array (list): List to unionize with. others (lis...
5,344,255
def CalculateMoranAutoVolume(mol): """ ################################################################# Calculation of Moran autocorrelation descriptors based on carbon-scaled atomic van der Waals volume. Usage: res=CalculateMoranAutoVolume(mol) Input: mol is a m...
5,344,256
def parse_acl(acl_iter): """Parse a string, or list of ACE definitions, into usable ACEs.""" if isinstance(acl_iter, basestring): acl_iter = [acl_iter] for chunk in acl_iter: if isinstance(chunk, basestring): chunk = chunk.splitlines() chunk = [re.sub(r'#.+', '', l...
5,344,257
def execute(cursor, query): """Secure execute for slow nodes""" while True: try: cursor.execute(query) break except Exception as e: print("Database query: {} {}".format(cursor, query)) print("Database retry reason: {}".format(e)) return cursor
5,344,258
def zip_to_gdal_path(filepath): """ Takes in a zip filepath and if the zip contains files ascii files, prepend '/viszip' to the path so that they can be opened using GDAL without extraction. """ zip_file_list = [] if zipfile.is_zipfile(filepath): try: zip_file ...
5,344,259
def calculateMACD(prices_data): """Calculate the MACD of EMA15 and EMA30 of an asset Args: prices_data (dataframe): prices data Returns: macd (pandas series object): macd of the asset macd_signal (pandas series object): macd signal of the asset """ ema15 = pd.Series(prices_...
5,344,260
async def async_setup(hass: HomeAssistant, config: dict): """Set up the Logitech Squeezebox component.""" return True
5,344,261
def partida_19(): """partida_19""" check50.run("python3 volleyball.py").stdin("A\nA\nA\nB\nB\nB\nA\nB\nA\nA\nB\nA\nA", prompt=False).stdout("EMPIEZA\nSACA A\nGANA A\nA 1 B 0\nSACA A\nGANA A\nA 2 B 0\nSACA A\nGANA A\nA 3 B 0\nSACA A\nGANA B\nA 3 B 0\nSACA B\nGANA B\nA 3 B 1\nSACA B\nGANA B\nA 3 B 2\nSACA B\nGANA...
5,344,262
def generateDwcaExportFiles(request): """ Generates DarwinCore-Archive files for the 'Export formats' page. """ error_message = None # if request.method == "GET": form = forms.GenerateDwcaExportFilesForm() contextinstance = {'form' : form, 'error_messa...
5,344,263
def composer_update(php_bin, composer_bin, memory_limit=False): """ Updates composer for project :param php_bin: path to php executable :param composer_bin: path to composer executable :param memory_limit: memory limit for composer update :return: """ if memory_limit: command = '...
5,344,264
def treeFromList(l): """ Builds tree of SNode from provided list Arguments: l: the list with tree representation Return: the tuple with root node of the tree and the sentence index of last leaf node """ root = SNode("S") s_index = 0 for child in l: node = SNode(ch...
5,344,265
def with_event_loop(func): """ This method decorates functions run on dask workers with an async function call Namely, this allows us to manage the execution of a function a bit better, and especially, to exit job execution if things take too long (1hr) Here, the function func is run in a background th...
5,344,266
def test_3d_time(): """reading/writing of 3D NMRPipe time domain data""" dic, data = ng.pipe.read( os.path.join(DATA_DIR, "nmrpipe_3d", "data", "test%03d.fid")) sdic, sdata = ng.pipe.read( os.path.join(DATA_DIR, "nmrpipe_3d", "data", "test001.fid")) assert data.shape == (128, 88, 1250) ...
5,344,267
def create_table_of_content(steering_file,data_root,load_all_tables,indices,names): """ Create a table of content for all the tables found in the STEERING_FILE that can be used in your submission. You can put the output (snippet) directly into your 'steering_file' as a table called 'overview'. ...
5,344,268
def get_current_time(): """Retrieve a Django compliant pre-formated datetimestamp.""" datetime_tz_naive = datetime.datetime.now() django_timezone = settings.TIME_ZONE datetime_tz = pytz.timezone(django_timezone).localize(datetime_tz_naive) return datetime_tz
5,344,269
def is_eval_epoch(cfg, cur_epoch): """ Determine if the model should be evaluated at the current epoch. Args: cfg (CfgNode): configs. Details can be found in sgs/config/defaults.py cur_epoch (int): current epoch. """ return ( cur_epoch + 1 ) % cfg.TRAIN.EVAL_P...
5,344,270
def get_app_run_sleep(): """Returns the entrypoint command that starts the app.""" return get(cs.ODIN_CONF, cs.APP_SECTION, cs.RUN_SLEEP)
5,344,271
def plot_sphere(Radius, Point, part="Part::Feature", name="Sphere", grp="WorkObjects"): """ makeSphere(radius,[pnt, dir, angle1,angle2,angle3]) -- Make a sphere with a given radius By default pnt=Vector(0,0,0), dir=Vector(0,0,1), angle1=0, angle2=90 and angle3=360 """ if not(App.ActiveDocument.g...
5,344,272
def test_harvester(mocker): """Test the reddit harvester.""" mocker.patch('praw.Reddit', new_callable=PrawMock) source = Source.objects.get(code='reddit') harvester = Harvester(source) jobs = harvester.harvest() assert jobs is not None assert len(list(jobs)) >= 100
5,344,273
def process_test_set(num_workers, failed_save_file): """ Extract video frames for the test set. :param num_workers: Number of worker processes. :param failed_save_file: Path to a log of failed extractions. :return: None. """ pool = parallel.Pool(None, config.TEST_ROOT,...
5,344,274
def write_json_path(out_json_path, json_data): """ 写入 JSON 数据 :param out_json_path: :param json_data: :return: """ with open(out_json_path, 'w') as f: json.dump(json_data, f, indent=4)
5,344,275
async def my_job_async_gen(my_job_manager): """Fixture provides the job definition (async generator). Returns: The object yielded by the fixture `my_job_manager` with one extra attribute: `job` - job function decorated with `@job` and wrapped into `sync_to_async` for convenience (tests ...
5,344,276
def test(): """Test. """ all_boards = glob.glob("src/boards/*") boards = set(all_boards) - set("cygwin") for board in boards: git_clean_dfx() # Building one application is enough to ensure that all code # in src/ compiles. command = [ "make", ...
5,344,277
def VerifyLatestAFDOFile(afdo_release_spec, buildroot, gs_context): """Verify that the latest AFDO profile for a release is suitable. Find the latest AFDO profile file for a particular release and check that it is not too stale. The latest AFDO profile name for a release can be found in a file in GS under the ...
5,344,278
def cluster(self, net_cvg, net_boxes): """ Read output of inference and turn into Bounding Boxes """ batch_size = net_cvg.shape[0] boxes = np.zeros([batch_size, MAX_BOXES, 5]) for i in range(batch_size): cur_cvg = net_cvg[i] cur_boxes = net_boxes[i] if (self.is_groundt...
5,344,279
def _disable_autopx(self): """Disable %autopx by restoring the original runsource.""" if hasattr(self, 'autopx'): if self.autopx == True: self.runsource = self._original_runsource self.autopx = False print "Auto Parallel Disabled"
5,344,280
def _getMissingResidues(lines): """Returns the missing residues, if applicable.""" try: missing_residues = [] for i, line in lines['REMARK 465']: if len(line.split()) == 5 and int(line.split()[4]) > 0: missing_residues.append("{0:<3s} {1}{2:>4d}".format(line.split()[...
5,344,281
def test_changing_font_size(): """Test that the font_size property properly scales DecimalNumber.""" num = DecimalNumber(0, font_size=12) num.font_size = 48 assert num.height == DecimalNumber(0, font_size=48).height
5,344,282
def register_single_sampler(name): """ A decorator with a parameter. This decorator returns a function which the class is passed. """ name = name.lower() def _register(sampler): if name in _registered_single_sampler: raise ValueError("Name {} already chosen, choose a differe...
5,344,283
def export_txt(obj, file_name, two_dimensional=False, **kwargs): """ Exports control points as a text file. For curves the output is always a list of control points. For surfaces, it is possible to generate a 2-D control point output file using ``two_dimensional`` flag. Please see the supported file format...
5,344,284
def add_permissions_to_file(filename, add_stat): """ Adds file permission on a existing file path """ st = os.stat(filename) try: os.chmod(filename, st.st_mode | add_stat) except Exception as e: logging.error("Path '%s' stat is %s", filename, st) raise e
5,344,285
def compile(expr): """ Force compilation of expression for the Postgres target """ from .client import PostgresDialect from ibis.sql.alchemy import to_sqlalchemy return to_sqlalchemy(expr, dialect=PostgresDialect)
5,344,286
def build_bar_chart(x_axis_name, request, **kwargs): """This abstract function is used to call submethods/specific model""" base_query = request.GET.get("base_query", None) bar_chart_input = [] if base_query == 'group_users': bar_chart_input = group_users_per_column(x_axis_name) elif base_q...
5,344,287
def diff_hours(t1,t2): """ Number of hours between two dates """ return (t2-t1).days*hours_per_day + (t2-t1).seconds/seconds_per_hour
5,344,288
def fatorial(num=1, show=False): """ Calcula o fatorial de um número: :param n: O número a ser calculado. :param show: (opcional) Mostrar ou não os cálculos. :return: O valor do fatorial. """ f = 1 c = num if show==True: while c > 0: print(c, end='') ...
5,344,289
def get_season(msg, info_fields): """find season in message""" seasonDICT = {'2016':['二零一六球季', '二零一六賽季', '2016球季', '2016賽季', '2016年', '2016'], '2017':['二零一七球季', '二零一七賽季', '2017球季', '2017賽季', '2017年', '2017'], '2018':['二零一八球季', '二零一八賽季', '2018球季', '2018賽季', '2018年', '2018'], ...
5,344,290
def gray_img(img:'numpy.ndarray'): """ 对读取的图像进行灰度化处理 :param img: 通过cv2.imread(imgPath)读取的图像数组对象 :return: 灰度化的图像 """ grayImage=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) return grayImage pass
5,344,291
def draw_circles(window, points, radius, color): """ What comes in: -- An rg.RoseWindow -- A sequence of rg.Point objects -- A positive number -- A string that can be used as a RoseGraphics color What goes out: Nothing (i.e., None). Side effects: See draw_circles_picture....
5,344,292
def main(): """ウインドウの表示 すでに表示されていた場合は閉じるだけ """ global window window = NN_ToolWindow() if pm.window(window.window, exists=True): pm.deleteUI(window.window, window=True) else: window.create()
5,344,293
def class_acc(label_threshold_less): """ Wrapper function to return keras accuracy logger Args: label_threshold_less (int): all label IDs strictly less than this number will be ignored in class accuracy calculations Returns: argument_candidate_acc (function) """ def arg...
5,344,294
def left_turn(degree: float): """ Turn turtle left (counter-clockwise) by \"degree\" degree. :param degree: the degree to turn """ _check_turtle() _turtle.left_turn(degree)
5,344,295
def write_wordsearch_svg(filename, grid, wordlist): """Save the wordsearch grid as an SVG file to filename.""" width, height = 1000, 1414 with open(filename, 'w') as fo: svg_preamble(fo, width, height) y0, svg_grid = grid_as_svg(grid, width, height) print(svg_grid, file=fo) ...
5,344,296
def reduce_30Hz(meas_run_30Hz, ref_run_30Hz, ref_data_60Hz, template_30Hz, scan_index=1, template_reference=None): """ Perform 30Hz reduction @param meas_run_30Hz: run number of the data we want to reduce @param ref_run_30Hz: run number of the reference data, take with the same config ...
5,344,297
def input_bed_message(driver): """输入床铺信息""" driver.find_element_class_name_and_click('床铺信息') driver.find_element_class_name_and_click('添加床铺') driver.find_element_id_and_click_wait(driver.ele.FBXT_tv_title_publish_lu_bed_add_item) driver.find_element_id_and_click_wait(driver.ele.FBXT_btn_submit_publi...
5,344,298
def test_sgts_in_database(arg): """Whitelisted SGTs must have Dashboard and ISE IDs in the DB; Default SGTs must have ISE IDs in the DB""" success = True default_vals = [d['value'] for d in sync._config.ise_default_sgts] sgts = Tag.objects.order_by("tag_number") for s in sgts: ds = s.tagdat...
5,344,299