content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from datetime import datetime def is_utc_today(utc): """ Returns true if the UTC is today :param utc: :return: """ current_time = datetime.datetime.utcnow() day_start = current_time - datetime.timedelta(hours=current_time.hour, minutes=current_time.minute, ...
f707b44ce9a741a4d126e1e55a33c7e78cb1159e
21,600
def test_run_completed(mock_job, mock_queue, mock_driver): """Test run function for a successful run.""" # Setup def mock_render(*args, **kwargs): return class MockStorage: def __init__(self): pass def load(self, *args, **kwargs): return 'blah' ...
bd4660738e952cf5da24dbd2bc22cd0876716b66
21,601
async def get_telegram_id(phone_number, user_mode=False): """ Tries to get a telegram ID for the passed in phone number. """ async with start_bot_client() as bot: if user_mode: # just leaving this code here in case it proves useful. # It only works if you use a user, not ...
e0a0c8d4bcd305b23f831297880b0ead30eeb94a
21,602
def QuadRemesh(thisMesh, parameters, multiple=False): """ Quad remesh this mesh. """ url = "rhino/geometry/mesh/quadremesh-mesh_quadremeshparameters" if multiple: url += "?multiple=true" args = [thisMesh, parameters] if multiple: args = list(zip(thisMesh, parameters)) response = Util.Com...
f3068768ea62b8960fe11b736a6fcaea722d105d
21,603
def part_2_helper(): """PART TWO This simply runs the script multiple times and multiplies the results together """ slope_1 = sled_down_hill(1, 1) slope_2 = sled_down_hill(1, 3) slope_3 = sled_down_hill(1, 5) slope_4 = sled_down_hill(1, 7) slope_5 = sled_down_hill(2, 1) return slope...
2a62fa6acde73a8a5c1e59a0403cf6c067baf57a
21,604
def read_and_download_profile_information(id): """ linke: https://developer.apple.com/documentation/appstoreconnectapi/read_and_download_profile_information :param id: bundle_id :return: 请求结果 """ data = { "fields[certificates]": "certificateType", "fields[devices]": "platform", ...
01ba704a352df28d20d944baecf108fc0fb44ad1
21,605
def get_config(node): """Get the BIOS configuration. The BIOS settings look like:: {'EnumAttrib': {'name': 'EnumAttrib', 'current_value': 'Value', 'pending_value': 'New Value', # could also be None 'read_only': False, ...
ca9467800fae3939f83e964c29d564cc306d4b1e
21,606
import matplotlib.pyplot as plt import matplotlib.lines as mlines import seaborn as sns def plot_neural_reconstruction_traces( traces_ae, traces_neural, save_file=None, xtick_locs=None, frame_rate=None, format='png'): """Plot ae latents and their neural reconstructions. Parameters ---------- ...
00e864e8121e2240269b898f2fb30606ad4d7195
21,607
def get_only_metrics(results): """Turn dictionary of results into a list of metrics""" metrics_names = ["test/f1", "test/precision", "test/recall", "test/loss"] metrics = [results[name] for name in metrics_names] return metrics
1b0e5bb8771fdc44dcd22ff9cdb174f77205eadd
21,608
def max_sub_array(nums): """ Returns the max subarray of the given list of numbers. Returns 0 if nums is None or an empty list. Time Complexity: ? Space Complexity: ? """ if nums == None: return 0 if len(nums) == 0: return 0 pass
0575524e2e38a215867ce51c08828fd47a230e97
21,609
import re def find_tags_containing(project, commit): """Find all tags containing the given commit. Returns the full list and a condensed list (excluding tags 'after' other tags in the list).""" tags = run_list_command(['git', 'tag', '--contains', commit], project) # The packaging projects had a different...
792bfd8c6972e818d36343723345ee1152cb66ec
21,610
def setup_nupack_input(**kargs): """ Returns the list of tokens specifying the command to be run in the pipe, and the command-line input to be given to NUPACK. Note that individual functions below may modify args or cmd_input depending on their specific usage specification. """ # Set up terms of command-line ...
6dc26413bb2eab4b94c343770e6110ba2d012a41
21,611
from typing import List from typing import Union from typing import Literal def rebuild_current_distribution( fields: np.ndarray, ics: np.ndarray, jj_size: float, current_pattern: List[Union[Literal["f"], str]], sweep_invariants: List[Union[Literal["offset"], Literal["field_to_k"]]] = [ "o...
66e81639e3ff3995c4a6b6bbe2f361071a6b51b1
21,612
def get_LCA(index, item1, item2): """Get lowest commmon ancestor (including themselves)""" # get parent list from if item1 == item2: return item1 try: return LCA_CACHE[index][item1 + item2] except KeyError: pass parent1 = ATT_TREES[index][item1].parent[:] parent2 = AT...
22e65163cd1c32ac8bd20dadc3aa69c208adb540
21,613
def select_workspace_access(cursor, workspace_id): """ワークスペースアクセス情報取得 Args: cursor (mysql.connector.cursor): カーソル workspace_id (int): ワークスペースID Returns: dict: select結果 """ # select実行 cursor.execute('SELECT * FROM workspace_access WHERE workspace_id = %(workspace_id)s', ...
4cf1e0dd4a1232bd5a00d49d952e3bfb98e189c5
21,614
def pkcs7_unpad(data): """ Remove the padding bytes that were added at point of encryption. Implementation copied from pyaspora: https://github.com/mjnovice/pyaspora/blob/master/pyaspora/diaspora/protocol.py#L209 """ if isinstance(data, str): return data[0:-ord(data[-1])] else: ...
4b43b80220e195aa51c129b6cbe1f216a94360cd
21,615
def leveinshtein_distance(source,target): """ Implement leveintein distance algorithm as described in the reference """ #Step 1 s_len=len(source) t_len=len(target) cost=0 if(s_len==0): return t_len if(t_len==0): return s_len print("Dimensions:\n\tN:%d\n\tM:%d"%(s_len,t_len)) #Step 2 matrix=[[0 for _ in ...
cb8e35f491463469c68f5dbc3e3af4cff7e34441
21,616
def minus (s): """ заменить последний минус на равенство """ q = s.rsplit ('-', 1) return q[0] + '=' + q[1]
8d4ae538d866a930603b71ccdba0b18145af9988
21,617
def _chk_y_path(tile): """ Check to make sure tile is among left most possible tiles """ if tile[0] == 0: return True return False
cf733c778b647654652ae5c651c7586c8c3567b8
21,618
def json_project_activities(request): """docstring for json_project_activities""" timestamp = int(request.GET['dt']) pid = int(request.GET['id']) project = get_object_or_404(Project, id=pid) items = project.items(timestamp) objs = [] for item in items: ...
cde499b9279194cb42df66989849d8beb2de1376
21,619
from typing import List def to_complex_matrix(matrix: np.ndarray) -> List: """ Convert regular matrix to matrix of ComplexVals. :param matrix: any matrix. :return: Complex matrix. """ output: List[List] = matrix.tolist() for i in range(len(matrix)): for j in range(len(matrix[i])):...
ea21f0993452b4d2b540de4b92f64579e9aeee00
21,620
def skipIfDarwin(func): """Decorate the item to skip tests that should be skipped on Darwin.""" return skipIfPlatform( lldbplatform.translate( lldbplatform.darwin_all))(func)
ddca10a60e9d12f7e556192f922bbeaee0bc3a85
21,621
from typing import Tuple from pathlib import Path def load_dataframe(csv_path: PathLike) -> Tuple[str, pd.DataFrame]: """Returns a tuple (name, data frame). Used to construct a data set by `load_dataframes_from_directory`. See: load_dataframes_from_directory Dataset """ return Path(cs...
dbbb5f36cb767d39f01bc9c57ea27e7edfb2fb35
21,622
def VerifyReleaseChannel(options): """Verify that release image channel is correct. ChromeOS has four channels: canary, dev, beta and stable. The last three channels support image auto-updates, checks that release image channel is one of them. """ return GetGooftool(options).VerifyReleaseChannel( opt...
2be7073c9aceb2eaef111b73204d4ef4c71cc6df
21,623
def make_start_script(cmd, repo, anaconda_path, env, install_pip=(), add_swap_file=False): """ My basic startup template formatter Parameters ---------- cmd : str The actual command to run. repo : str The repository anaconda_path : str The anaconda ...
0749f257a511526bb220c3fc4c9f34bc00a0fa32
21,624
import healpy def radius_hpmap(glon, glat, R_truncation, Rmin, Npt_per_decade_integ, nside=2048, maplonlat=None): """ Compute a radius map in healpix Parameters ---------- - glon/glat (deg): galactic longitude and latitude in degrees - R_...
1daafe536ba673213a1ff3b05d0b38f8f6c48abb
21,625
def convert_grayscale_image_to_pil(image): """Converts a 2D grayscale image into a PIL image. Args: image (numpy.ndarray[uint8]): The image to convert. Returns: PIL.Image: The converted image. """ image = np.repeat(image[:, :, None], 3, 2) image_pil = Image.fromarray(image).co...
01382037d7f08de0e66a47c2be7fbaf158443a00
21,626
def delete_group(group_id, tasks=False, cached=Conf.CACHED): """ Delete a group. :param str group_id: the group id :param bool tasks: If set to True this will also delete the group tasks. Otherwise just the group label is removed. :param bool cached: run this against the cache backend :retu...
6bad912ecb265b512fecb131d9a6f567f90edc52
21,627
import re def alphanum_key(string): """Return a comparable tuple with extracted number segments. Adapted from: http://stackoverflow.com/a/2669120/176978 """ convert = lambda text: int(text) if text.isdigit() else text return [convert(segment) for segment in re.split('([0-9]+)', string)]
0e5e3f1d6aa43d393e1fb970f64e5910e7dc53fc
21,628
def merge_data(attribute_column, geography, chloropleth, pickle_dir): """ Merges geometry geodataframe with chloropleth attribute data. Inputs: dataframe or csv file name for data desired to be choropleth Outputs: dataframe """ gdf = load_pickle(pickle_dir, geography) chloropleth = load_pick...
70ce82667a974311bb3cda8785e0f6211a86dfd1
21,629
def get_ls8_image_collection(begin_date, end_date, aoi=None): """ Calls the GEE API to collect scenes from the Landsat 7 Tier 1 Surface Reflectance Libraries :param begin_date: Begin date for time period for scene selection :param end_date: End date for time period for scene selection ...
d74370a85dedd102ebe99fa41da1a69fdbb313d2
21,630
def multi_halo(n_halo): """ This routine will repeat the halo generator as many times as the input number to get equivalent amount of haloes. """ r_halo = [] phi_halo = [] theta_halo = [] for i in range(n_halo): r, theta,phi = one_halo(100) r_halo.append(r) theta...
3b46e21f983dfaa44192b7977ca2f4858818ffc1
21,631
def allocation_proportion_of_shimenwpp(): """ Real Name: Allocation Proportion of ShiMenWPP Original Eqn: Allocation ShiMen WPP/Total WPP Allocation Units: m3/m3 Limits: (None, None) Type: component Subs: None """ return allocation_shimen_wpp() / total_wpp_allocation()
e476e9472132bb81feccceef7f56c7e2eaa4b6f2
21,632
import copy def update_cfg(base_cfg, update_cfg): """used for mmcv.Config or other dict-like configs.""" res_cfg = copy.deepcopy(base_cfg) res_cfg.update(update_cfg) return res_cfg
c03dcfa7ac6d2f5c6745f69028f7cdb2ebe35eec
21,633
import traceback def check(conn, command, exit=False, timeout=None, **kw): """ Execute a remote command with ``subprocess.Popen`` but report back the results in a tuple with three items: stdout, stderr, and exit status. This helper function *does not* provide any logging as it is the caller's res...
f3ada320c245d0660f5f820e08131fed010a9fd4
21,634
import functools def domains_configured(f): """Wraps API calls to lazy load domain configs after init. This is required since the assignment manager needs to be initialized before this manager, and yet this manager's init wants to be able to make assignment calls (to build the domain configs). So ...
b336912d9abc80b2f3f5899be7fbf6ae384ae248
21,635
def add_modified_tags(original_db, scenarios): """ Add a `modified` label to any activity that is new Also add a `modified` label to any exchange that has been added or that has a different value than the source database. :return: """ # Class `Export` to which the original database is passe...
b1e18f8871e7d9430e5c4eaff41128c72359ce1c
21,636
import subprocess def get_sub_bibliography(year, by_year, bibfile): """Get HTML bibliography for the given year""" entries = ','.join(['@' + x for x in by_year[year]]) input = '---\n' \ f'bibliography: {bibfile}\n' \ f'nocite: "{entries}"\n...\n' \ f'# {year}' out...
7c990c0a1e463f1db0fdc9a522f7c224f5969f7f
21,637
def import_tep_sets(lagged_samples: int = 2) -> tuple: """ Imports the normal operation training set and 4 of the commonly used test sets [IDV(0), IDV(4), IDV(5), and IDV(10)] with only the first 22 measured variables and first 11 manipulated variables """ normal_operation = import_sets(0) t...
d9affb48e182f4bb79cdb86e70ca90dadd461d51
21,638
def to_fgdc(obj): """ This is the priamry function to call in the module. This function takes a UnifiedMetadata object and creates a serialized FGDC metadata record. Parameters ---------- obj : obj A amg.UnifiedMetadata class instance Returns ------- : str A strin...
762f77c45f2e40fd9135b3821e91b9c1c7a30bd9
21,639
def compute_iqms(settings, name='ComputeIQMs'): """ Workflow that actually computes the IQMs .. workflow:: from mriqc.workflows.functional import compute_iqms wf = compute_iqms(settings={'output_dir': 'out'}) """ workflow = pe.Workflow(name=name) inputnode = pe.Node(niu.IdentityI...
90ce62cd50ed2818e01c55eabde437b84a10dc70
21,640
def get_nbest_bounds_from_membership(membership_logits, n_best_size=1): """ Return possible inclusive start, exclusive end indices given a list of membership logits. :param membership_logits: :return: two lists, each of length n (in nbest) """ # TODO: include heuristic for choosing bounds (not j...
0e6e40f27d568b7a4e1078f44ea4ef4d90b46c3a
21,641
def GetDepthFromIndicesMapping(list_indices): """ GetDepthFromIndicesMapping ========================== Gives the depth of the nested list from the index mapping @param list_indices: a nested list representing the indexes of the nested lists by depth @return: depth """ retur...
c2318b3c6a398289c2cbf012af4c562d3d8bc2da
21,642
import signal def lowpassIter(wp, ws, fs, f, atten=90, n_max=400): """Design a lowpass filter using f by iterating to minimize the number of taps needed. Args: wp: Passband frequency ws: Stopband frequency fs: Sample rate f: Function to design filter atten: desired...
c9733a8d7c225dfbf76a4a11441ce75bd8f9042f
21,643
from typing import Union from typing import Dict import numpy def evaluate_themes( ref_measurement: Measurement, test_measurement: Measurement, themes: Union[FmaskThemes, ContiguityThemes, TerrainShadowThemes], ) -> Dict[str, float]: """ A generic tool for evaluating thematic datasets. """ ...
d6f56d54e19b35d6ab3d716d7a231fb27bc3db9a
21,644
def test_global_averaging(): """Test that `T==N` and `F==pow2(N_frs_max)` doesn't error, and outputs close to `T==N-1` and `F==pow2(N_frs_max)-1` """ if skip_all: return None if run_without_pytest else pytest.skip() np.random.seed(0) N = 512 params = dict(shape=N, J=9, Q=4, J_fr=5, Q...
d8a7c08754c403a2a3450be6ee5856a57f686003
21,645
def poly_coefficients(df: np.ndarray,z: np.ndarray,cov: np.ndarray) -> np.ndarray: """ Calculate the coefficients in the free energy polynomial Parameters ---------- df : [2,iphase] Difference between next and current integration points z: np.ndarray [2,iphase] Conjugate v...
67270bbb03a8f9d006e4d22d22f114ec6deab057
21,646
def NoneInSet(s): """Inverse of CharSet (parse as long as character is not in set). Result is string.""" return ConcatenateResults(Repeat(NoneOf(s), -1))
00bb27c434b630926eb8d2012ebed6bb1bf368d4
21,647
import re def _read_part(f, verbose): """Reads the part name and creates a mesh with that name. :param f: The file from where to read the nodes from. :type f: file object at the nodes :param verbose: Determines what level of print out to the console. :type verbose: 0, 1 or 2 :return: Nothing,...
d6546e39dc0998e979c3cb03b60f149e2a474518
21,648
async def get_prefix(bot, message): """Checks if the bot has a configuration tag for the prefix. Otherwise, gets the default.""" default_prefix = await get_default_prefix(bot) if isinstance(message.channel, discord.DMChannel): return default_prefix my_roles = [role.name for role in message.guild...
15d44e0a976858b5217b68740485dddd4b4bf0ef
21,649
import pickle import os import re def fileprep(f, plate=None, ifu=None, smearing=None, stellar=False, maxr=None, cen=True, fixcent=True, clip=True, remotedir=None, gal=None, galmeta=None, rootdir=None): """ Function to turn any nirvana output file into useful objects. Can take in `.fits`,...
7b0540ca4f6eead1769c17e4b4824e5f994f8d33
21,650
def HA19(request): """ Returns the render for the sdg graph """ data = dataFrameHA() figure = px.bar(data, x = "Faculty", y = "HA 19", labels = {"Faculty":"Faculties", "HA19":"Number of Modules Corresponding to HA 19"}) figure.write_image("core/static/HA19.png") return render(re...
6cdeb6589fffd910b981c583213e268e2ae0f1e2
21,651
import os def student_stop_eligibility_plots(input_directory): """ Create a distribution plot of the number of stop options for """ f = [stop_eligibility_counts(os.path.join( input_directory, 'student-stop-eligibility-{}.csv'.format(s))) for s in ['25', '40', '50', '100', '82']] fi...
77c1d137dee4f5d823403b0ef1fd5fff8fd2703c
21,652
def beta(data, market, periods, normalize = False): """ .. Beta Parameters ---------- data : `ndarray` An array containing values. market : `ndarray` An array containing market values to be used as the comparison when calculating beta. periods : `int` Number ...
23071387d52d9a715dcb286cc74779d83438d453
21,653
import math def heading_from_to(p1: Vector, p2: Vector) -> float: """ Returns the heading in degrees from point 1 to point 2 """ x1 = p1[0] y1 = p1[1] x2 = p2[0] y2 = p2[1] angle = math.atan2(y2 - y1, x2 - x1) * (180 / math.pi) angle = (-angle) % 360 return abs(angle)
a9fe4fe79fdff0c390e5870fb05d4e9f0c371185
21,654
import math def selSPEA2Diverse(individuals, k): """Apply SPEA-II selection operator on the *individuals*. Usually, the size of *individuals* will be larger than *n* because any individual present in *individuals* will appear in the returned list at most once. Having the size of *individuals* equals t...
d5b651844c3dc8ad96e04f9a93e264d368b066a3
21,655
def utilization_to_states(state_config, utilization): """ Get the state history corresponding to the utilization history. Adds the 0 state to the beginning to simulate the first transition. (map (partial utilization-to-state state-config) utilization)) :param state_config: The state configuration. ...
1eaaff399dfd6981feb8de56eb5dc4b4baa8fd3f
21,656
import requests def post_captcha(captcha, cookie, id): """Envia o captcha reconhecido para permitir o download. Parameters ---------- captcha : str, captcha reconhecido coookie : str, cookie com as informacoes da sessao id : str, id do CV Notes ----- Esse endpoint retorna um json...
adc96d4c285bf9d02a446a7f826288d79470a416
21,657
from typing import Dict def generate_person(results: Dict): """ Create a dictionary from sql that queried a person :param results: :return: """ person = None if len(results) > 0: person = { "id": results[0], "name": results[1].decode("utf-8"), ...
21c2f2c8fa43c43eabf06785203556ccae708d45
21,658
def paliindrome_sentence(sentence: str) -> bool: """ `int` """ string = '' for char in sentence: if char.isalnum(): string += char return string[::-1].casefold() == string.casefold()
4559f9f823f748f137bbe1eb96070dba8e7d867d
21,659
def get_default_pool_set(): """Return the names of supported pooling operators Returns: a tuple of pooling operator names """ output = ['sum', 'correlation1', 'correlation2', 'maximum'] return output
32d28fdb80ecdacab8494251edd87b566128fd79
21,660
def virtual_networks_list_all(**kwargs): """ .. versionadded:: 2019.2.0 List all virtual networks within a subscription. CLI Example: .. code-block:: bash salt-call azurearm_network.virtual_networks_list_all """ result = {} netconn = __utils__["azurearm.get_client"]("network...
52b9d655a2459d1b2f2904fc216b5ccc8ad12b04
21,661
def generate_state_matrix(Hprime, gamma): """Full combinatorics of Hprime-dim binary vectors with at most gamma ones. :param Hprime: Vector length :type Hprime: int :param gamma: Maximum number of ones :param gamma: int """ sl = [] for g in range(2,gamma+1): for s in combinatio...
165a6bfe742569780939783dc7f1b086245c747e
21,662
import os def excel_file2(): """Test data for custom data column required fields.""" return os.path.join('test', 'data', 'NADataErrors_2018-05-19_v1.0.xlsx')
84a6ae00e88b8035f92b9c4c8702a63a0631ec0f
21,663
def playfair_decipher(message, keyword, padding_letter='x', padding_replaces_repeat=False, letters_to_merge=None, wrap_alphabet=KeywordWrapAlphabet.from_a): """Decipher a message using the Playfair cipher.""" column_order = list(range(5)) row_order = list(range(5...
d66afe1447be6b5453a5271f80e678d5e1664c95
21,664
import json def create_role(role_name): """Create a role.""" role_dict = { "Version" : "2012-10-17", "Statement" : [ { "Effect" : "Allow", "Principal" : { "Service" : "lambda.amazonaws.com" }, "Acti...
743a88c5e071d1ed2e968f7ec3a7421eaab4d69e
21,665
def evaluate_field(record, field_spec): """ Evaluate a field of a record using the type of the field_spec as a guide. """ if type(field_spec) is int: return str(record[field_spec]) elif type(field_spec) is str: return str(getattr(record, field_spec)) else: return str(fiel...
66fdc96aa774a27c225fb273040acdbbf4ff9979
21,666
def project_points(X, K, R, T, distortion_params=None): """ Project points from 3d world coordinates to 2d image coordinates """ x_2d = np.dot(K, (np.dot(R, X) + T)) x_2d = x_2d[:-1, :] / x_2d[-1, :] if distortion_params is not None: x_2d_norm = np.concatenate((x_2d, np.ones((1, x_2d.sha...
e7f2c3f864e7beb798194eca3425cd9342b2c881
21,667
import os def project_exists(response: 'environ.Response', path: str) -> bool: """ Determines whether or not a project exists at the specified path :param response: :param path: :return: """ if os.path.exists(path): return True response.fail( code='PROJECT_NOT_FOUND'...
d672a8e7685e1a53634026bd3de9ffed2b1c1472
21,668
import numpy as np def rate_multipressure(qD, delta_p, B, mu, perm, h): """Calculate Rate as Sum of Constant Flowing Pressures""" return ((.007082 * perm * h) / (B * mu)) * (np.sum(qD * delta_p))
a8621613abb63bb6f15c71ab3ba02d65ab160e6b
21,669
def osculating_elements_of(position, reference_frame=None, gm_km3_s2=None): """Produce the osculating orbital elements for a position. `position` is an instance of :class:`~skyfield.positionlib.ICRF`. These are commonly returned by the ``at()`` method of any Solar System body. ``reference_frame`` is an...
cf6096ed0eeaeccaa013e052ad1a2fe7e63940f5
21,670
import copy def rename_actions(P: NestedDicts, policy: DetPolicy) -> NestedDicts: """ Renames actions in P so that the policy action is always 0.""" out: NestedDicts = {} for start_state, actions in P.items(): new_actions = copy.copy(actions) policy_action = policy(start_state) new...
433433ded44f118ec05ddbf9fde17825b0fd4e62
21,671
import csv from datetime import datetime async def get_category(category): """ Retrieves the data for the provided category. The data is cached for 1 hour. :returns: The data for category. :rtype: dict """ # Adhere to category naming standard. category = category.lower() # URL to re...
a40ba9ec753b8d7a0b2a464675a1bb541be193f0
21,672
def plot_ellipses_area( params, depth="None", imin=0, imax=398, jmin=0, jmax=898, figsize=(10, 10) ): """Plot ellipses on a map in the Salish Sea. :arg params: a array containing the parameters (possibly at different depths and or locations). :type param: np.array :arg depth: The depth at w...
b1f96ae602b6e4b1db725ac4efd2be193c23c29c
21,673
import sys def get_repo_owner_from_url(url: str) -> str: """Get git repository owner from git remote url. Args: url: (str) git remote url. Can be "git@" or "https://". Returns: str: git repository owner (user or organization). """ last_slash_index = url.rfind('/') # IF HTTPS...
e482c6902b833fba92b3caad8934168963717542
21,674
def radec2lb(ra, dec, radian=False, FK5=False): """ Convert (ra, dec) into Galactic coordinate (l, b). Parameters ---------- ra : float or list or array RA Coordinates in degree dec : float or list or array DEC Coordinates in degree Returns ------- l : float or list...
300ca9b9dbb2b59870a2bbf050442b35364254f1
21,675
from typing import Dict def populate_workflow_request_body(manifest_data: Dict): """ Populate workflow request body with the passed data according API specification :param data: item data from manifest files :return: populated request :rtype: dict """ request = { "runId": ...
f0ec863d835907402a9a5fa3ce3c61ea1e9a4b69
21,676
import os import logging def openImage(filename, videoFrameTime=None, isMask=False, preserveSnapshot=False): """ Open and return an image from the file. If the file is a video, find the first non-uniform frame. videoFrameTime, integer time in milliseconds, is provided, then find the frame after that point...
70c0759ffaceba6a3c62df44439d290704a7af5a
21,677
def is_leap_year(year): """ Is the current year a leap year? Args: y (int): The year you wish to check. Returns: bool: Whether the year is a leap year (True) or not (False). """ if year % 4 == 0 and (year % 100 > 0 or year % 400 == 0): return True return False
16e4c83adc9d42dae2396186f980755b33af9188
21,678
def delta2bbox(src_bbox, delta): """ src_bbox: (N_bbox, 4) delta: (N_bbox, 4) """ #---------- debug assert src_bbox.shape == delta.shape assert isinstance(src_bbox, np.ndarray) assert isinstance(delta, np.ndarray) #---------- src_bbox_h = src_bbox[:,2] - src_bbox[:,0] src...
5626efbe0a051eea0123cc8fde1b1196e0f5dcf1
21,679
def blank_dog(): """Set up (16, 3) array of dog with initial joint positions""" length = 0.5 width = 0.2 ankle_length = 0.1 ankle_to_knee = 0.2 knee_to_shoulder = 0.05 O = Vector(0,0,0) # origin out = [] for lengthwise in [-1, +1]: for widthwise in [+1, -1]: foot = O + length * Vector(lengthwise/2,0,0) ...
af53bd94e273b79b44ff25fff32245ea0dcae280
21,680
def pandoc_command(event, verbose=True): #@+<< pandoc command docstring >> #@+node:ekr.20191006153547.1: *4* << pandoc command docstring >> """ The pandoc command writes all @pandoc nodes in the selected tree to the files given in each @pandoc node. If no @pandoc nodes are found, the command loo...
972cd1e683b70c175e6b1710b9efb875932d8359
21,681
def random_majority_link_clf(): """ for link classification we do not select labels from a fixed distribution but instead we set labels to the number of possible segments in a sample. I.e. we only predict a random link out of all the possible link paths in a sample. """ def clf(labels, k:int...
f53f2fee85914e25d5e407808dcfbee623b0782a
21,682
def db_to_df(db_table): """Reads in a table from the board games database as pandas DataFrame""" query = f"SELECT * FROM {db_table};" pd_table = pd.read_sql(query, DB) return pd_table
d20f876c7a7e8da891dc949e85eb35932c6ae5fa
21,683
import time import os import signal def kill_master_if_running(identifier="lunchrc", directory=None): """ Given a lunch master identifier and a PID file directory, kills the master. """ pid_file = gen_pid_file_path(identifier, directory) deferred = defer.Deferred() send_sigkill_at = time.time(...
6808932c8cc6d0d9280c7f76c5b282471dcbc287
21,684
def player_input_choice() -> int: """Function that takes the player input as the position for his|her marker""" marker_position = 0 while marker_position not in range(1, 10) or not tic_tac_toe.check_the_cell(marker_position): marker_position = int(input("Choose the position for your marker from 1 to...
b717068f4e1aa36251b1ee1503034a3f60b193c7
21,685
def increment_datetime_by_string(mydate, increment, mult=1): """Return a new datetime object incremented with the provided relative dates specified as string. Additional a multiplier can be specified to multiply the increment before adding to the provided datetime object. Usage: ...
7651ccb9c4b5b881c5d1389dcdfd015dfabb0a3b
21,686
def get_regularization_loss(scope=None, name="total_regularization_loss"): """Gets the total regularization loss. Args: scope: An optional scope name for filtering the losses to return. name: The name of the returned tensor. Returns: A scalar regularization loss. """ losses = get_regularization_...
dd65e13111b0927c197b38e4500d5194a7bd5453
21,687
import os def Make_Sequential(sents, **kwargs): """ Make sequential parses (each word simply linked to the next one), to use as baseline """ output_path = kwargs.get("output_path", os.environ["PWD"]) sequential_parses = [] for sent in sents: parse = [["0", "###LEFT-WALL##...
53590b53fcbfe2739662c16c2b943dfff6184bf4
21,688
def storage_backend_get_all(context, inactive=False, filters=None): """Get all storage backends""" return IMPL.storage_backend_get_all(context, inactive, filters)
9f67dab8e6576ee30185a36e59cfb8e0d45569cb
21,689
from datetime import datetime import requests def get_date_opm_status_response(intent, session): """ Gets the current status of opm for the day """ card_title = "OPM Status Result" session_attributes = {} speech_output = "I'm not sure which o. p. m. status you requested. " \ "P...
29d1517f87495751a604c209768d6750a0ab960e
21,690
def oauth_api_request(method, url, **kwargs): """ when network error, fallback to use rss proxy """ options = _proxy_helper.get_proxy_options() client = RSSProxyClient(**options, proxy_strategy=_proxy_strategy) return client.request(method, url, **kwargs)
07438100ea75ae144567001832986f03cd72c3a8
21,691
def validate_cached(cached_calcs): """ Check that the calculations with created with caching are indeed cached. """ valid = True for calc in cached_calcs: if not calc.is_finished_ok: print('Cached calculation<{}> not finished ok: process_state<{}> exit_status<{}>' ...
3406c584dada7d24a46cbb565d0cdbab98a1d303
21,692
def SplitRecursively(x, num_splits, axis=-1): """Splits Tensors in 'x' recursively. Args: x: a Tensor, or a list or NestMap containing Tensors to split. num_splits: number of splits per Tensor. axis: the split axis. Returns: A list of split values of length 'num_splits'. - If 'x' is a Tenso...
75b7f1bae3af09dc27147b234a1a17ee8c6c988a
21,693
import time def generate_entry(request, properties, data, mtime=None): """ Takes a properties dict and a data string and generates a generic entry using the data you provided. :param request: the Request object :param properties: the dict of properties for the entry :param data: the data co...
3fcbaa919a2abb3d35e5d096b65b8d3ddf020b51
21,694
def info(): """Refresh teh client session using the refresh token""" global client client = client.refresh_session(app_id, app_secret) return "Refreshed"
0bd7070d020a40af17a105663e8cfca6b7bbc800
21,695
def weight_point_in_circle( point: tuple, center: tuple, radius: int, corner_threshold: float = 1.5 ): """ Function to decide whether a certain grid coordinate should be a full, half or empty tile. Arguments: point (tuple): x, y of the point to be tested ...
db0da5e101184975385fb07e7b22c5e8a6d4fd47
21,696
def encipher_shift(plaintext, plain_vocab, shift): """Encrypt plain text with a single shift layer. Args: plaintext (list of list of Strings): a list of plain text to encrypt. plain_vocab (list of Integer): unique vocabularies being used. shift (Integer): number of shift, shift to the right if shift is...
4bdd9d00523aa546ca697e45f31db6739ad71723
21,697
def esmf_interp_points(ds_in, locs_lon, locs_lat, lon_field_name='lon', lat_field_name='lat'): """Use ESMF toolbox to interpolate grid at points.""" # generate grid object grid = esmf_create_grid(ds_in[lon_field_name].values.astype(np.float), ds_in[lat_field_name...
b90322b852c2523a3265c9e0877675dc59717ec9
21,698
def update_loan_record(id_: int, loan_record: LoanRecord) -> bool: """Update a loan record from the database Args: id_: loan record id which wants to be modified. loan_record: new information for updating.""" updated_data = {key: value for key, value in loan_record.items() if value is not None} # ...
933d6551cf7c719bc98a4c3b37392ceba3f9e3f4
21,699