content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import json def create_diff_json(image_diff, file_output_name): """diff image file and save as file args: image_diff (object) file_output_name (str) returns: saved_file (str) """ diff_content = {} for attr in image_diff.attributes: diff_content[attr] = {} ...
0e5b506b7acbc15ca26f21640ee2748598858008
11,230
def format_class_name(spider_name): """Format the spider name to A class name.""" return spider_name.capitalize() + 'Spider'
a477c02873347e8df975dade64b8c316ab8dfe67
11,231
def ordinal(value): """ Cardinal to ordinal conversion for the edition field """ try: digit = int(value) except: return value.split(' ')[0] if digit < 1: return digit if digit % 100 == 11 or digit % 100 == 12 or digit % 100 == 13: return value + 'th' elif digit ...
b97accfe96f214ffe9878c24bd78ab63083c9329
11,233
import torch def complex_abs(tensor): """Compute absolute value of complex image tensor Parameters ---------- tensor : torch.Tensor Tensor of shape (batch, 2, height, width) Returns ------- Tensor with magnitude image of shape (batch, 1, height, width) """ tensor = (tensor[:, 0] ** 2 + tensor[...
dd206d9fb58b819d5ed1c58af8e9fc559430ac3a
11,234
import win32security import os def isUserAdmin(): """Check if the current OS user is an Administrator or root. :return: True if the current user is an 'Administrator', otherwise False. """ if os.name == 'nt': try: adminSid = win32security.CreateWellKnownSid( win32...
9214ef749c6cfeeee0305f2e1d0bfdbf2b5cedcc
11,235
def format_docstring(usage: str, arg_list, kwarg_dict): """ Use argument lists to create Python docstring """ usage = usage.strip().strip("\"") docstring = f'{usage}\n\n' for arg in arg_list: if not arg['input']: continue docstring += f"\t:param {arg['name']} {arg['t...
a68c0d03aaf851ffb039b722affbdc60f7d05c1c
11,236
from pathlib import Path import shutil def temp_article_dir(temp_cwd: Path) -> Path: """Run the test from a temporary directory containing the "tests/data/article" dataset. """ article_source_dir = Path(__file__).parent / "data" / "article" for source_path in article_source_dir.iterdir(): ...
643b2c7f1183f19f263eaba0f3e930ac18fa6988
11,237
def test_pointer_indexing(pointer_value, type_p): """ >>> a = np.array([1, 2, 3, 4], dtype=np.float32) >>> test_pointer_indexing(a.ctypes.data, float32.pointer()) (1.0, 2.0, 3.0, 4.0) >>> a = np.array([1, 2, 3, 4], dtype=np.int64) >>> test_pointer_indexing(a.ctypes.data, int64.pointer()) (1...
21f87a5ec840e3fd789c9e1ca9382d96f451e1e5
11,239
def find_by_id(object_id, items): """ Find an object given its ID from a list of items """ for item in items: if object_id == item["id"]: return item raise Exception(f"Item with {object_id} not found")
822bf82ea68bd94d0bb1ed2dd5db754aee9b0cba
11,240
import requests import json def create_snippet(data, baseurl, timeout, raw): """ Creates snippet with the given data on the haste server specified by the baseurl and returns URL of the created snippet. """ try: url = baseurl + "/documents" response = requests.post(url, data.encode(...
eb34861909b61749ef2f29da16450a82dcc8d83e
11,241
import torch def fuse_epic_sliding_windows(maps_dict): """ Since different sliding windows have overlap, we desigin this function to fuse sliding windows. Args: maps_dict (dict): { "start_map": (tensor) "end_map": (tensor) "verb_map": (te...
205ac18633fcfddd9ba9af6f7b82d89345bf96c3
11,242
import argparse def get_args(): """Process command-line arguments.""" parser = argparse.ArgumentParser( description='Tool to list all masters along with their hosts and ports.') parser.add_argument( '-l', '--list', action='store_true', default=False, help='Output a list of all ports in use by...
e2434453d3bb8a430966f78bfd7b7978628d0443
11,243
def wh_to_kwh(wh): """ Convert watt hours to kilowatt hours and round to two decimal places :param wh: integer or decimal value :return: two decimal spot kilowatt hours """ kw = float("{0:.2f}".format(wh / 1000.00)) return kw
19488960a9c7a4d2fc748f4d897d082cfdaee2b8
11,244
def julio (string, number): """ I like this program. """ alpha_cod = "" codificated = "" i = 0 position = 0 alpha = "ABCDEFGHIKLMNOPQRSTVX" while i < len(alpha): if i + number >= len(alpha) or i + number <= -1: alpha_cod = alpha_cod + alpha [(i + number) % len(al...
676b6f12ddf5897171cc809de2275ec4972fa4a0
11,247
import torch def recall_at_k_batch_torch(X_pred, heldout_batch, k=100): """ Recall@k for predictions [B, I] and ground-truth [B, I]. """ batch_users = X_pred.shape[0] _, topk_indices = torch.topk(X_pred, k, dim=1, sorted=False) # [B, K] X_pred_binary = torch.zeros_like(X_pred) if torch.cu...
580305c0ed43a22e8cf64bee23e3e207516e9e2a
11,248
def widthHeightDividedBy(image, value): """Divides width and height of an image by a given value.""" w, h = image.shape[:2] return int(w/value), int(h/value)
78bbe60c43a1bbf362c98125bfddc080cf568861
11,249
def analytical_pulse_energy(q, ekev): """ Estimate of analytical_pulse_energy from electron bunch charge and radiation energy :param q: electron bunch charge [nC] :param ekev: radiation energy [keV] :return P: pulse energy [J] """ P = 19*q/ekev return P/1e3
d81ddafcc41e0e8619922dce0583bf19579112bc
11,250
def get_file_date(tree): """ Get publication date from dta file xml tree. :param tree: the xml tree :return: int, the publication date """ date = tree.find("{http://www.dspin.de/data/metadata}MetaData/{http://www.dspin.de/data/metadata}source/{http://www.clarin.eu/cmd/}CMD/{http://www.clar...
64b0e43b9926d94f1cec066af5bf58ecc10d5044
11,251
import sys def open_file(path, mode='r'): """ Open file with an option to route from stdin or stdout as needed. """ if path == '-': if mode.count('r'): f = sys.stdin else: f = sys.stdout else: f = open(path, mode) return f
b304a8dc68f2b558e0d0dbd69158128bac103cc6
11,253
def format_version(version): """Converts a version specified as a list of integers to a string. e.g. [1, 2, 3] -> '1.2.3' Args: version: ([int, ...]) Version as a list of integers. Returns: (str) Stringified version. """ return '.'.join(str(x) for x in version)
fa85b122ce6fed4919ec87ad29847b0997493806
11,254
import yaml import os def read_config_file(filename): """ read yaml config file Parameters ---------- filename (string) Returns ------- dict (dictionary) boolean (boolean) """ flag = os.path.isfile(filename) if flag: with open(filename,'r') as handle: ...
28d20708faa26db9a1040444f04ee92af5523d9d
11,255
def even_or_odd(n): """Return a string odd or even for odd or even values of n.""" if n % 2 == 0: return 'Even' else: return 'Odd'
956e071eeb4be5b9ec2851fc1b566ff1e3e2ef98
11,256
def SetTriggerMode(mode): """ This function will set the trigger mode that the camera will operate in. Valid values: 0. Internal 1. External 6. External Start 7. External Exposure (Bulb) 9. Externa...
9fcb6f3524de7eed5cdda02ce56a5077a97c2d75
11,258
def L(n, ri, c): """Calcula las matrices Li. ri: a[i][c] / a[c][c] c : columna c-esima """ #Matriz identidad L = [[float(i == j) for j in range(n)] for i in range(n)] for k in range(c+1, n): L[k][c] = -ri[k] return L
d6f7293691842d7175facc540c35cd1c1a43ee09
11,259
import os import zipfile def unzip(src_path, dst_path = None): """Extracts a zipfile. Defaults extraction to the same path. Returns filename list.""" dst_pathmod = dst_path if dst_path is None: dst_pathmod = os.path.dirname(src_path) with zipfile.ZipFile(src_path) as zf: nmlist = zf.namelist() zf.extractall...
8947922c1026e669fa494d369f8beaedce49bea5
11,260
def get_type(type_f): """ A function used to categorized each formula. """ tmp = '' if 'trad' in type_f: tmp = 'T' elif 'TCONG' in type_f: tmp = 'P' elif 'DRA' in type_f: tmp = 'R' elif 'WDBA' in type_f: tmp = 'W' else: tmp = type_f ret...
438c3c3c7fc22fbd09f97727bd30890519efa918
11,261
def hex_to_int(input: str) -> int: """Given a hex string representing bytes, returns an int.""" return int(input, 16)
844714eaec1a2b2804cb4725e458980555516ce2
11,262
import string def filter_filename(filename): """Utility to filter a string into a valid filename""" valid_chars = "-_.() %s%s" % (string.ascii_letters, string.digits) filename = ''.join(c for c in filename if c in valid_chars) return filename
8ab97e9a3d9b806090a4b55f6a47d2f011f99ede
11,266
from warnings import warn import logging def logger(): """Access global logger. .. deprecated:: 3.3 To control logging from ixmp, instead use :mod:`logging` to retrieve it: .. code-block:: python import logging ixmp_logger = logging.getLogger("ixmp") # Example: ...
28b8eb99d41171e36163e89799c1cc313c311184
11,267
def dot_product(A, B): """ Computes the dot product of vectors A and B. @type A: vector @type B: vector @rtype: number @return: dot product of A and B """ if len(A) != len(B): raise ValueError("Length of operands do not match") result = 0.0 for i, v in enumerate(A): ...
f63528bda5d3890137a35de5fd639086262b5c93
11,268
def has_sources(target, extension=None): """Returns True if the target has sources. If an extension is supplied the target is further checked for at least 1 source with the given extension. """ return (target.has_label('sources') and (not extension or (hasattr(target, 'sources') ...
71853d034f6fe8283f2178daf3648ac75457ec2e
11,269
def fibo(n): """Returns nth fibonacci number.""" a, b = 0, 1 for i in range(1, n): a, b = b, a+b return b
b9a8d3960cc01f1745151eda250fea97c0e62b14
11,270
def check_accuracy_single(dat, label): """NOTE: OLD! UNUSED. Use sklearn funcs. Test the accuracy for a list of results, with single answer. Parameters ---------- dat : list of int Predicted labels of a set of test data. label : int The correct label. Returns ------- ...
26fec27fcd03eb637dd2c94559c182a172d693a5
11,271
from typing import Dict from typing import List from typing import Iterable def get_comments(pf) -> Dict[str, List[str]]: """Retrieves comments from proto file and creates a dictionary symbol which comment was aimed at""" def _get_inner(): i = 0 for location in pf.source_code_info.location: ...
e2617546f62f05c71a2113d06dc31f89cd6b688c
11,273
def or_(*args): """Compute the logic OR between expressions. """ return any(*args)
17b775029490d5ca4ea1574186bd02a77a92782a
11,275
def decimalHour(time_string): """ Converts time from the 24hrs hh:mm:ss format to HH.hhh format. """ hh, mm, ss = time_string.split(':') hh, mm, ss = map(float, (hh, mm, ss)) result = ((ss/60) + mm)/60 + hh return result
b931ce0bd1c57c0d2b47a5d51331685e6c478b61
11,276
def getFileName(fileRequest): """returns the file name from a file Request""" nameByteLength = int(((fileRequest[3] << 8 ) | (fileRequest[4]))) return fileRequest[5:nameByteLength * 2]
d6f500b4101677ab2655650f33f0b3f206c55e9c
11,277
def _generate_flame_clip_name(context, publish_fields): """ Generates a name which will be displayed in the dropdown in Flame. :param publish_fields: Publish fields :returns: name string """ # this implementation generates names on the following form: # # Comp, scene.nk (output backgro...
91d49612815830c3260920f6f87a6d4eada1006f
11,279
from typing import List from typing import Tuple from typing import Optional def aggregate_changes( query_result: List[Tuple[int, int]], initial: Optional[Tuple[int, int, int]] = None ) -> Tuple[int, int, int]: """Add a changeset to the aggregated diff result""" result = list(initial) if initial else [0, ...
ac31c0424ca26fd2bfb5d035b1fea436cbe7d008
11,280
def calc_air_density(temperature, pressure, elevation_ref=None, elevation_site=None, lapse_rate=-0.113, specific_gas_constant=286.9): """ Calculates air density for a given temperature and pressure and extrapolates that to the site if both reference and site elevations are given. :...
964bff72d67354abeff9a355788d3624d7ec230c
11,282
import os import requests def get_source_repo(target, auth=None): """Get the source repo for a given repo. Parameters ---------- target : str The GitHub organization/repo auth : str, optional The GitHub authorization token Returns ------- str A formatted PR en...
285636537155979fbaa31f53f313de75540223a2
11,284
import numpy def replace_df_nulls(DF, null_list): """For each column in input DataFrame, replace with null and values in null_list. Args: DataFrame to replace missing values with null, List of values to replace with null. Returns: Cleaned DataFrame.""" for col in...
62637bf2ef33884bc6bb4dd6dd0d8270e3a4e84b
11,285
def market_keys(): """Standard keys for storage""" return ['player_id', 'player_name', 'price', 'amount']
0a514f5ae1d138a1e84700ab15b88380186f70b0
11,286
def get_ads_from_path(path_i): """ """ #| - get_ads_from_path ads_i = None # if "run_o_covered" in path_rel_to_proj_i: if "run_o_covered" in path_i: ads_i = "o" elif "run_bare_oh_covered" in path_i: if "/bare/" in path_i: ads_i = "difjsi" # elif "/oh" ...
910ede094dd92c180724a950bce80c2d3e69f9b0
11,287
import pathlib def module_to_path(module: str, suffix=".py") -> pathlib.Path: """convert module a.b.c to path(a/b/c)""" return pathlib.Path(*module.split(".")).with_suffix(suffix)
682fd05379e81a5d8d24f5d0f4ab8134cbbce0e7
11,288
def byte(value): """Converts a char or int to its byte representation.""" if isinstance(value, str) and len(value) == 1: return ord(value) elif isinstance(value, int): if value > 127: return byte(value - 256) if value < -128: return byte(256 + value) r...
6ef59f49a5d0d49ee7222387a8615567ff9d6267
11,289
def select_frame(**params): """切换Frame""" return [ 'self.driver.switch_to.default_content()', "self.driver.switch_to.frame('{target}')".format(**params) ]
76939cadb680554fecd5bf481970a70a37be13a7
11,291
def mlist(self, node1="", node2="", ninc="", **kwargs): """Lists the MDOF of freedom. APDL Command: MLIST Parameters ---------- node1, node2, ninc List master degrees of freedom from NODE1 to NODE2 (defaults toNODE1) in steps of NINC (defaults to 1). If NODE1 = ALL (defaul...
611cd462d34cd4de0e34cb262549fc6cff40127d
11,292
import yaml def _get_benchmark(platform: str, command: str) -> dict: """Get benchmark structured datas.""" # template_index = parser.search_template_index(platform, command) command = str(command.replace(" ", "_")) with open( "tests/" + platform + "_" + command + "/" + platform + "_" + command...
4d98fac166a979343d0bb849eb2000e434edea78
11,293
def formatstr(text): """Extract all letters from a string and make them uppercase""" return "".join([t.upper() for t in text if t.isalpha()])
749aeec962e3e39760c028bfb3e3a27ad8c10188
11,294
def reflexive_missing_elements(relation, set): """Returns missing elements to a reflexive relation""" missingElements = [] for element in set: if [element, element] not in relation: missingElements.append((element,element)) return missingElements
c31ce237c9156f17cc87a12ac80e595f81b08889
11,295
def form2_list_comprehension(items): """ Remove duplicates using list comprehension. :return: list with unique items. """ return [i for n, i in enumerate(items) if i not in items[n + 1:]]
02d095c86de1b7d52d53cdb4bfe77db08523ea3a
11,296
def calcMass(volume, density): """ Calculates the mass of a given volume from its density Args: volume (float): in m^3 density (float): in kg/m^3 Returns: :class:`float` mass in kg """ mass = volume * density return mass
38f0ef780704c634e572c092eab5b92347edccd3
11,297
def rescale(arr, vmin, vmax): """ Rescale uniform values Rescale the sampled values between 0 and 1 towards the real boundaries of the parameter. Parameters ----------- arr : array array of the sampled values vmin : float minimal value to rescale to vmax : float ...
d6debc0eeccd9fe19ed72d869d0de270559c9ce8
11,298
def get_extreme(extreme, range_minimum, range_maximum): """ extreme : should be min or max range_minimum::int : minimum value you want your extreme to be range_maximum::int : maximum value you want your extreme to be """ if isinstance(extreme, str): if extreme == "": e...
d44d15310c83b1e2fcf03939cd1e7625f68f0b11
11,299
import shutil def rename(path: str, target: str): """Copy path to target.""" return shutil.move(path, target)
00f46f2557f4e0e7bd07610889a8c2deb028f24a
11,300
import socket def check_port_occupied(port, address="127.0.0.1"): """ Check if a port is occupied by attempting to bind the socket :return: socket.error if the port is in use, otherwise False """ s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: s.bind((address, port)) ex...
5919e228c835ceb96e62507b9891c6a1ce5948fa
11,301
def inverseExtend(boundMethod, *args, **kargs): """Iterate downward through a hierarchy calling a method at each step. boundMethod -- This is the bound method of the object you're interested in. args, kargs -- The arguments and keyword arguments to pass to the top-level method. You can call t...
a511470f6cd3d86de19cc95e489498e649bea7a5
11,303
from typing import Dict def determine_postAST_from_filename(filenamesplit) -> Dict: """determine postAST from filenamesplit""" basepf_split, postAST = filenamesplit, "" if all([i in basepf_split for i in ("post", "AST")]): if any(s in basepf_split for s in ["LC"]): if "postAST_LC" in ...
3787dcef3ae65538f2fe66f98be60cc0f71f7790
11,306
def pretty(data, corner = '+', separator='|', joins='-'): """ Parameters : ~ data : Accepts a dataframe object. ~ corner : Accepts character to be shown on corner points (default value is "+"). ~ separator : Accepts character to be shown in place to the line separating two values (default value...
812fb5d255c5e44c1d026d307e2a39c7b3c31f14
11,307
import csv def write_rows(rows, filename, sep="\t"): """Given a list of lists, write to a tab separated file""" with open(filename, "w", newline="") as csvfile: writer = csv.writer( csvfile, delimiter=sep, quotechar="|", quoting=csv.QUOTE_MINIMAL ) for row in rows: ...
41e04ee6203baf7db2d08722aed76dfacbc9e838
11,309
import collections def context(): """A mock for the lambda_handler context parameter.""" Context = collections.namedtuple('Context', 'function_name function_version') return Context('TestFunction', '1')
b7d65ca7ff87aea1bd22e87dba4cb2d0e5ec411d
11,310
def _auth_handler(): """ Requrired JWT method """ return None
9ec5301d6e32c7b3016a92ba9ae89d22fed3bad5
11,312
def HKL2string(hkl): """ convert hkl into string [-10.0,-0.0,5.0] -> '-10,0,5' """ res = "" for elem in hkl: ind = int(elem) strind = str(ind) if strind == "-0": # removing sign before 0 strind = "0" res += strind + "," return res[:-1]
325ddfcb2243ce9a30328c5b21626a4c93a219de
11,313
import logging import sys def getLogger(nm): """Get a basic-configured trace-enabled logger.""" logging.basicConfig(stream=sys.stdout, level=logging.INFO, format='%(levelname).1s: %(message)s') log = logging.getLogger(nm) return log
a6fc4f0fe6d2104c0e2487d6038401306ad3e3ba
11,314
import re def splitAtUppercase(a_string): """assumes a_string is a string returns a list of strings, a_string split at each uppercase letter""" pattern = "([A-Z])" string_list = re.split(pattern, a_string) return string_list
5cbf4673ee46db81b8acfb30bfe64a44d10d0d9a
11,315
from typing import List def should_expand_range(numbers: List[int], street_is_even_odd: bool) -> bool: """Decides if an x-y range should be expanded.""" if len(numbers) != 2: return False if numbers[1] < numbers[0]: # E.g. 42-1, -1 is just a suffix to be ignored. numbers[1] = 0 ...
fcd5a8e027120ef5cc52d23f67de4ab149b19a2c
11,316
def zyx_to_yxz_dimension_only(data, z=0, y=0, x=0): """ Creates a tuple containing the shape of a conversion if it were to happen. :param data: :param z: :param y: :param x: :return: """ z = data[0] if z == 0 else z y = data[1] if y == 0 else y x = data[2] if x == 0 else x ...
2477976f795f5650e45214c24aaf73e40d9fa4eb
11,317
def gen_anonymous_varname(column_number: int) -> str: """Generate a Stata varname based on the column number. Stata columns are 1-indexed. """ return f'v{column_number}'
f0e150300f7d767112d2d9e9a1b139f3e0e07878
11,318
def create_city_map(n: int) -> set: """ Generate city map with coordinates :param n: defines the size of the city that Bassi needs to hide in, in other words the side length of the square grid :return: """ return set((row, col) for row in range(0, n) for col in range(0, n))
fd30b936647bae64ccf2894ffbb68d9ad7ec9c6b
11,320
def nullable(datatype): """Return the signature of a scalar value that is allowed to be NULL (in SQL parlance). Parameters ---------- datatype : ibis.expr.datatypes.DataType Returns ------- Tuple[Type] """ return (type(None),) if datatype.nullable else ()
fe5935d1b4b1df736933455e97da29a901d6acb1
11,322
import os def TraverseByDepth(root, include_extensions): """ Return a set of child directories of the 'root' containing file extensions specified in 'include_extensions'. NOTE: 1. The 'root' directory itself is excluded from the result set. 2. No subdirectories would be excluded if 'i...
68f510a0014c3ad8b511a2b024e6c1d4aef05732
11,323
def build_facets(data): """ Data from facets-serves.json Data structure: { "services" : [ {"(type)": "quolab...ClassName", "id": "<name>"} ] } """ deprecated = {"casetree", "cache-id", "indirect"} services = [service["id"] for service in data["services"] if ...
1b617180a3a5d3115c5300b91eebb3d6ca079942
11,324
from typing import Dict def make_country_dict( csv_file:str = 'data/country_list.csv') -> Dict[str, str]: """Make a dictionary containing the ISO 3166 two-letter code as the key and the country name as the value. The data is read from a csv file. """ country_dict = {} with open(csv_fi...
0334a2b2c918f407d1df682f56c14943f1e66c43
11,325
import platform def host_arch_target(): """ Converts the host architecture to the first part of a target triple :return: Target host """ host_mapping = { "armv7l": "arm", "ppc64": "powerpc64", "ppc64le": "powerpc64le", "ppc": "powerpc" } machine = platform.m...
7cae48c32e03cecb42e29279a93013ad3529c978
11,326
import requests import json def ocr_space_url(overlay=False, api_key='must specify your own apikey', language='eng'): """ OCR.space API request with remote file. Python3.5 - not tested on 2.7 Register here to get free api key: -> https://ocr.space/ocrapi :param url: Image url. :param overlay: Is O...
ff16f026262383ccfca4b3de91d2b1fa09bbde32
11,327
from typing import List def get_reputation_data_statuses(reputation_data: List) -> List[str]: """ collects reported statuses of reputation data Args: reputation_data: returned data list of a certain reputation command Returns: a list of reported statuses """ reputation_statuses = [sta...
2c41344f2970243af83521aecb8a9374f74a40ac
11,328
def is_number(val): """Check if a value is a number by attempting to cast to ``float``. Args: val: Value to check. Returns: True if the value was successfully cast to ``float``; False otherwise. """ try: float(val) return True except (ValueError, TypeErr...
89728d3d199c3ef5885529da5a2d13dd94fa590f
11,329
def get_local_name(element): """ Just the element name with the schema URI (if any) removed @type element: Element @param element: The XML element @rtype: string @return: the base name of the element or None if it could not be determined """ if element is None: ret...
cef42ed650b2798c623f220686364f257e5f385f
11,330
def format_rfc3339(datetime_instance): """Formats a datetime per RFC 3339.""" return datetime_instance.isoformat("T") + "Z"
ad60a9e306e82554601efc1ae317296a59b009b0
11,331
def get_metadata_keys(options): """ Return a list of metadata keys to be extracted. """ keyfile = options.get("keyfile") if (keyfile): with open(keyfile, "r") as mdkeys_file: return mdkeys_file.read().splitlines() else: return None
2451d54ae49690691e5b0ce019178fd119e3d269
11,332
def hex_reflect_y(x, y, z): """Reflects the given hex through the x-axis and returns the co-ordinates of the new hex""" return x, z, y
92f36567d26ae8e942d3dad269cc3f196c8fbe16
11,333
import json def getFileTree(frame, dir): """ Get the TreeView structure (recursive way) """ frame.cmd_return = "" frame.exec_cmd("\r\n") result = frame.exec_cmd("os.listdir(\'%s\')\r\n" % dir) if result == "err": return result filemsg = result[result.find("["):result.find(...
64f7d9aba936476560b506b907cb36a6e1bee734
11,335
def _unpickle_method(name, im_self, im_class): """ Unpickles an instancemethod object. """ if im_self is not None: return getattr(im_self, name) else: return getattr(im_class, name)
71b7b81be74088f7060c78e706b4646c1f2e613d
11,336
def is_unexpected(actual, expected): """ evaluates if there is a parameter in actual that does not exist in expected """ if expected is None: unexpected = actual else: unexpected = filter(lambda x: x not in expected, actual) return unexpected
d0de1d2505e5ad78b5d465b2496b0a154fe0c237
11,337
def _remove_self(d): """Return a copy of d without the 'self' entry.""" d = d.copy() del d['self'] return d
a80eca3886d0499d1871998501c19e9cdae93673
11,338
def deltanpq(phino, phinoopt=0.2): """Calculate deltaNPQ deltaNPQ = (1/phinoopt) - (1/phino) :param phino: PhiNO :param phinoopt: Optimum PhiNO (default: 0.2) :returns: deltaNPQ (float) """ return (1/phinoopt) - (1/phino)
34d44a732bd87eb78e8ddee92b4555bea67789be
11,339
def html_string(request, html_file): """NYU Academic Calendar HTML as string""" return html_file.read()
c0879d51a97b643f110ad2134dc7afe9dd279b66
11,341
def opt_in_argv_tail(argv_tail, concise, mnemonic): """Say if an optional argument is plainly present""" # Give me a concise "-" dash opt, or a "--" double-dash opt, or both assert concise or mnemonic if concise: assert concise.startswith("-") and not concise.startswith("--") if mnemonic: ...
17333a2a526799d6db5e78746d3ecb7111cd8cd6
11,343
def add_side_effect_wrapper(session_mock): """Side effect for the add function, used to add an id to the input table.""" def add_side_effect(table): tablename = table.__tablename__ if tablename in session_mock.tables and len(session_mock.tables[tablename]) > 0: max_id = 0 ...
b85052f962c6437934fa9cd310eec7c559d5222d
11,345
def tie_amps_FIR_to_SIL1(model): """ function to tie the FIR amplitude to the SIL1 amplitude """ return (0.012 / 0.002) * model.SIL1_amp_0
13ae408cc618c118a7ad1059422fabad0036dff2
11,346
def split_by_unicode_char(input_strs): """ Split utf-8 strings to unicode characters """ out = [] for s in input_strs: out.append([c for c in s]) return out
290bb5ec82c78e9ec23ee1269fe9227c5198405e
11,347
def filter(lst): """ Method that filters list :param lst: list to be filtered :return: new filtered list """ if lst is None: return [] if not isinstance(lst, set): lst = set(lst) # Remove duplicates. new_lst = [] for item in lst: item = str(item) if (...
06c96962910b77a78615861822c76bbc9cfb52ce
11,348
def calc_hvac_energy(surface_area, building_type, Tin, Tout): """ Heat Transfer Equation Notes ----- Q = U x SA x (Tin - Tout) Q - Heat lost or gained due to outside temperature (kJ·h−1) U - Overall heat transfer coefficient (kJ·h−1·m−2·°C...
1616196b36f6c512763362292ceb296ad4acbf96
11,349
def getValidData(filelist=[]): """过滤集合中空的元素.""" valifile = [] for fp in filelist: if fp != None: valifile.append(fp) return valifile
57bccc440a056deee3bd16a4785823ab4f0845c2
11,350
def sorted_dict(d : dict) -> dict: """ Sort a dictionary's keys and values and return a new dictionary """ try: return {key: value for key, value in sorted(d.items(), key=lambda item: item[1])} except Exception as e: return d
ec8b38805ee26f2d2e2fe0d876c8cbda88098026
11,351
import configparser def export_story_as_config(from_slide, with_fields): """ Returns the story items for a story slide in the config format Each slide contains placeholder with a text frame which in turn contains paragraphs with text. Only ASCII characters are allowed in the story text files to overc...
529893dc5b238e86a9480d983afe5a229d762dd0
11,353
def sort_by_type_and_size(layer_nodes): """ 对关键路径中的叶子节点按照资源类型和大小进行排序 Args: leaf_nodes: 叶子节点列表 Returns: 排好序的叶子节点列表 """ document_list = [] stylesheet_list = [] font_list = [] script_list = [] for node in layer_nodes: if node['mime_type'] == 'text/html': ...
02026778cfe0ff1481e24a9b2f9304fb2a5a4fc3
11,356
def unescape_html(html): """ *Unescape a string previously escaped with cgi.escape()* **Key Arguments:** - ``dbConn`` -- mysql database connection - ``log`` -- logger - ``html`` -- the string to be unescaped **Return:** - ``html`` -- the unescaped string """ ###...
cafa4eb7ecc68b6221250947173c579e125ede07
11,357
def get_lr(optimizer): """get learning rate from optimizer Args: optimizer (torch.optim.Optimizer): the optimizer Returns: float: the learning rate """ for param_group in optimizer.param_groups: return param_group['lr']
fc8293cc29c2aff01ca98e568515b6943e93ea50
11,358