content
stringlengths
22
815k
id
int64
0
4.91M
def test_extract_data_from_csv_stream(requests_mock): """ Scenario: Extract data out of a downloaded csv file. Given: - User has provided valid credentials. When: - A fetch command is called and there is a CSV file reference in the response. Then: -...
52,900
def test_model_generate(): """Test calling model prediction method.""" p = GenerationModel.generate('ともだち') assert p.output == '友達\n友だち\nトモダチ\n友达'
52,901
def _evaluateMockedResponse(table, cmd_dict, success=True, is_save=True): """ Evaluates if the response from a mock is as expected. :param Table table: :param dict cmd_dict: :param bool success: value of success :param bool is_save: value of is_save """ response, returned_is_save = \ table.p...
52,902
def plot_resource_utilization(filename, subplt, ylim=None, pattern=None): """ :param filename: resource_log file :param subplt: pyplot axes object :param ylim: y-axes range, defaults to [0,1.05] :param pattern: only plot resources whose name matches the pattern (in regular expression), ...
52,903
def test_update_tri_data(): """Tests the upadte_tri_data function """ three_vols = df.DagmcFile(test_env['three_vols']) surf = three_vols.entityset_ranges['surfaces'][0] three_vols_query = dq.DagmcQuery(three_vols, surf) three_vols_query.calc_triangle_aspect_ratio() exp_tar = (10*10*10*np.sq...
52,904
def projection_simplex_sort(v, z=1): """ Bounds control field to agent's magnetic field budget. ... Parameters ---------- v : numpy.array Control field allocation of the agent. z : float Magnetic field budget (default 1.0) """ n_features = v.shape[0] v = np...
52,905
def _get_synthetic_digits_data(): """Returns a dictionary suitable for `tf.data.Dataset.from_tensor_slices`. Returns: A dictionary that matches the structure of the data produced by `tff.simulation.datasets.emnist.load_data`, with keys (in lexicographic order) `label` and `pixels`. """ data = _SYNT...
52,906
def all_subclasses(cls): """Returns recursively-generated list of all children classes inheriting from given `cls`.""" return set(cls.__subclasses__()).union([s for c in cls.__subclasses__() for s in all_subclasses(c)])
52,907
def Main(argv): """Set a mask to disable specific ports on a core switch.""" try: argv = FLAGS(argv) except gflags.FlagsError, e: sys.stderr.write('\nError: %s\n\nUsage: %s ARGS\n%s\n' % (e, argv[0], FLAGS)) sys.exit(1) disable_port_mask = 0 for port in FLAGS.disable_ports.sp...
52,908
def main(): """Pull Message and Process.""" region_name = os.environ["REGION"] queue_name = os.environ["QUEUE_NAME"] sqs = boto3.resource("sqs", region_name=region_name) # Get the queue try: queue = sqs.get_queue_by_name(QueueName=queue_name) except ClientError: logger.warn...
52,909
def get_sample_input01() -> Tuple[int, np.ndarray]: """ A single input vector sample of the "Necessary" category. """ label = 0 feature_vector = np.array([[0., 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0...
52,910
def calc_pose_instances( pose_heatmaps, pose_localmax, pose_embed_maps, min_embed_sep_between, max_embed_sep_within, max_inst_dist): """ Given the input parameters for a single image/frame, return a list of PoseInstance objects Parameters: pose_h...
52,911
def cap_rating(flight_phase, short_period_cap, short_period_damping): """ Give a rating of the short period mode flight quality level: Level1 Level2 or Level3 and 4 according to MIL-STD-1797A Args: flight_phase (string) : 'A', 'B' or 'C' short_period_cap (float): Control Anticipation ...
52,912
def set_immd(*args): """ set_immd(ea) -> bool Set 'has immediate operand' flag. Returns true if the 'FF_IMMD' bit was not set and now is set @param ea (C++: ea_t) """ return _ida_bytes.set_immd(*args)
52,913
def place_varga(A, B, p, dtime=False, alpha=None): """Place closed loop eigenvalues K = place_varga(A, B, p, dtime=False, alpha=None) Required Parameters ---------- A : 2D array_like Dynamics matrix B : 2D array_like Input matrix p : 1D array_like Desired eigenvalue ...
52,914
def update_all_podfile_dirs(directory, blacklist): """Run `pod update` in all directories containing a Podfile. Args: directory: The directory to use. blacklist: A set of directories that cannot appear in the paths of podfiles. """ dirs = find_matching_dirs(directory, 'Podfile', blacklist) for d in d...
52,915
def ObjectSecurity(*args,**kwargs): # real signature unknown """ Provides the ability to control access to objects without direct manipulation of Access Control Lists (ACLs). This class is the abstract base class for the System.Security.AccessControl.CommonObjectSecurity and System.Security.AccessControl.DirectoryObj...
52,916
def kToc(k, nu = 5.0, xF = 0.2, xS = 0.8, xG = 0.0 ): """ kToc will convert a k-eigenvalue to a c-eigenvalue given the cross sections for the problem. """ xA = xG + xF xT = xA + xS return (nu*xF/k + xS)/xT
52,917
def test_atomic_unsigned_byte_min_exclusive_nistxml_sv_iv_atomic_unsigned_byte_min_exclusive_1_4(mode, save_output, output_format): """ Type atomic/unsignedByte is restricted by facet minExclusive with value 0. """ assert_bindings( schema="nistData/atomic/unsignedByte/Schema+Instance/NISTSch...
52,918
def handle_http_err(ret: requests.Response, event: str) -> None: """处理 HTTP 异常 按照一个通用流程检查一个响应是否正确 如果不正确,会抛出异常 :param ret: 响应 :param event: 事件,这个请求做了什么事情(比如: '登录' ) :return: None """ if ret.status_code != 200: err_msg = f'{event}时服务端返回异常状态码:[{ret.status_code}] {ret....
52,919
def _build_parameters(statistics, gcs_data_dir): """Generate model params based on the stats generated from the data-set.""" # Do binning on sequence lengths bins = np.arange(0, 1700, 100) # Choose maximum seq length based on number which covers 50% of seq lengths threshold = statistics['num_data_p...
52,920
def analysis(sliceno, prepare_res, params): """ reading complete file, writing to this slice only""" separator, filename, _, labels, dw = prepare_res if options.hashlabel: hash_ix = labels.index(options.hashlabel) else: hash_ix = -1 copied_lines = 0 n_labels = len(labels) res_num = ffi.new('uint64_t [2]'...
52,921
def stream( pipeline: Pipeline, source: Path, labels: List[str], chunk: float = 30.0, randomize: bool = False, ) -> Iterable[Dict]: """Stream for `pyannote.audio` recipe Applies pretrained pipeline and sends the results for manual correction Parameters ---------- pipeline : Pip...
52,922
def leave(): """ Leave the current DHT. This request should only retrn the DHT this node is leaving has stabilized and this node is a standalone node now; noop is not part of any DHT. """ raise NotImplemented
52,923
def construct_generic_B(n_states, n_control): """ Generates a fully controllable transition likelihood array, where each action (control state) corresponds to a move to the n-th state from any other state, for each control factor """ num_factors = len(n_states) if num_factors == 1: ...
52,924
def parse( in_data: Union[str, PathLike, TextIO], input_linesep: Optional[str] = None, max_size: int = _MAX_SIZE, ) -> dict: """Parse a VEP plain text statistics file into a dictionary. :param in_data: Input VEP statistics contents. :param input_linesep: Name of the operating system used for de...
52,925
def prepare_training_data(): """Save a boolean mask of each DICOM scan at ../assets/segmented_lung_patient_{LIDC-ID}.npy that indicates whether a pixel was annotate by an expert as at least intermediate malicious or not. """ INTERMEDIATE_MALICIOUS = 3 ASSETS_DIR = Config.SEGMENT_ASSETS_DIR IMAGE...
52,926
def analysis_to_subword_dicts(ana): """ Returns a list of list of dicts. Each list element is an analysis. For each analysis, there is a list of subwords. Each dict contains an Omorfi analysis """ return map(pairs_to_dict, chunk_subwords(analysis_to_pairs(ana)))
52,927
def collect_storage_system_statistics(storage_system): """ Collects and sends statistics of a single storage system to graphite. :param storage_system: The JSON object of a storage_system """ try: session = get_session() graphite_package = [] storage_id = storage_system['id']...
52,928
def create_directory_content_output(share_name: str, raw_response: dict, directory_path: str = "") -> dict: """ Create XSOAR context output for list directory command. Args: share_name (str): Share name. raw_response (dict): Request raw response. directory_path (str): Source director...
52,929
def circle_area(r): """Calculates the area of a trapezium using the formula: area = \u03C0(radius squared) Parameters ---------- r: int or float The radius in the equation. Returns ------- Float \u03C0 * (r**2) Raises ------ ValueError If r:: ...
52,930
def test_del(): """Test deleting a key, value pair from BSTMap.""" init = [] for _ in range(1000): n = random.randrange(1, 10000) init.append((n, n)) tree = BSTMap(tuple(init)) for k, v in set(init): del tree[k] assert tree._isBST() assert k not in tree
52,931
def test_get_config(var, func, value, default_is_none): """Test helper functon to get different configuration parameters from the respective environment variables. """ # -- Setup ---------------------------------------------------------------- if var in os.environ: del os.environ[var] # ...
52,932
def split_to_batches(graphs, labels, size): """ split the same size graphs array to batches of specified size last batch is in size num_of_graphs_this_size % size :param graphs: array of arrays of same size graphs :param labels: the corresponding labels of the graphs :param size: batch size ...
52,933
def rawGen(model, gram): """ Generates a raw sequence from the model using ancestral sampling """ #model into eval mode model.eval() C=np.zeros((batch_size,8)) S=np.tile(gram,(batch_size,1)) #create a empty metal code for the sequence. C=torch.from_numpy(C).type(torch.FloatT...
52,934
async def test_feed_manager_with_status_callback(aresponses, event_loop): """Test the feed manager.""" aresponses.add( "test.url", "/testpath", "get", aresponses.Response(text=load_fixture("generic_feed_1.xml"), status=200), ) async with aiohttp.ClientSession(loop=event_...
52,935
def _get_attribute_accesses_for_starred(node, variable): """ ..code:: python Starred(expr value, expr_context ctx) """ assert isinstance(node.ctx, ast.Load) yield from _get_attribute_accesses(node.value, variable)
52,936
def showLines(*args, **kwargs): """ Show 1-D data using :func:`~matplotlib.axes.Axes.plot`. :arg x: (optional) x coordinates. *x* can be an 1-D array or a 2-D matrix of column vectors. :type x: :class:`~numpy.ndarray` :arg y: data array. *y* can be an 1-D array or a 2-D matrix of...
52,937
def hline_to_curve( ax, y, xdata, ydata, dot=False, line_kwargs={}, scatter_kwargs={}, **kwargs ): """[plots a vertical line from the x axis to the curve at location x] Arguments: ax {[axarray]} -- [ax to plot on] x {[float]} -- [x value to plot on ] curve {[np.array]} -- [array...
52,938
def test_character_arrays_dont_need_null_termination(binary): """ Test that a C string converted to Python doesn't need to be null terminated. I make this rather heavy assumption that it's ok in the docs. If this fails then a lot of examples are wrong. """ char = ctypes.c_char if binary else ct...
52,939
def build_response(status, message): # type: (DownloadStatus, str) -> str """ function to build a response as json string """ return json.dumps({'status': status, 'message': message})
52,940
def generate_config(ctx): """ Generates a sample gitlint config file. """ path = click.prompt('Please specify a location for the sample gitlint config file', default=DEFAULT_CONFIG_FILES[0]) path = os.path.realpath(path) dir_name = os.path.dirname(path) if not os.path.exists(dir_name): click...
52,941
def loads_json(fid, **kwargs): """ Loads a JSON file and returns it as a dict. :param path: String or another object that is accepted by json.loads :param kwargs: See ``json.dump()``. :return: Content of the JSON file. """ assert isinstance(fid, str), fid return json.loads(fid, **kwargs)
52,942
def cli_parse_args(args=None, namespace=None): """ CLI (Command Line Interface) parsing based on ``ArgumentParser.parse_args`` from the ``argparse`` module. """ # CLI interface description parser = argparse.ArgumentParser( description=__doc__, epilog="by Danilo J. S. Bellini", formatter_class=ar...
52,943
def storeOutputToExcel(storeOutput, exceldir): """Create file and add a worksheet or overwrite existing """ # https://pypi.python.org/pypi/XlsxWriter workbook = xlsxwriter.Workbook(os.path.join(exceldir,'storeOutputTemplate.xlsx')) worksheet = workbook.add_worksheet() # set column width work...
52,944
def get_rad_list(H_MR, H_OR): """主たる居室、その他の居室という単位で設定された放熱機器を暖房区画ごとの配列に変換 Args: H_MR(dict): 暖房機器の仕様 H_OR(dict): 暖房機器の仕様 Returns: list: 放熱機器の暖房区画ごとの配列 """ # 暖房区画i=1-5に対応した放熱器のリストを作成 rad_list = [None, None, None, None, None] # 放熱系の種類 rad_types = get_rad_type_list() ...
52,945
def GetArrayElement(tag, array_id, idx): """ Get value of array element. @param tag: Tag of array, specifies one of two array types: AR_LONG, AR_STR @param array_id: The array ID. @param idx: Index of an element. @return: Value of the specified array element. Note that this functi...
52,946
def shutdown_pi(): """ Shuts down the Pi system """ subprocess.Popen(["sudo", "shutdown", "-h", "now"]) return True
52,947
def init_lars_optimizer(current_epoch, params): """Initialize the LARS Optimizer.""" learning_rate = poly_rate_schedule(current_epoch, params) optimizer = tf.contrib.opt.LARSOptimizer( learning_rate, momentum=params['momentum'], weight_decay=params['weight_decay'], skip_list=['batch_norma...
52,948
def suffix(): """Generate a random string of length 4""" alph = "abcdefghijklmnopqrstuvwxyz" return "-".join([time.strftime("%Y-%m-%d-%H%M%S"), "".join(random.sample(alph, 4))])
52,949
def augment_data(spectrogram: np.ndarray) -> list: """ Augment the given data. :param spectrogram: Data to augment :return: Augmented data """ result = [ mask_spectrogram(spectrogram, n_freq_masks=1, n_time_masks=0), # mask_spectrogram(spectrogram, n_freq_masks=3, n_time_...
52,950
def load_train(root_path, dir, batch_size, phase): """ Load data for train set """ transform_dict = { 'src': transforms.Compose( [transforms.RandomResizedCrop(224), transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.Normalize(m...
52,951
def reduceModel(model, atoms, select): """Return reduced NMA model. Reduces a :class:`.NMA` model to a subset of *atoms* matching *select*. This function behaves differently depending on the type of the *model* argument. For :class:`.ANM` and :class:`.GNM` or other :class:`.NMA` models, force constan...
52,952
def executable(s): """Attempts to use the "ex" entry in LS_COLORS, falling back to green""" return __ls_color(s, 'ex', term.green)
52,953
def put_target_state(): """SDP target State. Sets the target state """ sdp_state = SDPState() errval, errdict = _check_status(sdp_state) if errval == "error": LOG.debug(errdict['reason']) rdict = dict( current_state="unknown", last_updated="unknown", ...
52,954
def _skew_circulant_multiply(c, x, f_method='std'): """Multiply a skew-circulant matrix by a vector. Runs in O(n log n) time. See algorithm S7 in Sukhoy & Stoytchev 2019 (full reference in README). Args: c (np.ndarray): first column of skew-circulant matrix G x (np.ndarray...
52,955
def _apply_temp_conv(var, var_unit, dest_unit): """Return the variable converted to different units using a temperature conversion algorithm. Args: var (:class:`xarray.DataArray` or :class:`numpy.ndarray`): A variable. var_unit (:obj:`str`): The variable's current units. ...
52,956
def read_all_labels(fp_folder: str = "./rs19_val/jsons/rs19_val") -> List[dict]: """Loads the data of all JSON files from a provided folder and returns the contents in a list. :param fp_folder: Filepath to the folder containing JSON files. :dtype fp_folder: str """ return [read_json(os.path.join(fp...
52,957
def epidemic_history() -> pd.DataFrame: """ 该接口最好用代理速度比较快 https://github.com/canghailan/Wuhan-2019-nCoV 2019-12-01开始 :return: :rtype: pandas.DataFrame """ url = "https://raw.githubusercontent.com/canghailan/Wuhan-2019-nCoV/master/Wuhan-2019-nCoV.json" r = requests.get(url) data_j...
52,958
def main(*, data, d): """entrypoint function for this component Usage example: >>> main( ... data = pd.Series( ... [1.2, 7.2, 2.8, 4.8, 10.8], ... index = [2, 3, 5, 6, 9] ... ), ... d = 2 ... )["interpolation"] 2 1.2 4 5.0 6 4.8 8...
52,959
def derivative ( fun , x , h = 0 , I = 2 , err = False , args = () , kwargs = {} ) : """Calculate the first derivative for the function # @code # >>> fun = lambda x : x*x # >>> print derivative ( fun , x = 1 ) - see R. De Levie, ``An improved numerical approximation for the first derivative'...
52,960
def test_igw_filter_by_attachment_state_boto3(): """ internet gateway filter by attachment state """ ec2 = boto3.resource("ec2", "us-west-1") client = boto3.client("ec2", "us-west-1") igw1 = ec2.create_internet_gateway() igw2 = ec2.create_internet_gateway() vpc = ec2.create_vpc(CidrBlock=VPC_CI...
52,961
def get_statevector(result) -> np.ndarray: """ Creates a statevector out of a simulation result. Used when the simulator does not give a statevector. Parameters ---------- result: the result from the simulation. Returns ------- ndarray: the statevector correspondin...
52,962
def weighting(distance): """Weighting function for pyresample.""" weight = 1 / distance**2 return weight
52,963
def absolute_path(path): """ Returns the absolute path for the given path and normalizes the path. :param path: Path for which the absolute normalized path will be found. :returns: Absolute normalized path. """ return os.path.abspath(os.path.normpath(path))
52,964
def weighted(*values): """ Calculates the uncertainty weighted average of the provided values, where each value is a ValueUncertainty instance. For mathematical formulation of the weighted average see "An Introduction to Error Analysis, 2nd Edition" by John R. Taylor, Chapter 7.2. :param values...
52,965
def average_precision_at_k(targets, ranked_predictions, k=None): """Computes AP@k given targets and ranked predictions.""" if k: ranked_predictions = ranked_predictions[:k] score = 0.0 hits = 0.0 for i, pred in enumerate(ranked_predictions): if pred in targets and pred not in ranked_...
52,966
def on_intent(intent_request, session): """ Called when the user specifies an intent for this skill. Main logic point to determine what action to take based on users request. """ print("on_intent requestId=" + intent_request['requestId'] + ", sessionId=" + session['sessionId']) #...
52,967
def bounceForward(sprite, partner, game): """ The partner sprite pushed, so if possible move in the opposite direction. """ sprite.physics.active_movement(sprite, unit_vector(partner.lastdirection)) # game._updateCollisionDict(sprite)
52,968
def check_index_by_doc(es_alias, db, doc_id, interval=10): """ Given a doc, update it in couch (meaningless save that updates rev) and check to make sure that ES will eventually see it after some arbitrary delay """ target_rev = None try: couch_doc = db.open_doc(doc_id if doc_id else "")...
52,969
def formatEpisodeNumbers(episodenumbers): """Format episode number(s) into string, using configured values """ if len(episodenumbers) == 1: epno = Config['episode_single'] % episodenumbers[0] else: epno = Config['episode_separator'].join( Config['episode_single'] % x for x in...
52,970
def _PureShape(shape): """Make sure shape does not contain int tensors by calling int().""" return [int(x) for x in shape]
52,971
def get_invalid_mirror_bunny_entrances(): """ Entrances that can't be superbunny-mirrored into. """ yield 'Skull Woods Final Section' yield 'Hype Cave' yield 'Bonk Fairy (Dark)' yield 'Thieves Town' yield 'Dark World Hammer Peg Cave' yield 'Brewery' yield 'Hookshot Cave' yiel...
52,972
def sum(pda: pdarray) -> np.float64: """ Return the sum of all elements in the array. Parameters ---------- pda : pdarray Values for which to calculate the sum Returns ------- np.float64 The sum of all elements in the array Raises ------ TypeError R...
52,973
def add_ui_containerized_action(sub_parser: ArgumentParser) -> ArgumentParser: """Populates the sub parser with the container launch kernel arguments.""" sub_parser.add_argument( '-d', '--directory', dest='notebooks_directory', default='.', help=textwrap.dedent( """ ...
52,974
def _tf_cleanup_all( triples_groups: Sequence[MappedTriples], *, random_state: TorchRandomHint = None, ) -> Sequence[MappedTriples]: """Cleanup a list of triples array with respect to the first array.""" reference, *others = triples_groups rv = [] for other in others: if random_state...
52,975
def apply_pdbfixer(input_file_path, output_file_path, directives): """ Apply PDBFixer to make changes to the specified molecule. Single mutants are supported in the form "T315I" Double mutants are supported in the form "L858R/T790M" The string "WT" still pushes the molecule through PDBFixer, but m...
52,976
def char_to_number(value: str, required_type: str) -> str: """Converts the string representation of a number (int or float) to a number Args: value (str): String representation of a number required_type (str): Output type desired (bigint or double) Raises: Exception: The conversion...
52,977
async def test_import_aborts_if_configured(hass): """Test config import doesn't re-import unnecessarily.""" with patch( "python_awair.AwairClient.query", side_effect=[USER_FIXTURE, DEVICES_FIXTURE] ), patch( "homeassistant.components.awair.sensor.async_setup_entry", return_value=Tru...
52,978
def get_PHM08Data(save=False): """ Function is to load PHM 2008 challenge dataset """ if save == False: return np.load("./PHM08/processed_data/phm_training_data.npy"), np.load("./PHM08/processed_data/phm_testing_data.npy"), np.load( "./PHM08/processed_data/phm_original_test...
52,979
def _validate_index_string(index_string: str) -> bool: """ Handle validation of index string from the argument. a string should be in format 't{%d}' or 'r{%d}' or 'd{%d}' Parameters: index_string: the string we want to validate Returns: a boolean indicating whether the index st...
52,980
def _restart_debugging(interactive=True): """ Args: interactive: Returns: """ global tb_pid #Kill existing TB proc = subprocess.Popen(["kill", str(tb_pid)]) proc.wait() debugger_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) debugger_socket.bind(('',0)) ...
52,981
def get_r_GU(r_HPU): """1時間平均のガスユニットの暖房出力分担率 (15) Args: r_HPU(ndarray): 1時間平均のヒートポンプユニット暖房出力分担率 (-) Returns: ndarray: 1時間平均のガスユニットの暖房出力分担率 """ return 1 - r_HPU
52,982
def control_thread(sess): """a thread used to control the vehicles""" while True: imgs = [] other_states = [] for camera, egopilot in zip(cameras, egopilots): img = camera.get() raw_img = img[FLAGS.img_height//2:, FLAGS.img_width//5:4*FLAGS.img_width//5, :] ## c...
52,983
def onset_by_rain(date, df, window=5, rain_threshold=5): """ Finds true storm onset by finding the first date around the landfall that rain exceeds a threshold Args: date: the date to look around df: df with a date and rain column window: number of days around date to find max (tota...
52,984
def get_most_read(key): """ Gets the most read news from a given page (national or international) :param key: the key of the source page (e.g: g1, localDF, WP, etc.) :return: a list with the most read news from the page """ # Check if the News Source is national or internacional if key in n...
52,985
def trapezoid_list(area, rotate_and_mirror=True): """Returns a list of possible trapezoids (various height/width ratios, various orientations) with approximately the requested area. We support two kinds of trapezoids: w1 w2 |----\ /--\ h | \ and h / ...
52,986
async def generate_tarot_card( id_: int, resources: BaseTarotResource, direction: int = 1, *, need_desc: bool = True, need_upright: bool = True, need_reversed: bool = True, width: int = 1024) -> Result.TextResult: """ 绘制塔罗卡片 :param id_: 牌id ...
52,987
def work_in(dir_ext): """Execute a function in a different directory""" def func_decorator(func): @wraps(func) def wrapped_function(*args, **kwargs): here = os.getcwd() dir_path = os.path.join(here, dir_ext) if not os.path.isdir(dir_path): ...
52,988
def login(request): """ Log user in using Github OAuth""" # Create keys if not yet there! if not request.session.get('github_token'): request.session['github_token'] = None # To keep API token request.session['github_info'] = None # To keep user infor (e.g. name, avatar url) # For Se...
52,989
def counter(iterable): """ Return a dict of counts for items in iterable. """ counts = defaultdict(int) for item in iterable: counts[item] += 1 return counts
52,990
async def memes(ctx): """Get the dankest memes Reddit has to offer.""" async with aiohttp.ClientSession() as session: url = "https://meme-api.herokuapp.com/gimme" async with session.get(url) as response: response = await response.json() embed = discord.Embed(title=response['t...
52,991
def meets_criteria(num): """boolean test for meeting the password criteria. + Two adjacent digits are the same (like 22 in 122345). + Going from left to right, the digits never decrease; they only ever increase or stay the same (like 111123 or 135679) Arg: num: number to be tested ...
52,992
def return_loop( onset_loc, envelope, function_time_thresh, hist_threshold, hist_time_samples, nperseg=512, ): """ This function is used by the calculate_onsets method. This looks backwards in time from the attack time and attempts to find the exact onset point by identifying the p...
52,993
def hostAppMat2numpy(hostmat): """ This will return a matrice in a numpy.array format This function can also be used when theire is LeftHand / RightHand conflict. ie a numpy matrice is a regular 4x4 matrice (3x3rot+trans) @type hostmat: hostObject Matrice @param hostmat: the hostObjec...
52,994
def filter_tree(tree: BeautifulSoup): """Filters page numbers, tables and suchlike.""" for pn in tree.find_all('span', {'class': 'pageno'}): pn.decompose() for pn in tree.find_all('span', {'class': 'pagenum'}): pn.decompose() for table in tree.find_all('table'): table.decompose()
52,995
def integrate_entropy(data, scaling): """Integrates entropy data with scaling factor along last axis Args: data (np.ndarray): Entropy data scaling (float): scaling factor from dT, amplitude, dx Returns: np.ndarray: Integrated entropy units of Kb with same shape as original array ...
52,996
def test_get_ipv6_address_error(monkeypatch): """Test get own ipv6 address when it's not possible.""" class Socket(MockSocket): def getsockname(self, *args, **kwargs): raise Exception monkeypatch.setattr(socket, "socket", Socket) assert not get_internal_ipv6_address()
52,997
def test_tanh(): """Test the tanh function""" fn = Tanh() nose.tools.assert_is_instance(fn, Function) nose.tools.assert_is_instance(fn, Tanh) nose.tools.assert_equals(fn.compute(0), 0) nose.tools.assert_equals(fn.compute_derivative(0), 1)
52,998
def parse_old_arhive_file_name(file_name): """Retrieves information from the given old archive file name and returns it in the following form: function, dimension, instance :param file_name: old archive file name in form f[f1]-[f2]_i[i1]-[i2]_[d]D.txt """ split = os.path.basename(file_name).sp...
52,999