content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def getWebImgType_file(filename):
"""
Get image file type of an image stored in disk. Can be used to verify if an image is available for web.
:param filename: The file you want to verify.
:return: Image file type. If image is invalid, returns False.
"""
data = open(filename,'rb').read(11)
#... | 8e196b94314cc03d724de6844c120f709560502d | 642,207 |
def get_dimension( q ):
""" This function is used to find out the dimension of problem with the help of the q array
since the solution field have one element more which contains the number of unknowns per subcell the dimension
computed by substracting one from the size of the solution list.
"""
siz... | c433fe41ee29da49b348ec7a50983de109125317 | 642,208 |
import requests
import json
def get_token(keyword, timespan):
"""
Retrieves a token from Google Trends, based on the keyword and timespan.
This function is a deritative of a function within Pytrends by
github.com/GeneralMills. Licensed under the Apache license, version 2.0.
Changes made by githu... | 670806ff76689bbe5e20619241f3aefce97bdcde | 642,209 |
def check_reference_positions(reference_sequence: str, positions: list) -> bool:
"""
Takes the aligned reference sequence and the list of parsed positions
and checks to see if there are any dashes at the beginning of the sequence.
If there are, they are removed and the positions are corrected.
Para... | fd42da766f22774317a3e03a015311a66cb98ea3 | 642,210 |
def populate(problem, size):
"""
Create a Point list of length size
"""
population = []
for _ in range(size):
population.append(problem.generate_one())
return population | 46f7b3040f2cf3d2bd3e08cc967f06374cc35453 | 642,212 |
import os
def valgrindify(cmdline):
"""Run a command under valgrind, if $VALGRIND was set."""
valgrind = os.getenv("VALGRIND")
if valgrind is None:
return cmdline
return valgrind + " " + cmdline | 255f2cccc516b5f87380416cfe3ac9a32f98c6b8 | 642,213 |
def getVocab(data):
"""
Get the frequency of each feature in the file named fname.
"""
vocab = {}
for review, _, _, in data:
for sentence in review:
for word in sentence:
vocab[word] = vocab.get(word, 0) + 1
return vocab | 868c9ebffd0bfa16aa43216e8cfa426b594d240d | 642,214 |
def limit(q, lim):
"""Non-MS SQL Server implementation of 'limit'"""
return "SELECT sq.* FROM ({}) sq LIMIT {}".format(q, lim) | a1b78a86679c7e5a68d89af6fa765aae9e6a32d4 | 642,215 |
def create_match_instance_pairs(plant_match_in):
"""
sort match index instances removing ambiguous matches and creating match 'B', 'I' dict
"""
## collect all plant name match instances indices
just_indices = [int(indices) for plant_match_in_set in plant_match_in for indices in plant_match_in_set[1]]
assert le... | a396734c66f91115cd8e04465b0a0f6e34cd1785 | 642,216 |
def _toolkit_get_topk_bottomk(values, k=5):
"""
Returns a tuple of the top k values from the positive and
negative values in a SArray
Parameters
----------
values : SFrame of model coefficients
k: Maximum number of largest positive and k lowest negative numbers to return
Returns
-... | 811d700a9c6d0f465567892783f9ecc1ded3bdec | 642,217 |
def resumePathProcessing():
"""
resumePathProcessing() -> None
Resume path processing.
Use prior to performingmultiple node graph modifications, to avoid repeated path processing.
@return: None.
"""
return None | 1bd308cae1ed644cf9e3a042e6baeea80fc66531 | 642,218 |
import os
import json
def parse_input_graph(file_name, dir_name):
"""
Function: parse_input_graph\n
Parameters: file_name -> graph_input file, dir_name -> directory of the file\n
Returns: UAV_location dictionary and placed list\n
"""
UAV_location = {}
with open(os.path.join(dir_name, file_... | e55534b982db245c5c09b45e9b376bdc3eeb61ea | 642,219 |
import socket
def get_ip_using_standard_if(host='8.8.8.8'):
"""
Gets the ip of the 'standard interface'
Source: https://stackoverflow.com/a/7335145
Args:
host (str): optional ip of a host to connect to. Default is '8.8.8.8'
Returns: own ip address on standard interface
"""
s = so... | 965fb8c19b212b6a5be746c2d5932e55fb951100 | 642,220 |
from datetime import datetime
def load_timestamps(timestamp_file):
"""Load timestamps from file."""
# Read and parse the timestamps
timestamps = []
with open(timestamp_file, 'r') as f:
for line in f.readlines():
# NB: datetime only supports microseconds, but KITTI timestamps
... | 87b6cfab557d097c257a21a01b15473fa01290ff | 642,222 |
import sqlite3
def _get_all_no_id(
cursor,
table_name,
table_id,
print_string,
verbose,
**kwargs,
):
"""Get all elements from a table as a dictionary, excluding id."""
try:
cursor.execute("""SELECT * FROM """ + table_name)
except sqlite3.Error as e:
raise type(e)(
... | 33498c9c78cd1f55099bd386208c37954a1bda56 | 642,223 |
def api_key() -> str:
"""The key for accessing the Shopify API access"""
return '12345a6b7c8d9' | ccd8bb1158790f3f8a5fd209b212d2500e0761bd | 642,224 |
def get_sum(value1, value2):
"""Return the sum of two values."""
return value1 + value2 | b2abe7de3f0b0d842bc901827aeb824aebc5d538 | 642,225 |
def myreplace(astr, thefind, thereplace):
"""in string astr replace all occurences of thefind with thereplace"""
alist = astr.split(thefind)
new_s = alist.split(thereplace)
return new_s | 14f5dc154979ff02de2b664a2333513f15a47564 | 642,226 |
def index():
"""
docstring
"""
return "Bienvenido a la prueba de api rest, intenta /productos" | d3e8efd7716d6170f0757ebf96cf9dc1969d92f3 | 642,227 |
import sys
def get_size(android_size: str):
"""
Compute size in Byte
:param android_size: size in KiB, MiB or GiB
:return: size in Byte
"""
if android_size.isdigit():
return android_size
unit = android_size[-1:]
tsv_size = android_size[:-1]
if unit == "K":
return i... | a63aadbc90d5ce87bc22f50a380f8517f7abd3dd | 642,228 |
def total_hazard_perceived_by_town(hazards: list, town_id: int, facilities: list) -> int:
"""
For the specified town retrieve the total risk caused by opened facility
:param hazards: list of list, describe every hazard for the couple (town,facility)
:param town_id: the town of interest
:param facil... | 1f3a1da00c84f965b3dcb939c84d4e28fd2462cc | 642,229 |
def requires_logged_in(func):
"""
Decorator which verify that client are logged in
if not but env variables are available
it tries to loggin using them
:param fn: function to decorated
:return: wrapper function
"""
def ret_fn(*args):
"""
wrapper function
:param ar... | 1b6782b69907636bc944af96de09ae70bef2fa87 | 642,230 |
def esc_prefix(is_windows):
"""
When executing on windows it's not necessary to escape the $ for variables
"""
if is_windows:
return ""
return "\\" | b52487e532fca72d7d83ad03b290de883cac9011 | 642,231 |
import collections
def _convert_to_ordered_dict(model_dict):
"""
Convert model dict into orderdict
:param model_dict: model dict
:return:
"""
order_dict = collections.OrderedDict()
for layer_name, layer_para in model_dict.items():
order_dict[layer_name] = layer_para
return orde... | 82d11689975092a5a78883169f29ffa025dce4b9 | 642,232 |
def find_single_number(arr: list[int]) -> int:
"""Finds the single number in a non-empty array of integers where every number appears exactly twice, except for one which appears exactly once.
Complexity:
Time: O(n)
Space: O(1)
Args:
arr: array of numbers with all but a single eleme... | a10f5f8cbb49968073c4a28d4eca883c128fb542 | 642,233 |
def calc_iou(box_a, box_b):
"""
Calculate the Intersection Over Union of two boxes
Each box specified by upper left corner and lower right corner:
(x1, y1, x2, y2), where 1 denotes upper left corner, 2 denotes lower right corner
Returns IOU value
"""
# Calculate intersection, i.e. area of overlap between the 2 ... | c330af6b6b213c5086fa8df079228ee214407455 | 642,234 |
def state_for_postcode(country, postcode, locality):
"""
Uses a simple range check to determine the state
"""
if country == 'AU':
""" Australian states """
if 800 <= postcode < 900:
return 'NT'
if (2600 <= postcode < 2618) or (2900 <= postcode < 2915):
ret... | 28ce1e020471f53df67a2fe5b2b82415330c0843 | 642,236 |
def sql_textify(text, comma=True):
"""Makes an input into a MYSQL format.\n
int's will not have quotes\n
str's will have quotes added\n
commas are also added by default
Args:
text (int/str): the text or int to surrounded in quotes
comma (bool, optional): should a comma be added? Defaults to True.
Returns:
... | 6832f4aa43c44f401ee3e1821d762f0b1938957b | 642,237 |
def LeapYear(year):
"""Leapyear returns 1 if year is a leap year and 0 otherwise. Note that leap years
famously fall on all years that divide by 4 except those that divide by 100 but
including those that divide by 400."""
if year%4:
return 0
elif year%100:
return 1
elif year%400:
return 0
else:
return 1 | a494b28ed7eda9800a9be99edc1149a4421eb318 | 642,238 |
def FormatTimestamp(timestamp):
"""Returns a string representing timestamp in RFC3339 format.
Args:
timestamp: A datetime.datetime object.
Returns:
A timestamp string in format, which is accepted by Cloud Logging.
"""
return timestamp.strftime('%Y-%m-%dT%H:%M:%SZ') | 7c4acf42bf9fbf8151611d63fa6c2f116a121a1b | 642,239 |
def _split_version_id(full_version_id):
"""Return server and version.
Args:
full_version_id: Value in the format that is set in the 'CURRENT_VERSION_ID'
environment var. I.e. 'server:server_version.minor_version'.
Returns:
(server, server_version) tuple, or (None, server_version) if this is the
... | 8c373703a89c5cc4f437e61a0f74a633979df006 | 642,240 |
def _revert(converter,
result,
converted=False,
result_conversion=None,
estimator=None,
**converter_args):
"""
Use the `converter` to convert the given `result` if necessary.
sklearn toolkit produces all its results as numpy format by default.
... | 95ab63fb519ebdf62122407f1f0a0eb9d4b14738 | 642,241 |
def create_cwl_yaml_workflow_schema():
"""Return dummy CWL workflow schema."""
reana_cwl_yaml_schema = """
version: 0.7.2
workflow:
type: cwl
file: main.cwl
outputs:
files:
- foo/bar
"""
return reana_cwl_yaml_schema | d445bff952bfdc2e9d2d8a2df8a7ef9960a74e39 | 642,242 |
def get_eq_equal_mag(cursor,magnitude):
"""Query to get the earth quakes equal to a maginitude """
cursor.execute("SELECT * FROM EARTHQUAKES WHERE mag ="+str(magnitude))
rows = cursor.fetchall()
return rows | 27510f13fcfb4f01de33bf6bb93d586171a6c9ab | 642,243 |
def _g_theta(theta,p):
"""
:param theta: dimensionless electron temperature
:param p: electron power law slope
:return: correction term for power law electron distribution
"""
aa = (6.0 + 15.0 * theta) / (4.0 + 5.0 * theta)
gamma_m = 1e0 + aa * theta
gtheta = ((p-1.0)*(1e0+aa*theta)/((p-... | 65975c654d1eff7efa7c7ae409bde695b9ec4c72 | 642,246 |
from typing import Optional
def recognize_id(id: int) -> Optional[str]:
"""Attempts to recognize what item type an id is"""
if 10000000 < id < 20000000:
return "character"
elif 1000000 < id < 10000000:
return "artifact_set"
elif 100000 < id < 1000000:
return "outfit"
elif 5... | 1486a4a3adae0f284f49b9ea5816fe55ec1362f1 | 642,247 |
def iso_date(s: str) -> str:
"""
Formatiert ds CDC Datum als ISO-Datum. Bsp.: 19690523 -> 1969-05-23
:param s: Datum in Schreibweise YYYYMMDD
:return: Datum in Schreibweise YYYY-MM-DD
"""
# 19690523 -> 1969-05-23
return "%s-%s-%s" % (s[0:4], s[4:6], s[6:]) | 2a3ebc4f3b4118a57d0933b7d91bc908c538681f | 642,248 |
def remove_border_spaces(string):
""" Strips the whitespace borders of a string.
Used inside 'read_config_file' function.
"""
if type(string) != str:
raise TypeError(
"Hey, a non-string object was passed to function "
"'Remove_border_spaces'!")
if string == '':
... | d947f70d80a69e1850c4d53cc8656bec470bd864 | 642,249 |
def metadata_key(config):
"""
Build a key to a file in the 'metadata' directory of the published dataset.
"""
def func(filename) -> str:
return f"{config.s3_publish_key}/metadata/{filename}"
return func | 3bb870841595f0521b0d02968cad655296e604c3 | 642,250 |
def copy_doc_from(obj, append=True):
"""
Decorator that copies the ``__doc__`` string from the specified object ``obj`` to the
decorated function. If the decorated function already has a documentation attached,
``append`` determines whether to append the copied documentation to the existing one or
t... | 4b21729bbff6a0242038b90f1f867245fdd075b6 | 642,251 |
import os
def _get_fields(filename):
"""Break CRDS-style filename down into: path, underscore-separated-parts, extension."""
path = os.path.dirname(filename)
name = os.path.basename(filename)
name, ext = os.path.splitext(name)
parts = name.split("_")
return path, parts, ext | 6e2547eeef4bd3c736ac893d27aae9e86c8d512e | 642,252 |
import math
def prime_numbers_reference(num):
"""A reference implementation of a prime number generator.
For num=10**7 it is 105 times slower than CPrime.prime_numbers
on a CPU Intel i5 3335S @ 2.7GHz and 4 physical cores.
More over needs much more memory to be allocated in advance, on
an 8Gb ma... | 831a72ff99a8eece45e47ac1ac331177dbe8ee66 | 642,253 |
def cpDelMac(clearpassObj, macAddress):
""" Aruba Clearpass method to delete Mac Address for blocking network access """
return clearpassObj.delete("/endpoint/mac-address/" + macAddress) | 0d0407ca1bba80f868ab6b8345e2204e5efaf5a0 | 642,254 |
def _tostr(x):
"""
Convert a value to the native string format.
Parameters
----------
x : str or bytes
value to convert to a native string.
Returns
-------
str
"""
if isinstance(x, bytes):
return x.decode()
else:
return str(x) | de8705895bc528b755a3c809b34fd24801a23999 | 642,255 |
def get_discont_val(t1, t2, _para):
"""
a general function to compute the discout value
input: travel time of the two companies
"""
val = _para.discount_ratio*(t1 - t2)
if val < 0:
input(
"The travel time of company op2 is greater than op 1, need to further examine")... | 10077fe6c10a9032b0c3e24beaf00844cb61ae8a | 642,256 |
import sqlite3
def db_connector(filepath):
"""
Creates an SQLite server from the given filepath
:param filepath: the location of the SQLite database
:return: An SQLite connection
"""
print("Initiating connection to database")
return sqlite3.connect(filepath) | b207321f32c7a57c8d52a382b851835cef8375af | 642,257 |
from pathlib import Path
import json
def load_params(model_dir: Path) -> dict:
"""
Load params from json
Args:
model_dir (Path): model directory path
Returns:
dict: dictionary of params
"""
file_name = model_dir / 'params.json'
with open(file_name, 'r') as f:
para... | 40d146ed612f5fc39ef870367f4f626e2a0da3c4 | 642,258 |
def count(rdd, field_name):
"""Perform a word count on the specified field of the input rdd by tokenizing the text.
Return an rdd of dicts with "word" and "count" fields.
"""
# Split the text in the records into lowercase words
words = rdd.flatMap(lambda r: r[field_name].lower().split())
# Gen... | 2bf6a8bcd53ce7ca2a7280401b03e5bff330395c | 642,259 |
def shell_quote(s):
"""Given bl"a, returns "bl\\"a".
Returns bytes.
"""
if not isinstance(s, bytes):
s = s.encode('utf-8')
if any(c in s for c in b' \t\n\r\x0b\x0c*$\\"\''):
return b'"' + (s.replace(b'\\', b'\\\\')
.replace(b'"', b'\\"')
... | 1152d648ced9a3c7881dc5114cd5d76bf0af3f7a | 642,260 |
from typing import Dict
from typing import Any
from typing import Union
from typing import List
def get_kernel_shape(attributes: Dict[str, Any]) -> Union[List[float], None]:
"""
Get the kernel shape from a dictionary of a model's attributes
:param attributes: a dictionary of a model's attributes
:ret... | 29864e00ebd9e20dcfed94c6309f50c7d0eff7d4 | 642,261 |
import os
def check_rule(ui, repo, modified, basedir, output, inputs):
"""Verify that the output is newer than any of the inputs.
Return (status, stamp), where status is True if the update succeeded,
and stamp is the newest time stamp assigned to any file (might be in
the future).
If basedir is ... | f01929027b54aa1ce8d864ff5b638dfa9f2632c0 | 642,262 |
import os
import json
def smart_selection_rules():
"""Return the smart selection roles for the profiles."""
local = os.path.expanduser('~/.pterm.ssr.json')
local_ssr = []
if os.path.isfile(local):
with open(local) as out:
local_ssr = json.load(out)
return local_ssr + [
... | 78da6bbf72ad7b60e9c5ab29abbb26436c33ada7 | 642,264 |
def _create_id(data_set_id, record_id):
"""
The record_ids are not necessarily globally unique, because they're user provided and
are only guaranteed to be unique within a collection. So that we have a unique primary
key we're joining them with a colon.
>>> _create_id('foo', 'bar')
'foo:bar'
... | d6b317bb5366d66fe62b94cdaa324a08fcf697ea | 642,265 |
def pN_factory ( klass , *args ) :
"""Factory for deserialization of simple polynomians
- see Ostap.Math.Chebyshev
- see Ostap.Math.ChebyshevU
- see Ostap.Math.Hermite
- see Ostap.Math.Legendre
- see Ostap.Math.PLegendre
"""
return klass ( *args ) | 4789bbad5e6b76cd9491c1b8c138995ac389f279 | 642,266 |
import os
def from_cwd(filename=""):
"""
Returns the absolute path to a relative `filename` by joining it with
the current working directory.
If the filename starts with the os path separator, it is considered an
absolute path and returned as is.
Args:
filename: The relative filename... | b4addb2765351f56b559be204cdb0802e4351599 | 642,267 |
def all_none(*args):
"""Return True if all arguments passed in are None."""
return all(a is None for a in args) | 5d7c695b64f82f15b86be9cef64430f93ac8e14e | 642,268 |
import gzip
def read_file(filepath):
"""
Read normal or gz file (based on their extension .gz)
"""
data = None
if filepath.endswith(".gz"):
with gzip.open(filepath, "rb") as f:
data = f.read()
else:
with open(filepath, 'r') as myfile:
data = myfile.read(... | 10fcf2abd8fb9a696bfb7206a8dd441d2fe86dc1 | 642,269 |
import re
def mac2int(string):
"""
Convert a mac address in string format into int value
:param string: Should be a string if format
"00:11:22:33:44:55:66"
:return: Integer value of mac address
"""
if not isinstance(string, str):
raise TypeError("Value %s is not a type of string" %... | 8f30c2b983dfc9b5b4ff952e2a2bef5e1e019216 | 642,270 |
import random
def rndChar():
"""随机字母:"""
str = ''
for i in range(4):
str += chr(random.randint(65, 90))
return str | d5f2ac59fa14b3a85428adff55763f935472d506 | 642,271 |
def check_cmaq_units(df, param='O3', aqs_param='OZONE'):
"""Short summary.
Parameters
----------
df : type
Description of parameter `df`.
param : type
Description of parameter `param` (the default is 'O3').
aqs_param : type
Description of parameter `aqs_param` (the defau... | 21b0e187def219cb52b54141c7dbfe6827f1ba0e | 642,272 |
from typing import Optional
from typing import Union
from typing import Dict
from typing import Any
from typing import List
def is_multipart(item: Optional[Union[bytes, Dict[str, Any], List[Any]]]) -> bool:
"""A poor detection if the body should be a multipart request.
It traverses the structure and if it co... | 5b6ce1cbfdecc56e8d8bda156edaaf21957ba211 | 642,273 |
import base64
def _get_bytes_from_pem_file(fpath: str) -> bytes:
"""Returns bytes from a pem file.
"""
with open(fpath, 'r') as fstream:
as_pem = fstream.readlines()
as_b64 = [l for l in as_pem if l and not l.startswith("-----")][0].strip()
as_bytes = base64.b64decode(as_b64)
ret... | d523e9f2baa23a4719d9c7bd79053ed49535b0d6 | 642,274 |
import configparser
def load_settings():
"""
Loading and assigning global variables from our settings.txt file
"""
config_parser = configparser.RawConfigParser()
config_file_path = 'settings.txt'
config_parser.read(config_file_path)
browser = config_parser.get('your-config', 'BROWSER')
... | 2c673fbc2f4ddfe415c34722607356203bcd9df9 | 642,275 |
import math
def _is_external(a, b):
""" Check if blob b is outside blob a
:param a: first blob. This is larger than b.
:param b: second blob. This is smaller than a.
:returns: if b is outside the radius of a
"""
ay, ax, ar = a
by, bx, br = b
d = math.sqrt((ax - bx)**2 + (ay - by)**2)... | b5ff7c93f8bd0929404105432cce817de4501c17 | 642,277 |
def find_complete_faces(indices, faces):
"""
Given a set of vertices, find the ones that make complete faces.
Parameters
----------
indices : list of integers
indices to connected vertices
faces : list of lists of three integers
the integers for each face are indices to vertices... | 78097e380ffec9326f892e2d54f9722e811af907 | 642,278 |
import subprocess
def assemble_email(to_address, from_address, subject, body_string):
""" Construct an email the hard way
"""
retval = ""
retval += "To: {}\n".format(to_address)
retval += "From: {}\n".format(from_address)
retval += "Subject: {}\n".format(subject)
retval += 'Content-Type:... | 0a201f8ea771608722f893c2c0859877a15c613c | 642,279 |
import re
def year_grabber(year_str: str):
"""
From a string containing a year, possibly more than one, pull out the first.
>>> year_grabber("1948194819491949195019501951")
'1948'
>>> year_grabber("abs1987")
'1987'
>>> year_grabber("1987a")
'1987'
>>> year_grabber("<y>1916̵... | dbb429f74ebfabd7715be0298099f7be0ddbfec1 | 642,280 |
def subsumed(id, s_visited_id, STKMAX):
"""Helper for is_term_id and is_surv_id
---
If id is (q,in_str,stk_str)
and exists a member (q1,in_str1,stk_str1) in s_visited_id
then subsumed is True if q==q1, in_str==in_str1
and stk_str1 starts with st... | 6f4e6acf398ba966037032b33f70028e013e28e6 | 642,281 |
def get_number(s):
""" Check that s is number
If s is a number, returns it as a float. If not, returns s without modification.
Inputs:
s - An input string or number
Outputs:
value - Either float(s) or False if s cannot be cast to float
"""
try:
return float(s)
e... | 0df8f0225b443079670c83a5dee9e3b56787aeb8 | 642,282 |
import re
def get_github(text):
"""
Fetches GitHub and GitHub's gist urls from the text obtained from the resume.
:param text:(unicode string) parsed text from the resume.
:return: a list of GitHub and Gist urls
"""
github_url = []
githubs = re.findall('.*[\w\.-]*github[\w\.-]*.*', text)
... | 1a9ad9af2298bbbcb3a49cc340337e18080890bf | 642,283 |
import re
def if_title_invalid_symbol_use(title):
"""If the title has an invalid name besides spaces, return True"""
title_length = len(title)
if title_length==0: #To prevent out of bounds
return True
#Symbols not allowed at all:
char_blacklist = [ #Characters not possible in a title
... | 5e61f117d482f346c37499f98ec659008f8a8d5a | 642,284 |
from typing import Optional
import os
def _read_file(src_path: Optional[str] = None) -> str:
"""Returns the text content of the src_path if it is a file
Args:
src_path (Optional[str], optional): The path to the file. Defaults to None.
Returns:
str: The text content of the file
"""
... | da2b71aa91a44bca75dba3f5a8398d31477e7421 | 642,285 |
def _get_dns_server_ip():
"""
Get the dns server ipv4
Returns
-------
str: The dns server ipv4 address., default is retrieved from /etc/resolv.conf.
"""
resolv_file = '/etc/resolv.conf'
nameserver = '8.8.8.8'
with open(resolv_file, 'r') as rf:
for rf_line in rf:
... | e0af29b0518088ea0a5a71f2fc4c3528111bc251 | 642,286 |
def tamPeriodo (denominador):
"""Esta función calcula el tamaño del periodo de
la fracción 1/denominador"""
tam=0
"""numerador, denominador y resto"""
numerador=1;
paso=(numerador,0)
listaPasos=[]
parar=False
# Bucle, mientras que no encontremos un periodo
while parar==False:
... | 3cf56031672b78cd41ae5a6fc2d97bda0cfe1422 | 642,287 |
def get_files(folder, restrict_to_folder=False):
"""
Gets all files in a folder + subfolders
:param folder: pathlib.Path object
:param restrict_to_folder: bool. If false also
the files in the subdirectories are found
"""
if not restrict_to_folder:
return [x for x ... | ff65b266bd7970e9086a6be930dfc8064fb63c88 | 642,288 |
def post_process_human_data(human_data):
"""Remove unwanted space and solves double shad(ཉིས་ཤད་) split cases
Args:
human_data (str): human segmented data
Returns:
str: clean human segmented data
"""
human_data = human_data.replace('། །', '།།')
human_data = human_data.replace(... | ea4624b47a068d2de2b7f85e0bf8132bbb91e06e | 642,289 |
import argparse
def add_go_args():
"""
Run GO analysis
"""
parser = argparse.ArgumentParser(description='hiseq go -i gene.xls -g dm6 -o output')
parser.add_argument('-a', '--all',
help='for all siginificantly changed genes, require "sig" in header, ignore: -i')
parser.add_argument('-i'... | 4ea70cb6df07db8031a183476e9c7c36e2f90e2b | 642,290 |
from typing import List
from typing import Dict
def filter_by_keywords(results: List[Dict], keywords: Dict) -> List[Dict]:
"""
Filter the search results according to the given keywords
Args:
results (List): a list of retrieval results.
keywords (Dict): a dict containing keywords to be sel... | c9ecb9cff4d9023d15d3c258207a4df738829170 | 642,291 |
import click
def users_flag(
help_message,
long="--users",
name="users",
show_default=True,
):
"""
Users flag standard definition.
Use as a decorator for commands.
"""
return click.option(
long,
name,
is_flag=True,
default=False,
show_defaul... | 2024295643436dd3b6ae795bacc62496998ac79a | 642,292 |
import random
def generate_random_permutation(n):
"""
Generate a random length n permutation (element of :math:`S_n`).
:param n: Length of permutation.
:return: Permutation in one-line notation (length n tuple of the numbers 0, 1, ..., n-1).
"""
# Knuth shuffle
array = list(range(n))
... | e47e9f5861661c290af9072e420c90696eb00d1a | 642,293 |
def replace_extension(name: str, new_extension: str) -> str:
"""
Replaces the content after the last '.' with the <new_extension>
:param name:
:param new_extension:
:return:
"""
dot_index = name.rfind(".")
return name[:dot_index + 1] + new_extension | 6bf518c1647220484ce006eec179616085a11210 | 642,294 |
def tempo(msg):
"""Returns the usec tempo value from a tempo meta message."""
return (msg[3] << 16) + (msg[4] << 8) + msg[5] | 0b282dec32180c991513f32a664352594bb9ba29 | 642,295 |
def load_wordlist(filename):
"""Load a list of word from a file (one word per line)"""
words = []
with open(filename, 'r') as f:
for line in f:
words.append(line.strip().lower())
return words | d2fef472ad7cb5a7c77d614183f4a47970fff38e | 642,296 |
import json
def __convert_json(string):
""" Converts a string into JSON format. If the conversion fails,
returns None.
"""
try:
return json.loads(string)
except:
return None | e6d5d6c848a42d1fe5e722d1ae3d1ae8cf429df3 | 642,297 |
def divisors_to_string(divs):
"""
Convert a list of numbers (representing the orders of cyclic groups
in the factorization of a finite abelian group) to a string
according to the format shown in the examples.
INPUT:
- ``divs`` -- a (possibly empty) list of numbers
OUTPUT: a string represe... | 10d236d585c59d25661300d737940485a0398124 | 642,298 |
def _func_dict_wrapper(func):
"""
Wrapper for handling {'col':func}
"""
def _wrapped(group, *args, **kwargs):
res = {}
for col, f in list(func.items()):
res[col] = f(group[col], *args, **kwargs)
return res
return _wrapped | 2d140aa3e0941344bd29a07c2772f0834e1e3970 | 642,299 |
import os
def image(img_src):
"""Renders an image.
:param img_src: Image filename.
:type img_src: str
:return: Template function that accepts a max pixel width integer and returns HTML.
:rtype: function
"""
# Convert absolute path to relative path, since a browser won't be able to grab a... | 065e7a0749d6ea97e92610df598de2700305ef2d | 642,300 |
def get_def_class(word):
"""
get_def_class()
Purpose: Checks for a definitive classification at the word level.
@param word. A string
@return 1 if the word is a test term,
2 if the word is a problem term,
3 if the word is a treatment term,
0 ... | 403ca0f45c61f00c3af7133bd2ce6f86387f01ab | 642,301 |
def validate_font_size(size):
"""
Returns whether or not given size is an acceptable font size.
"""
try:
size = int(size)
except:
return False
return 0 < size < 70 | a7772e1124ac01df056e25d62e6be3368cecf2a8 | 642,303 |
def logging_name(obj):
"""Get full path of the class
Args:
obj (:obj:`class`): A class object
"""
return obj.__class__.__module__ + '.' + obj.__class__.__name__ | ab07eef58ee6d02233c81bc08050052ce78099ed | 642,304 |
def to_lowercase(text):
"""
Transform all characters to lowercase
:param text: input text
:return: transformed text
"""
return text.lower() | 8978f6846211570a95235c297093c1e7e0728f57 | 642,305 |
import collections
def load_run(path):
"""Loads run into a dict of key: query_id, value: list of candidate doc ids."""
# We want to preserve the order of runs so we can pair the run file with the
# TFRecord file.
run = collections.OrderedDict()
with open(path) as f:
for i, line in enumerate(f):
q... | 8ec3fc1e465c558acf274c2f2bd8cdb4ea8f6292 | 642,306 |
def read_byte(file):
""" Read a byte from file """
out = ord(file.read(1))
return out | 8d7bd314df6282bdb1ded0f07c05de844f8f4eac | 642,307 |
import os
def get_css_filepaths(dependency_bundle, dependency_dir):
"""Gets dependency css filepaths.
Args:
dependency_bundle: dict(str, list(str) | str). The dict has three keys:
- 'js': List of paths to js files that need to be copied.
- 'css': List of paths to css files tha... | 3597a7aa32a9d3b312fd344cc0f8352614bbf194 | 642,308 |
def find_colours(shapes):
""" Takes a list of shapes with cells (y, x, colour) and finds their common and uncommon colours.
Note that uncommon colours are a nested list, where each nested list corresponds to uncommon colours
of a particular shape - different shapes could have different uncommon colours.
... | 9b4fca558d8e140a6e1c34e0ca82886d41c4fb76 | 642,309 |
def get_HNF_diagonals(n):
"""Finds the diagonals of the HNF that reach the target n value.
Args:
n (int): The target determinant for the HNF.
Retruns:
diags (list of lists): The allowed values of the determinant.
"""
diags = []
for i in range(1,n+1):
if... | 01c46de6db5cbf70f0a431b7f06aba2a67c6f062 | 642,310 |
from typing import List
from typing import Tuple
from typing import Any
def filter_tuple_list(include_list: List[int],
tuple_list: List[Tuple[Any, ...]]) -> \
List[Tuple[Any, ...]]:
"""Filter tuples of integers by include_list.
Filters tuple_list to include only the tuples that ... | 81d746b78d097460758332c4ba44df8b341da737 | 642,311 |
from datetime import datetime
def get_date_time() -> str:
"""get the current system date time
Args:
None
Returns:
(str): date time in the format of Y-m-d-H-M-S
"""
now = datetime.now()
return now.strftime("%Y-%m-%d-%H-%M-%S") | f5edfb2f3416c8837137c7daf6093584df5e0264 | 642,312 |
def file_extension(filename):
"""
Get file extension from filename
"""
return filename.rsplit('.', 1)[1].lower() | 3b9a5de023e28aa145625df3f3a54db253b4c4eb | 642,314 |
def version_diff(version1, version2):
"""Return string representing the diff between package versions.
We're interested in whether this is a major, minor, patch or 'other'
update. This method will compare the two versions and return None if
they are the same, else it will return a string value indicati... | 57bc2c607c7a98d1f4783dfffe54eb7c08612297 | 642,315 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.