content
stringlengths
22
815k
id
int64
0
4.91M
def ht_pairtree(request): """Override django settings for **HATHI_DATA**and create a temporary directory structure mirroring top-level of hathi pairtree data (currently has no pairtree content). Sets list of `hathi_prefixes` on the calling class.""" # create temporary directories mocking hathi pair...
22,200
def summarize_single_OLS(regression, col_dict, name, is_regularized=False): """Return dataframe aggregating over-all stats from a dictionary-like object containing OLS result objects.""" reg = regression try: col_dict['rsquared'][name] = reg.rsquared except AttributeError: col_dict['rsq...
22,201
def simplify(polynom): """Simplifies a function with binary variables """ polynom = Poly(polynom) new_polynom = 0 variables = list(polynom.free_symbols) for var_i in variables: coefficient_i = polynom.as_expr().coeff(var_i)/2 coefficient_i += polynom.as_expr().coeff(var_i ** 2) ...
22,202
def get_universe_planets_planet_id(*, planet_id, if_none_match=None): """ :param if_none_match: ETag from a previous request. A 304 will be returned if this matches the current ETag :param planet_id: planet_id integer Get information on a planet --- Alternate route: `/dev/universe/planets/{plane...
22,203
def process_login(): """Log user into site. Find the user's login credentials located in the 'request', look up the user, and store them in the session. """ user_login = request.get_json() if crud.get_user_by_email(user_login['email']): current_user = crud.get_user_by_email(user_l...
22,204
def cli(): """A small tool for download HRSL data""" pass
22,205
def verify_sha256sum_stream(ioobj, target_hash): """Verify the SHA256 hash sum of a file like object""" verify_hashsum_stream(ioobj, target_hash, hashlib.sha256())
22,206
def is_int(var): """ is this an integer (ie, not a float)? """ return isinstance(var, int)
22,207
def returnstringpacket(pkt): """Returns a packet as hex string""" myString = "" for c in pkt: myString += "%02x" % c return myString
22,208
def GetIndicesMappingFromTree( tree ): """ GetIndicesMappingFromTree ========================= reuse bill's idea to gives the indexes of all nodes (may they be a sub tree or a single leaf) gives a list of indices of every sublist. To do that, I add one thing: the last element of an index i...
22,209
def preprocess_labs(lab_df: pd.DataFrame, material_to_include: list = ['any_blood'], verbose: bool = True) -> pd.DataFrame: """ Preprocess the labs dataframe :param lab_df: :param material_to_include: list of materials to include where material is one of the following: 'any_blood', '...
22,210
def find_option(command, name): """ Helper method to find command option by its name. :param command: string :param name: string :return: CommandOption """ # TODO: use all_options if command in COMMAND_OPTIONS: if name == 'help': return OPTION_HELP for opt in ...
22,211
def generate_pairwise(params, n_comparisons=10): """Generate pairwise comparisons from a Bradley--Terry model. This function samples comparisons pairs independently and uniformly at random over the ``len(params)`` choose 2 possibilities, and samples the corresponding comparison outcomes from a Bradley-...
22,212
def render_json(fun): """ Decorator for views which return a dictionary that encodes the dictionary into a JSON string and sets the mimetype of the response to application/json. """ @wraps(fun) def wrapper(request, *args, **kwargs): response = fun(request, *args, **kwargs) tr...
22,213
def count_smileys_concise(arr: List[str]) -> int: """ Another person's implementation. Turns the list into an string, then uses findall() on that string. Turning the result into a list makes it possible to return the length of that list. So this version is more concise, but uses more space. O(n) whe...
22,214
def transform_dead_op_vars(graph, translator=None): """Remove dead operations and variables that are passed over a link but not used in the target block. Input is a graph.""" return transform_dead_op_vars_in_blocks(list(graph.iterblocks()), [graph], translator)
22,215
def test_reconstruction_torch(): """Test that input reconstruction via backprop has decreasing loss.""" if skip_all: return None if run_without_pytest else pytest.skip() if cant_import('torch'): return None if run_without_pytest else pytest.skip() import torch device = 'cuda' if torc...
22,216
def to_pixels(Hinv, loc): """ Given H^-1 and (x, y, z) in world coordinates, returns (c, r) in image pixel indices. """ loc = to_image_frame(Hinv, loc).astype(int) return (loc[1], loc[0])
22,217
def fetch(params, seqid=None, db=None, update=False): """ Obtains data from NCBI """ for p in params: # Skip if exists (or not update). if p.json and not update: continue # The JSON representation of the data. json_name = resolve_fname(name=p.acc, format="j...
22,218
def temporary_upload(request): """ Accepts an image upload to server and saves it in a temporary folder. """ if not 'image' in request.FILES: return HttpResponse(simplejson.dumps({'status': 'no image uploaded'})) filename = request.FILES['image']._get_name().strip().lower() imgdata = St...
22,219
def pin_to_pinata(filename: str, config: tp.Dict[str, tp.Dict[str, tp.Any]]) -> None: """ :param filename: full name of a recorded video :type filename: str :param config: dictionary containing all the configurations :type config: dict pinning files in pinata to make them broadcasted around ipf...
22,220
def adf_test(path): """ Takes a csv file path as input (as a string) This file must have one heading as Dates and the other as Close This csv file will be converted into a series and then the ADF test will be completed using data from that csv file (Optional: will plot the data using matplot...
22,221
def add_dependency(key, value, dict): """ Add dependency to appropriate dictionary ToDo: check if defaultdict would eliminate this function """ if key in dict: if value not in dict[key]: dict[key].append(value) else: dict[key] = [value]
22,222
def calc_distance_between_points_two_vectors_2d(v1, v2): """calc_distance_between_points_two_vectors_2d [pairwise distance between vectors points] Arguments: v1 {[np.array]} -- [description] v2 {[type]} -- [description] Raises: ValueError -- [description] ValueError...
22,223
def get_nearest_list_index(node_list, guide_node): """ Finds nearest nodes among node_list, using the metric given by weighted_norm and chooses one of them at random. Parameters ---------- node_list : list list of nodes corresponding to one of the two search trees growing towards each other. guide_node : dic...
22,224
def get_extensions_from_dir(path: str) -> list[str]: """Gets all files that end with ``.py`` in a directory and returns a python dotpath.""" dirdotpath = ".".join(path.split(sep)[1:]) # we ignore the first part because we don't want to add the ``./``. return [f"{dirdotpath}.{file}" for file in listdir(path...
22,225
def to_normalized_exacta_dividends(x,scr=-1): """ Convert 2-d representation of probabilities to dividends :param x: :param scr: :return: """ fx = to_normalized_dividends( to_flat_exacta(x), scr=scr ) return from_flat_exacta(fx, diag_value=scr)
22,226
def CSVcreation(): """This functions allows to access to page for the creation of csv""" if "logged_in" in session and session["logged_in"] == True: print("User login", session["username"]) try: count1 = managedb.getCountLoginDB(session["username"]) if count1 == 0: ...
22,227
def aws_services(): """List or search for services by attribute.""" pass
22,228
def filter_perm(user, queryset, role): """Filter a queryset. Main authorization business logic goes here. """ # Called outside of view if user is None: # TODO: I think this is used if a user isn't logged in and hits our endpoints which is a problem return queryset # Must be logg...
22,229
def generate_copies(func, phis): """ Emit stores to stack variables in predecessor blocks. """ builder = Builder(func) vars = {} loads = {} # Allocate a stack variable for each phi builder.position_at_beginning(func.startblock) for block in phis: for phi in phis[block]: ...
22,230
def poll_and_notify(): """ Check for updated results, and send a notification if a change is detected. """ # query the API for the latest result new_results = get_status(MYSEJAHTERA_USERNAME, MYSEJAHTERA_PASSWORD) # load the previous results from file try: with open(RESULTS_FILENAME)...
22,231
def calculate_dv(wave: Sequence): """ Given a wavelength array, calculate the minimum ``dv`` of the array. Parameters ---------- wave : array-like The wavelength array Returns ------- float delta-v in units of km/s """ return C.c_kms * np.min(np.diff(wave) / wav...
22,232
def check_link_errors(*args, visit=(), user="user", **kwargs): """ Craw site starting from the given base URL and raise an error if the resulting error dictionary is not empty. Notes: Accept the same arguments of the :func:`crawl` function. """ errors, visited = crawl(*args, **kwargs) ...
22,233
def cart3_to_polar2(xyz_array): """ Convert 3D cartesian coordinates into 2D polar coordinates. This is a simple routine for converting a set of 3D cartesian vectors into spherical coordinates, where the position (0, 0) lies along the x-direction. Parameters ---------- xyz_array : ndarray ...
22,234
def deploy_release(rel_id, env_id): """deploy_release will start deploying a release to a given environment""" uri = config.OCTOPUS_URI + "/api/deployments" r = requests.post(uri, headers=config.OCTOPUS_HEADERS, verify=False, json={'ReleaseId': rel_id, 'EnvironmentId': env_id}) ret...
22,235
def create_static_route(dut, next_hop=None, static_ip=None, shell="vtysh", family='ipv4', interface = None, vrf = None): """ To create static route Author: Prudvi Mangadu (prudvi.mangadu@broadcom.com) :param dut: :param next_hop: :param static_ip: :param shell: sonic|vtysh :param family...
22,236
def _markfoundfiles(arg, initargs, foundflags): """Mark file flags as found.""" try: pos = initargs.index(arg) - 1 except ValueError: pos = initargs.index("../" + arg) - 1 # In cases where there is a single input file as the first parameter. This # should cover cases such as: ...
22,237
def part_a(puzzle_input): """ Calculate the answer for part_a. Args: puzzle_input (list): Formatted as the provided input from the website. Returns: string: The answer for part_a. """ recipes_to_make = int(''.join(puzzle_input)) elf_index_1 = 0 elf_index_2 = 1 recip...
22,238
def _CompareFields(field, other_field): """Checks if two ProtoRPC fields are "equal". Compares the arguments, rather than the id of the elements (which is the default __eq__ behavior) as well as the class of the fields. Args: field: A ProtoRPC message field to be compared. other_field: A ProtoRPC mess...
22,239
def classpath_dest_filename(coord: str, src_filename: str) -> str: """Calculates the destination filename on the classpath for the given source filename and coord. TODO: This is duplicated in `COURSIER_POST_PROCESSING_SCRIPT`. """ dest_name = coord.replace(":", "_") _, ext = os.path.splitext(src_fi...
22,240
def loadtxt_rows(filename, rows, single_precision=False): """ Load only certain rows """ # Open the file f = open(filename, "r") # Storage results = {} # Row number i = 0 # Number of columns ncol = None while(True): # Read the line and split by commas ...
22,241
def create_signal(frequencies, amplitudes, number_of_samples, sample_rate): """Create a signal of given frequencies and their amplitudes. """ timesamples = arange(number_of_samples) / sample_rate signal = zeros(len(timesamples)) for frequency, amplitude in zip(frequencies, amplitudes): signa...
22,242
def serp_goog(q, cx, key, c2coff=None, cr=None, dateRestrict=None, exactTerms=None, excludeTerms=None, fileType=None, filter=None, gl=None, highRange=None, hl=None, hq=None, imgColorType=None, imgDominantColor=None, imgSize=None, imgType=None, linkSite=None, lowRa...
22,243
def get_git_revision(): """ Get the number of revisions since the beginning. """ revision = "0" if os.path.isdir(os.path.join(basedir, '.git')): try: proc = subprocess.Popen( ['git', '-C', basedir, 'rev-list', '--count', 'HEAD'], stdout=subprocess....
22,244
def get_wiki_modal_data(term): """ runs the wikiperdia helper functions and created the wikipedia data ready for the modal """ return_data = False summary_data = get_wiki_summary(term=term) related_terms = get_similar_search(term=term) if summary_data: return_data = { ...
22,245
def format_taxa_to_js(otu_coords, lineages, prevalence, min_taxon_radius=0.5, max_taxon_radius=5, radius=1.0): """Write a string representing the taxa in a PCoA plot as javascript Parameters ---------- otu_coords : array_like Numpy array where the taxa is positioned li...
22,246
def _get_symbols_from_args(args: argparse.Namespace) -> List[icmsym.Symbol]: """ Get list of symbols to extract. """ # If all args are specified to extract only one symbol, return this symbol. if args.symbol and args.exchange and args.asset_class and args.currency: return [ icmsy...
22,247
def compute_heading(mag_read): """ Computes the compass heading from the magnetometer X and Y. Returns a float in degrees between 0 and 360. """ return ((atan2(mag_read[1], mag_read[0]) * 180) / pi) + 180
22,248
def data_loader(filename, input_directory, input_directory_processed, fs_resampled, p_and_t_waves=False): """Convert data and header_data to .npy and dict format.""" # Dataset lookup lookup = {'A': 'A', 'Q': 'B', 'I': 'C', 'S': 'D', 'H': 'E', 'E': 'F'} # Get datset dataset = lookup[filename[0]] ...
22,249
def generate_all_commands( configs_path, commands_file, n_repeats, row_wise=True, optimize_access=True ): """ Parameters: row_wise: if True, commands are generated s.t. all configs (columns) are evaluated for one dataset (rows) first before moving on to the next dataset. If False, all datase...
22,250
def ConvertTrieToFlatPaths(trie, prefix=None): """Flattens the trie of paths, prepending a prefix to each.""" result = {} for name, data in trie.items(): if prefix: name = prefix + '/' + name if len(data) != 0 and not 'results' in data: result.update(ConvertTrieToFlatPaths(data, name)) el...
22,251
def get_root_version_for_subset_version(root_dataset_path: str, sub_dataset_version: str, sub_dataset_path: MetadataPath ) -> List[str]: """ Get the versions of the root that contains the ...
22,252
def tojson(input, pretty, echo, strip_whitespace, strip_namespace, strip_attribute, **kwargs): """ Converts the XML input to JSON output. Requires valid input. """ # output = xml2json.json2xml(input) if not input: input = '-' with click.open_file(input, mode='rb') as f: xmlstrin...
22,253
def subject() -> JsonCommandTranslator: """Get a JsonCommandTranslator test subject.""" return JsonCommandTranslator()
22,254
def acquire(arn: Optional[str]): """Aquire SUDO privileges. This requires that the AWS_SUDO_RULE_ARN environment variable be set. If the system was using environment variables they will be lost. It is recommended that the credentials file be used for standard credentials. """ if not arn: ...
22,255
def accuracy(output, target, cuda_enabled=True): """ Compute accuracy. Args: output: [batch_size, 10, 16, 1] The output from DigitCaps layer. target: [batch_size] Labels for dataset. Returns: accuracy (float): The accuracy for a batch. """ batch_size = target...
22,256
def save_message(my_dict): """ Saves a message if it is not a duplicate. """ conn = sqlite3.connect(DB_STRING) # Create a query cursor on the db connection queryCurs = conn.cursor() if my_dict.get('message_status') == None: my_dict['message_status'] = "Unconfirmed" ...
22,257
def write_feats_space(fpath): """ Writes the features configuration in *fpath*. Args: fpath (str): Path to write Returns: None """ with open(fpath, 'w') as file: writer = csv.writer(file) writer.writerow(['feature', 'normalized']) for f in Config.include...
22,258
def getKFolds(train_df: pd.DataFrame, seeds: List[str]) -> List[List[List[int]]]: """Generates len(seeds) folds for train_df Usage: # 5 folds folds = getKFolds(train_df, [42, 99, 420, 120, 222]) for fold, (train_idx, valid_idx, test_idx) in enumerate(folds): tr...
22,259
def redownload_window() -> str: """The number of days for which the performance data will be redownloaded""" return '30'
22,260
def p_addtotals_opt(p): """wc_string : ADDTOTALS_OPT EQ value""" p[0] = ParseTreeNode('EQ', raw='assign') p[1] = ParseTreeNode('OPTION', raw=p[1]) if p[1].raw in ['row', 'col']: p[3].role = 'VALUE' p[3].nodetype = 'BOOLEAN' if p[1].raw in ['fieldname', 'labelfield']: p[3].rol...
22,261
def _write_snapshot(timewsync_data_dir: str, monthly_data: Dict[str, str]) -> None: """Creates a backup of the written files as a tar archive in gz compression. Takes the file name specified in the timewsync config, defaults to 'snapshot.tgz'. Args: timewsync_data_dir: The timewsync data directory...
22,262
def clean_flight_probs(flight_probs: np.ndarray, rng: np.random.Generator) -> np.ndarray: """ Round off probabilities in flight_probs to 0 or 1 with random bias of the current probability :param flight_probs: a vector of inclusion probabilities after the landing phase :param rng: a random number genera...
22,263
def file_scan_validation(file): """ This validator sends the file to ClamAV for scanning and returns returns to the form. By default, if antivirus service is not available or there are errors, the validation will fail. Usage: class UploadForm(forms.Form): file = forms.FileField(vali...
22,264
async def question(session: AskSession): """ Ask user for his answer on which LeetCode problem he whats to anticipate. """ return await session.prompt( message="Enter the problem URL from LeetCode site: ", validator=LeetCodeUrlValidator(session) )
22,265
def mongo_instance(instance_dict, ts_dt): """An instance as a model.""" dict_copy = copy.deepcopy(instance_dict) dict_copy["status_info"]["heartbeat"] = ts_dt return Instance(**dict_copy)
22,266
def remove(path, force=False): """ Remove the named file or directory Args: path (str): The path to the file or directory to remove. force (bool): Remove even if marked Read-Only. Default is False Returns: bool: True if successful, False if unsuccessful CLI Example: ....
22,267
def get_conversion_option(shape_records): """Prompts user for conversion options""" print("1 - Convert to a single zone") print("2 - Convert to one zone per shape (%d zones) (this can take a while)" % (len(shape_records))) import_option = int(input("Enter your conversion selection: ")) return import...
22,268
def main(flags=None): """ Script main function """ if not flags: flags = sys.argv module_name = flags[0] module_args = flags[1:] log(logging.INFO, DataCategory.PUBLIC, "Read parameters...") # construct the argument parser parser = get_arg_parser() args = parser.parse_args(modu...
22,269
def base_conditional(Kmn, Lm, Knn, f, *, full_cov=False, q_sqrt=None, white=False): """ Given a g1 and g2, and distribution p and q such that p(g2) = N(g2;0,Kmm) p(g1) = N(g1;0,Knn) p(g1|g2) = N(g1;0,Knm) And q(g2) = N(g2;f,q_sqrt*q_sqrt^T) This method computes the mean and (co)v...
22,270
def find_shortest_dijkstra_route(graph, journey): """ all_pairs_dijkstra_path() and all_pairs_dijkstra_path_length both return a generator, hense the use of dict(). """ all_paths = dict(nx.all_pairs_dijkstra_path(graph)) all_lengths = dict(nx.all_pairs_dijkstra_path_length(graph)) if len(a...
22,271
def product_consec_digits(number, consecutive): """ Returns the largest product of "consecutive" consecutive digits from number """ digits = [int(dig) for dig in str(number)] max_start = len(digits) - consecutive return [reduce(operator.mul, digits[i:i + consecutive]) for i in ra...
22,272
def alpha_161(code, end_date=None, fq="pre"): """ 公式: MEAN(MAX(MAX((HIGH-LOW),ABS(DELAY(CLOSE,1)-HIGH)),ABS(DELAY(CLOSE,1)-LOW)),12) Inputs: code: 股票池 end_date: 查询日期 Outputs: 因子的值 """ end_date = to_date_str(end_date) func_name = sys._getframe().f_code.co_name ...
22,273
def log_info(who, text): """Helper logging abstract to be redone later.""" print datetime.datetime.utcnow(),\ '{} {}'.format(who, current_process().pid),\ text
22,274
def WeightedCrossEntropyLoss(alpha=0.5): """ Calculates the Weighted Cross-Entropy Loss, which applies a factor alpha, allowing one to trade off recall and precision by up- or down-weighting the cost of a positive error relative to a negative error. A value alpha > 1 decreases the false negative co...
22,275
def expand_stylesheet(abbr: str, config: Config): """ Expands given *stylesheet* abbreviation (a special Emmet abbreviation designed for stylesheet languages like CSS, SASS etc.) and outputs it according to options provided in config """ return stringify_stylesheet(stylesheet_abbreviation(abbr, ...
22,276
def generate_legacy_dir(ctx, config, manifest, layers): """Generate a intermediate legacy directory from the image represented by the given layers and config to /image_runfiles. Args: ctx: the execution context config: the image config file manifest: the image manifest file layers: the ...
22,277
def workflow_key(workflow): """Return text search key for workflow""" # I wish tags were in the manifest :( elements = [workflow['name']] elements.extend(workflow['tags']) elements.extend(workflow['categories']) elements.append(workflow['author']) return ' '.join(elements)
22,278
def get_logits(input_ids,mems,input_mask,target_mask): """Builds the graph for calculating the final logits""" is_training = False cutoffs = [] train_bin_sizes = [] eval_bin_sizes = [] proj_share_all_but_first = True n_token = FLAGS.n_token batch_size = FLAGS.batch_size features =...
22,279
def serve_protocols(environ, start_response): """Serve a list of all protocols. """ status = '200 OK' response_headers = [('Content-type', 'text/html')] start_response(status, response_headers) repo = os.path.join(APP_ROOT, 'storage') protocols = [f_name for f_name in os.listdir(repo)...
22,280
def download_tar(local_path, dropbox_paths, download_q): """ Downloads files (tar.gz.aes) from dropbox, decrypts them, then extracts the chunks files inside and merges them into single files, finally decrypts the files and builds a bozorth list file. This method is used for charge operations :param...
22,281
def _api_get_scripts(name, output, kwargs): """ API: accepts output """ return report(output, keyword="scripts", data=list_scripts())
22,282
def dump_iowawfo(fn): """A region with the Iowa WFOs""" pgconn = get_dbconn("postgis", user="nobody") df = read_postgis( """ SELECT ST_Simplify(ST_Union(the_geom), 0.01) as geom from cwa WHERE wfo in ('DMX', 'ARX', 'DVN', 'OAX', 'FSD')""", pgconn, geom_col="geom", ...
22,283
def WriteNewIRC(FilePath): """Writes correctly the irc in a .xyz file""" fwrite = open(FilePath.split(".")[0] + "NewIRC.xyz","w") #If a irc reversed is asked, reverse will equal True for key in sorted(DictLines,reverse=Reversed): fwrite.writelines(DictLines[key]) fwrite.close()
22,284
def get_children(key): """ Lists all direct child usages for a name usage :return: list of species """ api_url = 'http://api.gbif.org/v1/species/{key}/children'.format( key=key ) try: response = requests.get(api_url) json_response = response.json() if json_res...
22,285
def test_alias(): """Test alias functionality in help commands.""" from commands import help commands = help.alias() assert 'help' in commands
22,286
def _extend(obj, *args): """ adapted from underscore-py Extend a given object with all the properties in passed-in object(s). """ args = list(args) for src in args: obj.update(src) for k, v in src.items(): if v is None: del obj[k] return obj
22,287
async def test_offers_no_records(http_client): """Request offers for a product is registered, but has no offer records.""" prod_id = await create_product(http_client) await set_reg_token_hash(prod_id) resp = await http_client.get(f"/products/{prod_id}/offers") assert resp.status_code == 200 ass...
22,288
def async_test(func): """ Wrap async_to_sync with another function because Pytest complains about collecting the resulting callable object as a test because it's not a true function: PytestCollectionWarning: cannot collect 'test_foo' because it is not a function. """ # inner import beca...
22,289
def get_logger(lname, logfile): """logging setup logging config - to be moved to file at some point """ logger = logging.getLogger(lname) logging.config.dictConfig({ 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'standard': { ...
22,290
def get_percentiles(data, percentiles, integer_valued=True): """Returns a dict of percentiles of the data. Args: data: An unsorted list of datapoints. percentiles: A list of ints or floats in the range [0, 100] representing the percentiles to compute. integer_valued: Whether or not the values are...
22,291
def estimate_poster_dedpul(diff, alpha=None, quantile=0.05, alpha_as_mean_poster=False, max_it=100, **kwargs): """ Estimates posteriors and priors alpha (if not provided) of N in U with dedpul method :param diff: difference of densities f_p / f_u for the sample U, np.array (n,), output of estimate_diff() ...
22,292
def test(): """Run the unit tests.""" raise SystemExit(helper.test())
22,293
def get_short_topic_name(test_run_name): """Returns the collection name for the DLQ. Keyword arguments: test_run_name -- the unique id for this test run """ return test_run_name[3:] if test_run_name.startswith("db.") else test_run_name
22,294
def cut_in_two(line): """ Cuts input line into two lines of equal length Parameters ---------- line : shapely.LineString input line Returns ---------- list (LineString, LineString, Point) two lines and the middle point cutting...
22,295
def local_input_loop(): """ Initialize the local input channels (fifo and socket). Then poll on those and forward messages to Telegram. """ # Cleanup socket # Use a separate lockfile to avoid locking the socket # If lockfile can be locked, redo the socket # If lockfile can't be locked, e...
22,296
def get_processor(aid): """ Return the processor module for a given achievement. Args: aid: the achievement id Returns: The processor module """ try: path = get_achievement(aid)["processor"] base_path = api.config.get_settings()["achievements"]["processor_base_p...
22,297
def parse_price(price): """ Convert string price to numbers """ if not price: return 0 price = price.replace(',', '') return locale.atoi(re.sub('[^0-9,]', "", price))
22,298
def _validate_keys(connection_string_parts): """Raise ValueError if incorrect combination of keys """ host_name = connection_string_parts.get(HOST_NAME) shared_access_key_name = connection_string_parts.get(SHARED_ACCESS_KEY_NAME) shared_access_key = connection_string_parts.get(SHARED_ACCESS_KEY) ...
22,299