content
stringlengths
22
815k
id
int64
0
4.91M
def pyregion_subset(region, data, mywcs): """ Return a subset of an image (`data`) given a region. Parameters ---------- region : `pyregion.parser_helper.Shape` A Shape from a pyregion-parsed region file data : np.ndarray An array with shape described by WCS mywcs : `astropy...
5,357,100
def transformer_encoder(encoder_input, encoder_self_attention_bias, hparams, name="encoder", nonpadding=None, save_weights_to=None, make_image_summary=True): """A stack of tr...
5,357,101
def update(event, context): """ Place your code to handle Update events here To return a failure to CloudFormation simply raise an exception, the exception message will be sent to CloudFormation Events. """ region = os.environ['AWS_REGION'] prefix_list_name = event['ResourceProperties']['Pr...
5,357,102
def plotComparison(parameters, optimizationModel, reference, X, Y): """ This function generates a figure with the following subplots: (1) Stress vs. strain for reference and current observation, (2) Initial effective temperature (Teff) field contour with colorbar, (3) Final observat...
5,357,103
def compute_dict(file_path): """Computes the dict for a file whose path is file_path""" file_dict = {} with open(file_path, encoding = 'utf8') as fin: for line in fin: line = line.strip() txt = re.sub('([^a-zA-Z0-9\s]+)',' \\1 ',line) txt = re.sub('([\s]+)',' ',tx...
5,357,104
def get_scale(lat1, lon1, var, desired_distance, unit='miles'): """ Calculate the difference in either latitude or longitude that is equivalent to some desired distance at a given point on Earth. For example, at a specific point, how much does latitude need to change (assuming longitude is constant) to be equal ...
5,357,105
async def connect_unix(path: Union[str, PathLike]) -> UNIXSocketStream: """ Connect to the given UNIX socket. Not available on Windows. :param path: path to the socket :return: a socket stream object """ path = str(Path(path)) return await get_asynclib().connect_unix(path)
5,357,106
def isMatch(s, p): """ Perform regular simple expression matching Given an input string s and a pattern p, run regular expression matching with support for '.' and '*'. Parameters ---------- s : str The string to match. p : str The pattern to match. Returns -------...
5,357,107
def cepheid_lightcurve_advanced(band, tarr, m0, period, phaseshift, shape1, shape2, shape3, shape4, datatable=None): """ Generate a Cepheid light curve. More flexibility allowed. band: one of "B", "V", "I" tarr: times at which you want the light curve evaluated m0: mean magnitude for the light curve...
5,357,108
def view_info(): """View keybindings """ if ALWAYS_SHOW_INFO: display_info() return answer = input( "Would you like to view the info for the environment [y]/N? " ) if answer.lower() != "n": display_info()
5,357,109
def scripter(image_hash): """ Download an image geeration JavaScript file for a given image hash. """ link = script_template.format(image_hash) path = folder + "js\\" + image_hash[0] + "\\" filename = path + image_hash + '.js' if not os.path.exists(path): with lock: if not o...
5,357,110
def PrintAttrSpec(attr_spec, out): """Prints a Markdown version of the given proto message (AttrSpec). See amp.validator.AttrSpec in validator.proto for details of proto message. Args: attr_spec: The AttrSpec message. out: A list of lines to output (without newline characters), to which this fu...
5,357,111
def pairwise_point_combinations(xs, ys, anchors): """ Does an in-place addition of the four points that can be composed by combining coordinates from the two lists to the given list of anchors """ for i in xs: anchors.append((i, max(ys))) anchors.append((i, min(ys))) for i in ys:...
5,357,112
def copy(src: PathType, dst: PathType, overwrite: bool = False) -> None: """Copy a file from the source to the destination.""" src_fs = _get_filesystem(src) dst_fs = _get_filesystem(dst) if src_fs is dst_fs: src_fs.copy(src, dst, overwrite=overwrite) else: if not overwrite and file_e...
5,357,113
def app_list(context): """ Renders the app list for the admin dashboard widget. """ context["dashboard_app_list"] = admin_app_list(context["request"]) return context
5,357,114
def load_vars(executor, dirname, main_program=None, vars=None, predicate=None): """ Load variables from directory by executor. :param executor: executor that save variable :param dirname: directory path :param main_program: program. If vars is None, then filter all variables in this program whi...
5,357,115
def path_depth(path: str, depth: int = 1) -> str: """Returns the `path` up to a certain depth. Note that `depth` can be negative (such as `-x`) and will return all elements except for the last `x` components """ return path_join(path.split(CONFIG_SEPARATOR)[:depth])
5,357,116
def read_config_file(filename, preserve_order=False): """ Read and parse a configuration file. Parameters ---------- filename : str Path of configuration file Returns ------- dict Configuration dictionary """ with open(filename) as f: return parse_config...
5,357,117
def languages_list_handler(): """Get list of supported review languages (language codes from ISO 639-1). **Example Request:** .. code-block:: bash $ curl https://critiquebrainz.org/ws/1/review/languages \\ -X GET **Example Response:** .. code-block:: json { ...
5,357,118
def corpus_subdirs(path): """ pathの中のdir(txt以外)をlistにして返す """ subdirs = [] for x in listdir(path): if not x.endswith('.txt'): subdirs.append(x) return subdirs
5,357,119
def edit_string_for_tags(tags): """ Given list of ``Tag`` instances or tag strings, creates a string representation of the list suitable for editing by the user, such that submitting the given string representation back without changing it will give the same list of tags. Tag names which contai...
5,357,120
def convert_postgres_array_as_string_to_list(array_as_string: str) -> Optional[list]: """ Postgres arrays are stored in CSVs as strings. Elasticsearch is able to handle lists of items, but needs to be passed a list instead of a string. In the case of an empty array, return null. For example,...
5,357,121
def generate_prime_number(min_value=0, max_value=300): """Generates a random prime number within the range min_value to max_value Parameters ---------- min_value : int, optional The smallest possible prime number you want, by default 0 max_value : int, optional The largest possible...
5,357,122
def sort_extended_practitioner(practitioner): """ sort on date latestDate Then alpha on other practitioners :param practitioner: :return: practitioner """ uniques = [] for p in practitioner: if find_uniques(p, uniques): uniques.append(p) return uniques
5,357,123
def lti13_login_params_dict(lti13_login_params): """ Return the initial LTI 1.3 authorization request as a dict """ utils = LTIUtils() args = utils.convert_request_to_dict(lti13_login_params) return args
5,357,124
def calcShannonEnt(dataset): """ 计算数据集的熵 输入:数据集 输出:熵 """ numEntris = len(dataset) labelCounts = {} for featVec in dataset: currentLabel = featVec[-1] #每行数据中的最后一个数,即数据的决策结果 label if currentLabel not in labelCounts.keys(): labelCounts[currentLabel] = 0 l...
5,357,125
def test_task_by_build_id_option(koji_session, koji_module): """ Tasks are specified via module's ``--build-id`` option. """ task_id, build_id = koji_session koji_module._config['build-id'] = [build_id] koji_module.execute() assert_task_attributes(koji_module, task_id)
5,357,126
def get_boundaries_medians(things, lowers=[], uppers=[]): """Return the boundaries and medians of given percentage ranges. Parameters: 1. things: a list of numbers 2. lowers: lower percentage limits 3. uppers: upper percentage limits Returns: lower, median, upper """ #...
5,357,127
def getMeanBySweep(abf, markerTime1, markerTime2): """ Return the mean value between the markers for every sweep. """ assert isinstance(abf, pyabf.ABF) pointsPerSecond = abf.dataRate sweepIndex1 = pointsPerSecond * markerTime1 sweepIndex2 = pointsPerSecond * markerTime2 means = [] ...
5,357,128
def handler(event, context): """ Params: ------- event (dict): content (dict): Both params are standard lambda handler invocation params but not used within this lambda's code. Returns: ------- (string): JSON-encoded dict with top level keys for each of the possible que...
5,357,129
def add_prefix(key): """Dummy key_function for testing index code.""" return "id_" + key
5,357,130
def update_element_key(element_type, old_key, new_key): """ Update an element's key in relative tables. Args: element_type: (string) object's element type. old_key: (string) object's old key. new_key: (string) object's new key """ # The object's key has changed. element ...
5,357,131
def schedule_conv2d_nhwc_tensorcore(cfg, outs): """TOPI schedule callback""" s = te.create_schedule([x.op for x in outs]) def _callback(op): if "conv2d_nhwc_tensorcore" in op.tag: schedule_nhwc_tensorcore_cuda(cfg, s, op.output(0)) traverse_inline(s, outs[0].op, _callback) retu...
5,357,132
def simulate(config, show_progress=False): """Simulate incarceration contagion dynamics. Parameters ---------- config : Config Config object specifying simulation parameters. Returns ------- dict Dictionary specifying simulated population of agents. """ popu = init...
5,357,133
def get_event_log(file_path: str = None, use_celonis=False): """ Gets the event log data structure from the event log file. Dispatches the methods to be used by file tyoe :param use_celonis: If the attribute is set to true the event log will be retrieved from celonis :param file_path: Path to the ev...
5,357,134
def find_peak(corr, method='gaussian'): """Peak detection algorithm switch After loading the correlation window an maximum finder is invoked. The correlation window is cut down to the necessary 9 points around the maximum. Afterwards the maximum is checked not to be close to the boarder of the correlat...
5,357,135
def mesh_plot( mesh: PyEITMesh, el_pos, mstr="", figsize=(9, 6), alpha=0.5, offset_ratio=0.075, show_image=False, show_mesh=False, show_electrode=True, show_number=False, show_text=True, ): """plot mesh structure (base layout)""" # load mesh structure pts = mesh.n...
5,357,136
def atanx(curvelist): """ Take the arctangent of x values of a single curve or curves in a list. >>> curves = pydvif.read('testData.txt') >>> pydvif.atanx(curves) :param curvelist: A single curve or a list of curves :type curvelist: curve or list """ if isinstance(curvelist, list): ...
5,357,137
def binaryToString(binary): """ 从二进制字符串转为 UTF-8 字符串 """ index = 0 string = [] rec = lambda x, i: x[2:8] + (rec(x[8:], i - 1) if i > 1 else '') if x else '' fun = lambda x, i: x[i + 1:8] + rec(x[8:], i - 1) while index + 1 < len(binary): chartype = binary[index:].index('0') # 存放字...
5,357,138
def disable_log_warning(fun): """Temporarily set FTP server's logging level to ERROR.""" @functools.wraps(fun) def wrapper(self, *args, **kwargs): logger = logging.getLogger('pyftpdlib') level = logger.getEffectiveLevel() logger.setLevel(logging.ERROR) try: return...
5,357,139
def create_csv_step_logger(save_dir: pyrado.PathLike, file_name: str = "progress.csv") -> StepLogger: """ Create a step-based logger which only safes to a csv-file. :param save_dir: parent directory to save the results in (usually the algorithm's `save_dir`) :param file_name: name of the cvs-file (with...
5,357,140
def _key_chord_transition_distribution( key_chord_distribution, key_change_prob, chord_change_prob): """Transition distribution between key-chord pairs.""" mat = np.zeros([len(_KEY_CHORDS), len(_KEY_CHORDS)]) for i, key_chord_1 in enumerate(_KEY_CHORDS): key_1, chord_1 = key_chord_1 chord_index_1 = i...
5,357,141
def eigvals(a: Union[dask.array.core.Array, numpy.ndarray]): """ usage.dask: 2 usage.scipy: 2 """ ...
5,357,142
def level_set( current_price, standard_deviation, cloud, stop_mod, take_profit_mod, ): """ Calculates risk and reward levels. Should return a stop loss and take profit levels. For opening a new position. Returns a stop (in the format (StopType, offset)) and a take profit level. """...
5,357,143
def back(deque): """ returns the last elemement in the que """ if length(deque) > 0: return deque[-1] else: return None
5,357,144
def imshow(image, title=None, norm=None, colorbar_label=None, saveto=None, maximize=False): """Shows a 2D image. Args: image (np.ndarray, ndim=2): Image to be plotted. title (str, optional): Plot title. Default is None. norm (str, optional): Can be se...
5,357,145
def my_subs_helper(s): """Helper function to handle badly formed JSON stored in the database""" try: return {'time_created':s.time_created, 'json_obj':sorted(json.loads(s.json_data).iteritems(), key=operator.itemgetter(0)), 'plain_json_obj':json.dumps(json.loads(s.json_data)),'id':s.id, 'json_score_data...
5,357,146
def dynamic_features(data_dir, year, data_source, voronoi, radar_buffers, **kwargs): """ Load all dynamic features, including bird densities and velocities, environmental data, and derived features such as estimated accumulation of bird on the ground due to adverse weather. Missing data is interpolated...
5,357,147
def add_parser_arguments(verb_parser, extension): """ Add the arguments and recursive subparsers to a specific verb parser. If the extension has an `add_arguments` method it is being called with the subparser being passed as the only argument. :param verb_parser: The verb parser :param extensi...
5,357,148
def __normalize_allele_strand(snp_dfm): """ Keep all the alleles on FWD strand. If `strand` is "-", flip every base in `alleles`; otherwise do not change `alleles`. """ on_rev = (snp_dfm.loc[:, "strand"] == "-") has_alleles = (snp_dfm.loc[:, "alleles"].str.len() > 0) condition = (on_rev & h...
5,357,149
def TestNetworkListFields(): """gnt-network list-fields""" qa_utils.GenericQueryFieldsTest("gnt-network", list(query.NETWORK_FIELDS))
5,357,150
def test_init(): """Test extension initialization.""" app = Flask('testapp') app.url_map.converters['pid'] = PIDConverter ext = InvenioDeposit(app) assert 'invenio-deposit' in app.extensions app = Flask('testapp') app.url_map.converters['pid'] = PIDConverter # check that current_deposi...
5,357,151
def add_to_codetree(tword,codetree,freq=1): """ Adds one tuple-word to tree structure - one node per symbol word end in the tree characterized by node[0]>0 """ unique=0 for pos in range(len(tword)): s = tword[pos] if s not in codetree: codetree[s] = [0,{}] ...
5,357,152
def draw_watch(sw): """ Renders the stopwatch object <sw> in a digital hr:min:sec format. """ # Compute time in hours, minutes and seconds seconds = round(sw.elapsed()) time = '' hours = seconds // 3600 # Compute total hours seconds %= 3600 # Update seconds remaining minutes ...
5,357,153
def viz_samples(data, trace, num_sweeps, K, viz_interval=3, figure_size=3, title_fontsize=20, marker_size=1.0, opacity=0.3, bound=20, colors=['#AA3377','#0077BB', '#EE7733', '#009988', '#BBBBBB', '#EE3377', '#DDCC77'], save_name=None): """ visualize the samples along the sweeps """ E_tau, E_mu, E_z = tr...
5,357,154
def TA_ADXm(data, period=10, smooth=10, limit=18): """ Moving Average ADX ADX Smoothing Trend Color Change on Moving Average and ADX Cross. Use on Hourly Charts - Green UpTrend - Red DownTrend - Black Choppy No Trend Source: https://www.tradingview.com/script/owwws7dM-Moving-Average-ADX/ Parameter...
5,357,155
def remove_from_dict(obj, keys=list(), keep_keys=True): """ Prune a class or dictionary of all but keys (keep_keys=True). Prune a class or dictionary of specified keys.(keep_keys=False). """ if type(obj) == dict: items = list(obj.items()) elif isinstance(obj, dict): items = list(...
5,357,156
def unify_qso_catalog_uvqs_old(qsos): """Unifies the name of columns that are relevant for the analysis""" qsos.rename_column('RA','ra') qsos.rename_column('DEC','dec') qsos.rename_column('FUV','mag_fuv') qsos.rename_column('Z','redshift') qsos.add_column(Column(name='id',data=np.arange(len(qso...
5,357,157
def get_hash_key_name(value): """Returns a valid entity key_name that's a hash of the supplied value.""" return 'hash_' + sha1_hash(value)
5,357,158
def uniform_generator(): """ Uses linear congruential generator to generate a random variable between 0 and 1 from uniform distribution. Basic Equation for generator is X_(n+1) = (a * X_n + b) mod m where a, b and m are large numbers. However, to allow large periods between states, a sep...
5,357,159
def yaml_dumps(value, indent=2): """ YAML dumps that supports Unicode and the ``as_raw`` property of objects if available. """ return yaml.dump(value, indent=indent, allow_unicode=True, Dumper=YamlAsRawDumper)
5,357,160
def poi_remove(poi_id: int): """Removes POI record Args: poi_id: ID of the POI to be removed """ poi = POI.get_by_id(poi_id) if not poi: abort(404) poi.delete() db.session.commit() return redirect_return()
5,357,161
def plot(cmp, noffsets, nsamples, dt): """ Plots synthetic cmp gathers """ cutoff = 0.1 plt.imshow(cmp, extent=[0.5, noffsets + 0.5, dt*nsamples, 0], aspect='auto', cmap='Greys', vmin=-cutoff, vmax=cutoff, interpolation='none') # following is purely for visual ...
5,357,162
def stringToTupleOfFloats(s): """ Converts s to a tuple @param s: string @return: tuple represented by s """ ans = [] for i in s.strip("()").split(","): if i.strip() != "": if i == "null": ans.append(None) else: ans.append(float...
5,357,163
def create_training(training: TrainingSchema): """ Create an training with an TrainingSchema :param training: training data as TrainingSchema :return: http response """ endpoint_url = Config.get_api_url() + "training" job_token = Config.get_job_token() headers = { 'content-type':...
5,357,164
def plot_tracks_parameter_space( tracks, n_tracks=None, condition="Condition", save=False, palette="deep", skip_color=0, context="notebook", ): """Plot tracks in velocities-turning-angles-space""" if "Displacement" not in tracks.columns: tracks = analyze(tracks) if condi...
5,357,165
def on_connect(): """ Handle connection event and send authentication key """ send_auth()
5,357,166
def respects_language(fun): """Decorator for tasks with respect to site's current language. You can use this decorator on your tasks together with default @task decorator (remember that the task decorator must be applied last). See also the with-statement alternative :func:`respect_language`. **Ex...
5,357,167
def zero_one_window(data, axis=(0, 1, 2), ceiling_percentile=99, floor_percentile=1, floor=0, ceiling=1, channels_axis=None): """ :param data: Numpy ndarray. :param axis: :param ceiling_percentile: Percentile value of the foreground to set to the ceiling. :param floor_percentile...
5,357,168
def factorial(x): """factorial(x) -> Integral "Find x!. Raise a ValueError if x is negative or non-integral.""" if isinstance(x, float): fl = int(x) if fl != x: raise ValueError("float arguments must be integral") x = fl if x > sys.maxsize: raise OverflowErro...
5,357,169
def get_event_stderr(e): """Return the stderr field (if any) associated with the event.""" if _API_VERSION == google_v2_versions.V2ALPHA1: return e.get('details', {}).get('stderr') elif _API_VERSION == google_v2_versions.V2BETA: for event_type in ['containerStopped']: if event_type in e: ...
5,357,170
def xA(alpha, gamma, lsa, lsd, y, xp, nv): """Calculate position where the beam hits the analyzer crystal. :param alpha: the divergence angle of the neutron :param gamma: the tilt angle of the deflector :param lsa: the sample-analyzer distance :param lsd: the sample deflector distance :param y:...
5,357,171
def win2(): """ This is the configuration for the best performing model from the DPRNN paper. Training takes very long time with this configuration. """ # The model becomes very memory consuming with this small window size. # You might have to reduce the chunk size as well. batch_size = 1 ...
5,357,172
def find_recent_login(user_id: UserID) -> Optional[datetime]: """Return the time of the user's most recent login, if found.""" recent_login = db.session \ .query(DbRecentLogin) \ .filter_by(user_id=user_id) \ .one_or_none() if recent_login is None: return None return re...
5,357,173
def test_get_strategy(): """ Test rebootmgr.get_strategy without parameters """ strategy = "Reboot strategy: best-effort" salt_mock = { "cmd.run_all": MagicMock(return_value={"stdout": strategy, "retcode": 0}) } with patch.dict(rebootmgr.__salt__, salt_mock): assert rebootmgr...
5,357,174
async def async_remove_config_entry_device( hass: HomeAssistant, config_entry: ConfigEntry, device_entry: dr.DeviceEntry ) -> bool: """Remove ufp config entry from a device.""" unifi_macs = { _async_unifi_mac_from_hass(connection[1]) for connection in device_entry.connections if conn...
5,357,175
def batch_unsrt_segment_sum(data, segment_ids, num_segments): """ Performas the `tf.unsorted_segment_sum` operation batch-wise""" # create distinct segments per batch num_batches = tf.shape(segment_ids, out_type=tf.int64)[0] batch_indices = tf.range(num_batches) segment_ids_per_batch = segment_ids +...
5,357,176
def test_main(kube_config, log_to_file_config): """Test the main function of the Kubernetes Controller, and verify that it starts, display the right output and stops without issue. """ log_config, file_path = log_to_file_config() kube_config.api_endpoint = "http://my-krake-api:1234" kube_config...
5,357,177
def read_json(file_name): """Read json from file.""" with open(file_name) as f: return json.load(f)
5,357,178
def get_role(request): """Look up the "role" query parameter in the URL.""" query = request.ws_resource.split('?', 1) if len(query) == 1: raise LookupError('No query string found in URL') param = parse.parse_qs(query[1]) if 'role' not in param: raise LookupError('No role parameter found in the query s...
5,357,179
def login(username: str, password: str) -> Person: """通过用户名和密码登录智学网 Args: username (str): 用户名, 可以为准考证号, 手机号 password (str): 密码 Raises: ArgError: 参数错误 UserOrPassError: 用户名或密码错误 UserNotFoundError: 未找到用户 LoginError: 登录错误 RoleError: 账号角色未知 ...
5,357,180
def _decode_end(_fp): """Decode the end tag, which has no data in the file, returning 0. :type _fp: A binary `file object` :rtype: int """ return 0
5,357,181
def export_private_keys(s_keys, foler_name='./data', file_name='secrets.txt'): """ Exports a set of private keys to a file. Each line in the file is one key. """ if not os.path.exists(foler_name): os.makedirs(foler_name) arch = open(os.path.join(foler_name, file_name), 'w') for k...
5,357,182
def raise_complete_async() -> NoReturn: """Raise an error that says the activity will be completed asynchronously. """ raise _CompleteAsyncError()
5,357,183
def make_dqn_agent(q_agent_type, arch, n_actions, lr=2.5e-4, noisy_net_sigma=None, buffer_length=10 ** 6, final_epsilon=0.01, final_exploration_frames=10 ** 6, ...
5,357,184
def build_consensus_from_haplotypes(haplotypes): """ # ======================================================================== BUILD CONSENSUS FROM HAPLOTYPES PURPOSE ------- Builds a consensus from a list of Haplotype objects. INPUT ----- [HAPLOTYPE LIST] [haplotypes] ...
5,357,185
def resizeWindow(win, w, h, timeout=2.0): """Resize a window and wait until it has the correct size. This is required for unit testing on some platforms that do not guarantee immediate response from the windowing system. """ QtGui.QApplication.processEvents() # Sometimes the window size wil...
5,357,186
def convert_data_for_rotation_averaging( wTi_list: List[Pose3], i2Ti1_dict: Dict[Tuple[int, int], Pose3] ) -> Tuple[Dict[Tuple[int, int], Rot3], List[Rot3]]: """Converts the poses to inputs and expected outputs for a rotation averaging algorithm. Args: wTi_list: List of global poses. i2Ti1_...
5,357,187
def all_arrays_to_gpu(f): """Decorator to copy all the numpy arrays to the gpu before function invokation""" def inner(*args, **kwargs): args = list(args) for i in range(len(args)): if isinstance(args[i], np.ndarray): args[i] = to_gpu(args[i]) return f(*a...
5,357,188
def fatal(*tokens: Token, exit_code: int = 1, **kwargs: Any) -> None: """Print an error message and exit the program :param tokens: list of `ui` constants or strings, like ``(cli_ui.red, "this is a fatal error")`` :param exit_code: value of the exit code (default: 1) """ error(*...
5,357,189
def create_intersect_mask(num_v, max_v): """ Creates intersect mask as needed by polygon_intersection_new in batch_poly_utils (for a single example) """ intersect_mask = np.zeros((max_v, max_v), dtype=np.float32) for i in range(num_v - 2): for j in range((i + 2) % num_v, num_v - int(i =...
5,357,190
def gdi_abuse_tagwnd_technique_bitmap(): """ Technique to be used on Win 10 v1703 or earlier. Locate the pvscan0 address with the help of tagWND structures @return: pvscan0 address of the manager and worker bitmap and the handles """ window_address = alloc_free_windows(0) manager_bitmap_handle = create_bitmap(0x1...
5,357,191
def main(): """CLI entrypoint""" parser = Parser( prog='unwad', description='Default action is to convert files to png format and extract to xdir.', epilog='example: unwad gfx.wad -d ./out => extract all files to ./out' ) parser.add_argument( 'file', metavar='fi...
5,357,192
def check_stop() -> list: """Checks for entries in the stopper table in base db. Returns: list: Returns the flag, caller from the stopper table. """ with db.connection: cursor = db.connection.cursor() flag = cursor.execute("SELECT flag, caller FROM stopper").fetchone() ...
5,357,193
def initialize_debugging(flags, mode, callback, filename): """Initializes the logging system. :param flags: The debug output control flags. :type flags: DEBUG_FLAGS :param mode: The output type. :type mode: DEBUG_MODE :param callback: Debugging callback, if applicable. :type callback:...
5,357,194
def open_controller(filename,ncircuits,use_sql): """ starts stat gathering thread """ s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.connect((control_host,control_port)) c = PathSupport.Connection(s) c.authenticate(control_pass) # also launches thread... c.debug(file(filename+".log", "w", bufferin...
5,357,195
def test_environment_python_version_multi_digit(tmpdir: py.path.local) -> None: """ Make sure the constructor for env.Environment can handle multi-digit minor versions of Python to ensure compatibility with Python 3.10+. """ with patch("sys.version_info", new=(3, 123, 0)): # python version i...
5,357,196
def get_camelcase_name_chunks(name): """ Given a name, get its parts. E.g: maxCount -> ["max", "count"] """ out = [] out_str = "" for c in name: if c.isupper(): if out_str: out.append(out_str) out_str = c.lower() else: out_s...
5,357,197
def _GetBuildBotUrl(builder_host, builder_port): """Gets build bot URL for fetching build info. Bisect builder bots are hosted on tryserver.chromium.perf, though we cannot access this tryserver using host and port number directly, so we use another tryserver URL for the perf tryserver. Args: builder_hos...
5,357,198
def case_two_args_positional_callable_first(replace_by_foo): """ Tests the decorator with one positional argument @my_decorator(goo) """ return replace_by_foo(goo, 'hello'), goo
5,357,199