content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def remove_dump_skills(skills_df):
"""This function is used to remove dump skills extracted from Dobie"""
remove_skills = skills_df.loc[~skills_df['skill'].isin(
['Assurance', 'LeSS', 'Computer Science', 'Development', 'Programming', 'BDD', 'TDD', 'Developer',
'Software Engineer', 'Design', 'Te... | 2718e9a9f75787f353a37eccfaab4c9579b6ac98 | 51,155 |
import re
def toIsoDateTime(value):
""" Convert a datetime to an ISO8601 formatted dateTime string.
:param value: the dateTime to convert
:returns: an ISO8601 formatted string version of the dateTime
"""
rv = value.isoformat()
if value.tzinfo is None:
rv += 'Z'
else:
# rep... | 1e029fb6b6ad60cb20bb6cc134c448d4a4f89a15 | 51,156 |
import re
def find_valid_dates(text):
"""Searches for valid dates in a given string.
Args:
text: The string to be searched.
Returns:
dates: A list of tuples containing the components of any valid date
found within the string.
"""
valid_date = re.compile(r"([0-3]\d)(/... | 6a496dff4c73c124c723f28b1b7ce3bbe28960f8 | 51,157 |
def read_sequence(filepath, labels=True):
"""
Return the list of protein sequences and cleavage sites from datapath.
The data file must strictly follow the following pattern:
- first line is a description of the sequence
- second line is the sequence itself
- third line is a list of chars S, C,... | 7df9a6ed25dc9b3f6d9005d84ddc375f30a55da4 | 51,158 |
def clean_for_viaf(text):
"""
assumes cleaned author form (see supporting_functions.clean_authors). Removes abbreviations and punctuation
:param text: input
:return: cleaned string
"""
text = text.strip().lower()
text = text.replace(".","")
text = text.replace('"',"")
text = text.sp... | c18abadeae4ebc015030793f64a9babd910a3f1e | 51,159 |
def _min(integers):
"""Returns the minimum of given elements.
Args:
integers: A list of integers. Must not be empty.
Returns:
The minimum integer in the given list.
"""
_ignore = [integers]
return 42 | 4345686783d910ed57c22b863b2f10f53ea07335 | 51,160 |
def penalty_label(dev_measure, dev_fun, value_discount):
"""Penalty label specifying design choices."""
dev_measure_labels = {
'none': 'None', 'rel_reach': 'RR', 'att_util': 'AU', 'reach': 'UR'}
label = dev_measure_labels[dev_measure]
disc_lab = 'u' if value_discount == 1.0 else 'd'
dev_lab = ''
if de... | a2c9bb0c3e5d96ce84a80f500603116cfa0cfc8f | 51,162 |
import sys
import time
def robust_request(twitter, resource, params, max_tries=5):
""" If a Twitter request fails, sleep for 15 minutes.
Do this at most max_tries times before quitting.
Args:
twitter .... A TwitterAPI object.
resource ... A resource string to request; e.g., "friends/ids"
... | a034d9a46ce996b4f3f1f432f45ea7b6d9a1c658 | 51,164 |
def build_risk_assessment_counter(years):
"""Build a risk counter
Args:
years (int): No. of years for analysis
Returns:
risk_counter (list): An empty list for keeping track of bankruptcy events
"""
risk_counter = []
for y in range(years+1):
risk_counter... | 677d548471f7dfa825f92ac948d91e54c4a0d21c | 51,165 |
import requests
import json
def check_api_obj_id_from_name(
jamf_url, object_type, object_name, enc_creds, verbosity
):
"""check if a Classic API object with the same name exists on the server"""
# define the relationship between the object types and their URL
# we could make this shorter with some re... | 3477afeafee04871b201422917101a9301308e9b | 51,166 |
def _retrieve_start_nodes(net, mc):
"""
retrieve nodes with in_degree == 0 as starting points for main path analysis
args:
net: a CitationNetwork object
mc: minimum citations
returns:
list of start nodes in net
"""
return [node for node in net.nodes if (net.in_degree(node... | ff31c50a16a24efa37fbe53f0ba4b7bd9195cb0d | 51,167 |
from typing import List
def get_corpus(documents: List[List[str]]) -> List[str]:
"""Get a list of all of the words in each document (includes duplicates).
Args:
documents (List[List[str]]): List where each element is a list of tokens in a given document.
Returns:
List[str]: List of all o... | 322fca0944b74bfcebf38eff3efe8aa469882e54 | 51,168 |
import json
def format_file_data_into_json(data_file):
"""input: data_file (sequence ids separated by \n)
output: json request structure of gene ids to pass to datasets api
"""
with open(data_file, "r") as f:
content = f.read()
genes = content.strip().split("\n")
return json.dumps({... | 7f646c511a6433f88f59909d281b9ae044e45c82 | 51,169 |
def bottom_up(num_steps: int) -> int:
"""Compute number of steps using a bottom up approach
This iterative appraoch is the best approach. Since it avoids the max
recursion depth and uses O(1) space. Actually, the space complexity is more
complicated. We only use 3 ints but the space needed by those 3 i... | 8645158380859b5fe8a84ee8b5ac5059437ecdb5 | 51,171 |
from typing import Dict
def get_line_from_file(input_filename: str) -> Dict[int, int]:
"""
Read comma seperated integers all on the same line
"""
with open(input_filename) as input_file:
list_of_nums = [int(num) for num in input_file.readline().split(",")]
return {idx: list_of_nums[idx... | 3274eeb5a36f9ad4b460a927396e5f02a91c5c88 | 51,172 |
def destination_index(circle):
"""
>>> destination_index([3, 2, 5, 4, 6, 7])
(2, 1)
>>> destination_index([2, 5, 4, 6, 7, 3])
(7, 4)
>>> destination_index([5, 8, 9, 1, 3, 2])
(3, 4)
"""
val_next = circle[0] - 1
while val_next not in circle:
val_next -= 1
if val_ne... | 2f35c15e4d44f43f9476a1d4b55095cec134dc17 | 51,173 |
def populate_store(store, gc_roots, profiles, paths, requisites=True):
"""Load derivations from nix store depending on cmdline invocation."""
if gc_roots:
store.add_gc_roots()
for profile in profiles:
store.add_profile(profile)
for path in paths:
store.add_path(path)
return s... | bce67f5020db5d83cfa132bc9de79b425f76ccdd | 51,174 |
def sql(request_type, *args):
"""
Composes queries based on type of request.
"""
query = ''
######################
# USER RELATED QUERIES
######################
if request_type == 'GET_ALL_USERS':
query = """ SELECT * FROM Users_Public""" # <--- THIS IS A VIEW
elif reques... | 01604cf6576e9f61823d2777f2cadf90f9727b9e | 51,175 |
def dbfilename(db):
"""Compose filename from database record"""
return db.filename() | 381dd07143eb3cf09c7a0e0310f3b1e887f68135 | 51,177 |
def calc_offset(actpre, actcount):
"""
compute offset in ADC counts from a pressure reading and known
barometric pressure. actpre is in kPa and actcount is corresponding
adc count. Recall:
y = mx + b
where:
y is the pressure in the units of choice
x is the ADC reading
m is the sl... | 3f92d044b15df5dea3cddedfa952e81e396e92ec | 51,178 |
def invalid_expression_kwargs(request):
"""
Fixture that yields mappings that are invalid sets of kwargs for creating a new
:class:`~crython.expression.CronExpression` instance.
"""
return request.param | b15ee90beb61a7fb75cbfbeac9976928cc182f08 | 51,179 |
import os
def files_exist(root, files):
"""Return whether each of the given files exist relative to the given root
path."""
for filename in files:
if not os.path.isfile(os.path.join(root, filename)):
return False
return True | 0f62f8c5a5416b4d0f9c0f1c622369df80d3cf1b | 51,181 |
from typing import List
def rglob_invert(patterns: List[str]) -> List[str]:
"""
Inverts a rglob condition.
"""
result = []
for pattern in patterns:
if pattern.startswith("!"):
result.append(pattern[1:])
else:
assert "!" not in pattern
result.appe... | fb6af4460a13fcc2650e255afedf97e26ee068e6 | 51,182 |
import torch
def default_device() -> str:
"""
:return: the device that should be defaulted to for the current setup.
if multiple gpus are available then will return a string with all of them,
else if single gpu available then will return cuda,
else returns cpu
"""
if not torch... | 7ef23c2c39609d1188fb9f0f2197d0cb44821051 | 51,183 |
import time
def timestamp_from_local(item, pattern):
"""
Converts single local date/time to UNIX-epoch timestamp
"""
return time.mktime(time.strptime(item, pattern)) | 83b42e69a88d4ecbb0fcd8b2604a7d2b5c45a2f8 | 51,184 |
import argparse
def get_args():
"""
Returns parsed arguments.
"""
p = argparse.ArgumentParser(description="Character remapper.")
p.add_argument("input", type=str,
help="string to remap")
p.add_argument("-v", "--verbose", action="store_true", dest="verbose",
help="pro... | 5ace1538d7741f09473f935b4dceff2ea0a088ec | 51,187 |
import os
def make_directory(dirname):
"""Creates one or more directories."""
try:
os.mkdir(dirname)
except:
return False
return True | ab24ad6475bc72145bdb0ef86c539101aa1e29a5 | 51,188 |
import re
def _shell_quote(s):
"""Quote given string to be suitable as input for bash as argument."""
if not s:
return "''"
if re.search(r'[^\w@%+=:,./-]', s) is None:
return s
return "'" + s.replace("'", "'\"'\"'") + "'" | 9cb72e668f2839cbb992012a1973c21156213ae1 | 51,189 |
def dec_to_bin_slow(n):
""" Manually transform a decimal number to its binary representation.
Parameters
----------
n: int
Number in base 10
"""
res = ''
if n < 0:
raise ValueError
if n == 0:
return '0'
while n > 0:
res = str(n % 2) + res
n = n... | c6387f89781ec9d64dd3a3eaec840654ac6ac2e0 | 51,190 |
def get_image_representation(img_x, embedding_net):
"""
Return image representation (i.e., semantic features) for image features given embedding network.
"""
return embedding_net(img_x) | e8bda52c7edd60f77951513a5e078f97de93f623 | 51,192 |
def bbox_size(bbox):
"""Calcs bounding box width and height.
:type bbox: list
:param bbox: bounding box
:rtype: tuple
:return: width and height
"""
x0, y0, x1, y1 = bbox
return abs(x1 - x0), abs(y1 - y0) | 1032ab37e5b05e38f67121e974354ea2fcdf9385 | 51,193 |
def getFeedRate(rpm, chipLoad, numTeeth):
"""
Calculates the feedrate in inches per minute
args:
rpm = spindle speed
chipLoad = chip load (inches per tooth)
numTeeth = number of teeth on tool
"""
feedRate = rpm*chipLoad*numTeeth
return feedRate | e603bdb066a53ec6efd956871a12a08a40eaf971 | 51,194 |
def parse_sheets_for_get_response(sheets: list, include_grid_data: bool) -> list:
"""
Args:
sheets (list): this is the sheets list from the Google API response
include_grid_data (bool): will determine in what manner to parse the response
Returns:
list : The sheets... | d7c2a34d6f2be19e310e6d9e2343acf5e21c43ae | 51,195 |
def birch(V, E0, B0, B1, V0):
"""
From Intermetallic compounds: Principles and Practice, Vol. I: Principles
Chapter 9 pages 195-210 by M. Mehl. B. Klein, D. Papaconstantopoulos paper downloaded from Web
case where n=0
"""
E = (E0
+ 9.0/8.0*B0*V0*((V0/V)**(2.0/3.0) - 1.0)**2
+... | fea738a86f6ed3cfd0be421583c96a63ace548cd | 51,196 |
def stringToWordList(s):
"""Returns t.split() where t is obtained from s.lower() by replacing
every non-letter in this string with a blank. Basically, it returns
a list of the 'words' (sequences of letters) in s.
PreC: s is a string.
"""
t = ''
for c in s.lower():
if c in 'abcdefghi... | 166d192a6e3701431fc00617a9d667f0cf39a63a | 51,198 |
def apply_zero_correction(nodes):
"""
Subtract from each ingress/egress edge to/from the master node (rank 0) the
minimum inbound/outbound weight. We assume this baseline to be due to
synchronisation comms.
"""
def find_min_weight_to_from_zero(nodes):
w_to = 1e8
w_from = 1e8
... | c8703ed7f52ae9ae083562e234f071d4c5e1c2ac | 51,199 |
from typing import Any
import types
import sys
def _is_instrumentable(obj: Any) -> bool:
"""Returns True if this object can be instrumented."""
try:
# Only callables can be instrumented
if not hasattr(obj, "__call__"):
return False
# Only objects with a __code__ member of type CodeType can be in... | 04c78f3924744c25721954947b1c1f224df9dad7 | 51,200 |
def get_genomicsWorkflowbatches(db, query):
"""
Return list of documents from 'genomicsWorkflowbatches' collection based
on query.
"""
return db, query | f43754e9000acfa8e340f8d4cacb7c0f30155641 | 51,202 |
from typing import List
import statistics
def compute_average_memory_usage(memory_data_list: List[float]) -> float:
"""Computes the mean and for a given list of data."""
return statistics.mean(memory_data_list) | 0a13139d3dbe6e6a1ea23c353b680169857dd6ff | 51,203 |
def load_instructions(file):
"""loads instructions from file, stores in cryptic tuples"""
raw = file.readlines()
dirs = [(l[0], int(l[1:])) for l in raw]
return dirs | ff20dde4f02d10e2afc9c862aaba10828bfe88ef | 51,204 |
def reflect_mpo_2site(mpo_2site):
"""Spatial reflection of a 2-site MPO.
"""
return tuple(reversed(mpo_2site)) | 8158a5c5c58f0e96716c3cc1dd26663c08fd6893 | 51,205 |
import os
def file_count(path: str):
"""Return the number of file in a path and subpaths.
Args:
path: a string containing the path in which to count the files.
Returns:
The number of files int the path.
"""
return sum(len(files) for r, d, files in os.walk(path)) | b2119f36c5afe3a0e1f9d1cc2b2bce96344eb97e | 51,207 |
def _split_domain_name(domain_name):
"""ClouDNS requires the domain name and host to be split."""
full_domain_name = "_acme-challenge.{}".format(domain_name)
domain_parts = full_domain_name.split(".")
domain_name = ".".join(domain_parts[-2:])
host = ".".join(domain_parts[:-2])
return domain_na... | 3512c881f81c2cafc5d56564b306e334e63258e0 | 51,208 |
import json
def read2json(file_name):
"""读取json文件,并转换为字典/列表"""
with open(file_name, "r", encoding="utf-8") as fp:
dict = json.load(fp)
print(dict)
return dict | 4f9535a9b7244890313c9bc3432df76d243d5484 | 51,211 |
import math
def manning_equation(hydraulic_radius, manning_coefficient, slope):
"""Manning formula estimating the average velocity of a liquid driven by gravity.
:param hydraulic_radius: hydraulic radius of pipe or channel [m]
:param manning_coefficient: Gauckler–Manning coefficient
:param slope: slo... | 313db8e85c74d2f346b24617ea6228627f589e57 | 51,213 |
def type_with_number(message):
"""
>>> type_with_number('Welcome to Beijing!')
'9352663086023454641'
>>> type_with_number('I miss my laptop.')
'40647706905278671'
>>> type_with_number('!!??.. ,,')
'1111110011'
# Add your doctests below here #
>>> type_with_number('aaaaaaaaAAAAaaaaa... | 46a2c004160b14268fcf72c08693e60918cb3f91 | 51,214 |
def monpow(a, b):
"""Calcul de a à la puissance b
Ici une explication longue de la puissance
d'un nombre :math:`a^b = aa..a` b fois
:param a: la valeur
:param b: l'exposant
:type a: int, float,...
:type b: int, float,...
:returns: a**b
:rtype: int, float
:Exem... | 30f7b5c0ff08082594e2e2cf62509bc1c0742627 | 51,215 |
def weighted_recall(P0, P, Y):
"""
Compute precision without the complex weighting strategy.
"""
m = len(P)
rhos = []
Z = sum(P0[x] for x, _ in Y)
for i in range(m):
rho_i = 0.
for x, fx in Y:
assert fx == 1.
gxi = 1.0 if x in P[i] and P[i][x] > 0 else... | 406f026ca2d98a69470dd7f7bfbde313244c1b89 | 51,216 |
def is_int(val):
"""
Check if val is int
Parameters
----------
val: value to check type
Returns
-------
True or False
"""
if type(val) == int:
return True
else:
if val.is_integer():
return True
else:
return False | 0c33396973ff601deae19e1f47352c45ca3269a6 | 51,217 |
def plural(n):
"""Devuelve s si n!= 1"""
if n != 1:
return "s"
else:
return "" | 5841d42b534cb21d4451b4ec20b92d16c0df12bc | 51,218 |
def readable(filename: str) -> bool:
"""Conditional method to check if the given file (via filename)
can be opened in this thread.
:param filename: name of the file
:type filename: str
:return: true if file can be read, otherwise false
:rtype: bool
"""
try:
handler = open(filena... | 997dbd3f42ed432109169fb98b3d66f3f53341ba | 51,220 |
def get_child_object(obj, child_name):
"""Return the child object
Arguments:
obj {object} -- parent object
child_name {str} -- cild name
Returns:
object -- child object
"""
if hasattr(obj, '__getattr__'):
try:
return obj.__getattr__(child_name)
... | d9404e09cdeaaf755c75675e6c0dc42f5fc7adf2 | 51,221 |
def main(name=None):
"""
Main function.
Example use:
>>> if gv.parallel.main(__name__):
... res = gv.parallel.imap_unordered(f, params)
"""
return name == '__main__' | 5c92e83087ab190c6cca8c958fbb21fa464f07d5 | 51,222 |
import re
def clean(text):
"""Cleans text by: (1) removing obviously non-Coptic text; (2) turning sequences of >=1 newline into a single
newline; (3) turning sequences of >=1 space into a single space; (4) spacing out ., ·, and :
:param text: A string of Coptic text
:return: Cleaned Coptic text
"""
text = text.... | 1088dc0fccb66790f622a05d58027ca3635c8134 | 51,223 |
import subprocess
def perform_whois(target_ip):
"""Method that relies on subprocess to perform a WHOIS lookup on an IP address"""
whois_results = ""
# Set time value for whois call in seconds
time_limit = 180
## Text result of the whois is stored in whois_result...
# Note: encoding='iso-8859... | a04026f29500b349c64a18a22469170f36ae2d4b | 51,224 |
def ping_time_to_distance(time, calibration=None, distance_units='cm'):
"""
Calculates the distance (in cm) given the time of a ping echo.
By default it uses the speed of sound (at sea level = 340.29 m/s)
to calculate the distance, but a list of calibrated points can
be used to calculate the distan... | db8cba30c8d50d301b6a0e15073c527e285d4aa6 | 51,225 |
def from_dict(cls, config):
"""
Helper function to convert a dict to a class
"""
return cls(**config) | cb50159046061f6b2a7ec15302f6df7bd1ed6cb9 | 51,226 |
import os
def extract_directory_name(filename):
"""Extract a directory name from a HTAR `filename` that may contain
various prefixes.
Parameters
----------
filename : :class:`str`
Name of HTAR file, including directory path.
Returns
-------
:class:`str`
Name of a dire... | 19b13a09f5490ceef09cecb35f97a1c06b92ebfd | 51,227 |
def get_distinct_value(df, cols=None):
"""
Return list of distinct values of a dataframe
Parameters
----------
df : dataframe
col: string
Returns
-------
"""
if not cols:
cols = df.columns
return dict(( col, df[col].unique()) for col in ... | 5b34136f986bdef3a1c25fcc7d5eaa42ec407a80 | 51,228 |
import subprocess
def check_node() -> bool:
"""
Check if node is installed on the system.
:return: true if Node is installed on the system.
"""
try:
subprocess.check_output("node -v", shell=True)
return True
except subprocess.CalledProcessError:
return False | 828b8607a13a6085a47849136c56cf6cca890025 | 51,229 |
def pack_str(string):
"""Pack a string into a byte sequence."""
return string.encode() | 5ef0e1f41db1a242c8a67a90d32397f270e2ce4e | 51,230 |
import token
def _get_definition_tokens(tokens):
""" Given the tokens, extracts the definition tokens.
Parameters
----------
tokens : iterator
An iterator producing tokens.
Returns
-------
A list of tokens for the definition.
"""
# Retrieve the trait definition.
defin... | f5ffe1b5757828742777d8678fdbd4738d227aa8 | 51,231 |
def _parse_daily_time(xml_root):
"""Convert contents of <DailyTime> to decimal mask"""
mask = [[0 for h in range(24)] for d in range(7)]
for instance in xml_root.findall("DailyTime/time_instance"):
day = int(instance.find('daily').text) -1
s, e = instance.find('time').text.split('-')
... | 477c6e01a0be20545793a05f6b5aabac78d57f32 | 51,233 |
import os
def traverse_mxd(root_dir, filter=lambda x: x.endswith("mxd")):
"""
Listing of all .mxd file in a given root directory and their sub-directory.
Returns the list of path to the.file mxd.
"""
result = []
for files in os.walk(root_dir):
dir = files[0]
for file i... | 4973c67e84bed0f6f9dfc493b6fb777b80ae77ea | 51,235 |
def _get_ancestors(cube):
"""Extract ancestors from ``filename`` attribute of cube."""
ancestors = cube.attributes['filename'].split('|')
return ancestors | 35e5e70ea3b72e055895a9e66b4eff262ec24163 | 51,236 |
def flatten_test_results(trie, prefix=None):
"""Flattens a trie structure of test results into a single-level map.
This function flattens a trie to a single-level map, stopping when it reaches
a nonempty node that has either 'actual' or 'expected' as child keys. For
example:
.. code-block:: python
{
... | 8204b5a2ccec23cb8323b6709979114fef12633e | 51,237 |
import io
import csv
def csv_loader(text, metadata):
"""A loader for csv text.
"""
with io.StringIO(text, newline='') as csvfile:
dialect = csv.Sniffer().sniff(csvfile.read(2048), delimiters=";, \t")
csvfile.seek(0)
reader = csv.reader(csvfile, dialect)
table = list(reader.... | 23afaaae7b12f06fd62641286c5856fc11556274 | 51,238 |
def calculate_reward(state, v):
"""Calculate reward for player v based on current state."""
status = state.get_status()
r = 0.0
if status == 0:
r = -1.0
elif status == v:
r = 2.0
else:
r = -2.0
return (r, status) | 5d575afbb34b56f8097766f2027596e2b6759238 | 51,239 |
def _sort_func_of_double(point):
"""
double outの時の得点の評価
ダブルアウトの場合ブルは最終手段なのでsepa, fat関係ない
Parameters
-----
point : int
評価する得点
Returns
-----
score : int
得点の評価
"""
#Bullは上がれるならいいが、最終手段
if point == 50:
return 0.1
#ダブルの場合good
if point%... | 9bf7de44573013ef1096edf3d43783b1e1b81779 | 51,240 |
def continue_to_get_objects(vim, token):
"""Continues to get the list of objects of the type specified."""
return vim.ContinueRetrievePropertiesEx(
vim.service_content.propertyCollector,
token=token) | 6f5632a9f7f1ea2da5be76088c5565d101f32114 | 51,241 |
def expandGrid(coord_tuple, base):
"""
If the coordinate pair defining a grid is equal, expand it out so
that the grid is 2 * base wide.
"""
if len(set(coord_tuple)) == 1:
coord_tuple[0] -= base
coord_tuple[1] += base
return coord_tuple | 59cc66cf063bcf952466df2badf6049915c4dfd9 | 51,245 |
def RC(annotation, prediction):
"""
Kendall rank correlation coefficient
"""
number_con = 0.0
number_dis = 0.0
for i in range(0, len(prediction)):
for j in range(i + 1, len(prediction)):
if annotation[prediction[i]][0] < annotation[prediction[j]][0]:
number_co... | d2ab2af4333bc8cfb43b69e5291f7e0002296717 | 51,246 |
def human_readable(solutions):
"""Print letter solution in a human-readable way
Parameters
----------
solutions : pandas.DataFrame
Letter draw best solutions, ordered by number of letters
Returns
-------
str
Human-readable version of `solutions`
"""
result = ""
... | becca40e87db069eaf256e6514f6d47b05e7e1f0 | 51,247 |
from typing import Counter
def label_sizes(pages):
"""
pages: list(Page)
returns: dict[str: int]
For all labels with landings in the page list, assign each label a "size",
from 1 to 5, based on the total number of pages with that label. (A larger
size means the label contains more pages.)
... | 785ac402645eee2ac91a66d538f39e8e64f56fa3 | 51,248 |
import os
import errno
def _open_ipipes(wds, fifos, input_pipes):
"""
This will attempt to open the named pipes in the set of ``fifos`` for
writing, which will only succeed if the subprocess has opened them for
reading already. This modifies and returns the list of write descriptors,
the list of w... | 3239c55a73a551fa061c7a9361190defba3198dd | 51,249 |
import sys
def detect_parity_bit_error(data, parityBit):
"""
Checks (validated) parity bit at the receiver's end.
Returns True if sender has sent correct parity bit,
else returns False.
"""
onesCount = 0
for d in data:
if d == '1':
onesCount += 1
elif d == '0':
... | 2f268ba2ce0ec2d404803a6367b95aeb9517fff0 | 51,250 |
def verify_lc_action(action):
"""
:type: str
:param action: The action parameter to check
:rtype: str
:return: Fix action format
:raises: ValueError: invalid form
"""
action = str(action).lower()
if action not in ['archive', 'expire']:
raise ValueError('"{}" is not a valid ... | ab27d9c52baa2fa24149649e7825e58585c03a20 | 51,251 |
from typing import Iterable
def validation_failed_dict(
items: Iterable,
dict_code: int = 1001,
dict_message: str = 'Validation Failed'
):
"""Generate dict for failed validation in format of DRF-friendly-errors.
Attributes:
items: Items to put into dict. In format: [(code, field, message)... | 01de1c3bc47a4a44005b3e7cd36cf9f5444b7d62 | 51,253 |
def _get_textx_rule_name(parent_rule):
"""
Iterate parent instances until `TextxRule` instance.
"""
while not type(parent_rule).__name__ == "TextxRule":
parent_rule = parent_rule.parent
return parent_rule.name | 9073a82592edadeb43d7fcda91d718203052c1f7 | 51,256 |
def _train_and_score(clf, X, y, train, test):
""" Fit a classifier clf and train set
and return the accuracy score on test set"""
clf.fit(X[train], y[train])
return clf.score(X[test], y[test]) | 886397f99ff3b21cc62100269c9b2c8d5bca8669 | 51,257 |
import sys
import stat
def compare_file_modes(mode1, mode2):
"""Return true if the two modes can be considered as equals for this platform"""
if 'fcntl' in sys.modules:
# Linux specific: standard compare
return oct(stat.S_IMODE(mode1)) == oct(stat.S_IMODE(mode2))
# Windows specific: most o... | 45fd5e8f17c69b20b379a214c1c7d91075e779af | 51,258 |
def skip_dti_tests():
"""XXX These tests are skipped until we clean up some of this code
"""
return True | c00c6f4a67f68a39d982be9de0e2596bce266612 | 51,261 |
import re
def camelize(s):
"""
Convert underscores to camelcase; e.g. foo_bar => FooBar
"""
return s[0].upper() + re.sub(r'_([a-z])', lambda m: m.group(1).upper(), s[1:]) | ff1a6d87f1d10171276be4ae8529850a23a93df9 | 51,263 |
def knothash_reverse(string, start, length):
"""
reverse([0, 1, 2, 3, 4], 0, 3) = [2, 1, 0, 3, 4]
reverse([2, 1, 0, 3, 4], 3, 4) = [4, 3, 0, 1, 2]
reverse([4, 3, 0, 1, 2], 3, 1) = [4, 3, 0, 1, 2]
reverse([4, 3, 0, 1, 2], 1, 5) = [3, 4, 2, 1, 0]
"""
end = (start + length - 1) % len(string)
... | a458859286c520cc142bdc3809c229e576e03392 | 51,264 |
def _compute_pragmatic_meaning_building(building_geometry, building_land_use, buildings_gdf, buildings_gdf_sindex, radius):
"""
Compute pragmatic for a single building. It supports the function "pragmatic_meaning"
Parameters
----------
buildings_geometry: Polygon
building_land_use: Strin... | 4e0077d610aa576934e9eb87f3c352d5303fb15a | 51,265 |
def get_whole_table(table):
"""
Receives a results table
Returns all results in a list of lists with whitespace removed
"""
return [
entry.strip().split()
for line in table.strip().split("\n")
for entry in line.split("|")
if entry.replace("-", "") != "" and entry.stri... | 6f23a851d75540bff0c4643bc27a18ce7494d7f6 | 51,266 |
def format_step(action_id, step, index, notes):
""" reformat a step (dictionary) into a common response format """
return {
'url': '/actions/{}/steps/{}'.format(action_id, step.get('task_id')),
'state': step.get('state'),
'id': step.get('task_id'),
'index': index,
'notes'... | 58dec56de2f554d1736a639b5b217ebccca63265 | 51,267 |
from functools import reduce
import operator
def trim_ranks(dims, ranks):
"""Return TT-rank to which TT can be exactly reduced
A tt-rank can never be more than the product of the dimensions on the left
or right of the rank. Furthermore, any internal edge in the TT cannot have
rank higher than the pro... | 49d59691aba2b67b7e6686d887961fcf1939c071 | 51,268 |
import requests
def publish(url, assets):
"""
API publishing function.
"""
x = requests.post(url, json=assets)
return x.json() | 8ffe294e9d97d09f71ba082a243c1927c2a54743 | 51,269 |
def manage_groups(dset):
"""
manage_groups
description:
Prompts the user with options to manage group assignments on the Dataset instance:
- Assign indices to a group
- View assigned group indices
- Get data by group
Returns a boolean indicating whether the us... | 92b96bcfb387018c4148329cea577fe19c5c9290 | 51,270 |
def findIdx(list1, list2):
"""
Return the indices of list1 in list2
"""
return [i for i, x in enumerate(list1) if x in list2] | 2fb6c27cdc65185675bc4cd45a61d986f4792e07 | 51,271 |
def GenCount(data):
"""
Generate a total count from all bins for an OPC
"""
counts=[]
for index,row in data.iterrows():
count=0
for column in data.columns:
if "b" in column:
count=count+row[column]
# print(count)
counts.append(coun... | 0cf0cb677b3f87cb434f60501213b62ec86f6d0c | 51,273 |
from datetime import datetime
def reformat_subway_dates(date):
"""
The dates in our subway data are formatted in the format month-day-year.
The dates in our weather underground data are formatted year-month-day.
In order to join these two data sets together, we'll want the dates formatted
the sam... | a40aff606bc790e41b75b4588dbb9b4442510805 | 51,274 |
import re
def find_edf_artifacts(asc_str, kind='EBLINK|ESACC'):
"""Find artifacts in an edf asci representation
Parameters
----------
asc_str : str
String with edf asci represenation as returned by read_edf.
kind : 'EBLINK|ESACC' | 'EBLINK' | 'ESACC'
Kind of artifact to search.
... | d58173ee8c4d66be7a5ffb3ff080a151a3e49e17 | 51,275 |
import json
def serialize_sso_records(user_social_auths):
"""
Serialize user social auth model object
"""
sso_records = []
for user_social_auth in user_social_auths:
sso_records.append({
'provider': user_social_auth.provider,
'uid': user_social_auth.uid,
... | de84d7ba0d4f0c6f7c7074ad0d363c3ff031881b | 51,276 |
import requests
import logging
import json
def update_intersight_role(AUTH, ORG_MOID, ROLE_MOID, CLAIM_CONFIG):
""" Add priviledges to an Intersight Role """
response = requests.get(
CLAIM_CONFIG['intersight_base_url'] +
"iam/Roles?$select=Name,Moid&$filter=Name%20in%20%28" +
",".joi... | d968cc71e994ff11863d007cc175a433d851e395 | 51,278 |
import os
import logging
import json
def get_database_uri():
"""
Initialized DB2 database connection
This method will work in the following conditions:
1) With DATABASE_URI as an environment variable
2) In Bluemix with DB2 bound through VCAP_SERVICES
3) With PostgreSQL running on the loc... | 17a34194ac88c28434e31d199020fee470f1043d | 51,284 |
def load_txt(path):
"""
load txt file
:param path: the path we save the data.
:return: data as a list.
"""
with open(path,'r') as f:
data = []
while True:
a = f.readline().split()
if a:
data.append(a[0])
else:
br... | 902fdba2f6d3a9d2dbe1aef22fdcecfba1ed2455 | 51,285 |
from typing import Tuple
from typing import Counter
def check_string(instr: str) -> Tuple[bool, bool]:
"""Extract count check form a string."""
count = Counter(instr)
count_vals = count.values()
return (2 in count_vals, 3 in count_vals) | 9c3ce9f01c857495528bd557ff903847f6841e77 | 51,287 |
def get_time_string(hour):
"""Returns a string to display given a value 8-22 (8am to 10pm)"""
if hour < 12:
return str(hour) + ":00am"
elif hour == 12:
return str(hour) + ":00pm"
elif hour > 12 and hour < 23:
return str(hour-12) + ":00pm"
else:
return None | bc2d7f84f51ef2198d6cce7fa537f4e048331fcb | 51,288 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.