content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import tempfile
import zipfile
def unzip_csar_to_tmp(zip_src):
"""
Unzip csar package to temp path
:param zip_src:
:return:
"""
dirpath = tempfile.mkdtemp()
zip_ref = zipfile.ZipFile(zip_src, 'r')
zip_ref.extractall(dirpath)
return dirpath | b6be57f4e20c208583cc15dc9d0b997f6b41e2f1 | 13,669 |
from typing import Callable
from typing import Any
from typing import List
import inspect
def get_parameters(
f: Callable[..., Any], allow_args: bool = False, allow_kwargs: bool = False
) -> List[str]:
"""Get names of function parameters."""
params = inspect.getfullargspec(f)
if not allow_args and par... | 218e187ae504ce18c0d240aee93480e275f4b8a4 | 13,671 |
def _convertCtypeArrayToList(listCtype):
"""Returns a normal list from a ctypes list."""
return listCtype[:] | 89a408b796f2aba2f34bc20942574986abd66cd2 | 13,672 |
from typing import List
def get_cost_vector(counts: dict) -> List[float]:
"""
This function simply gives values that represent how far away from our desired goal we are. Said desired goal is that
we get as close to 0 counts for the states |00> and |11>, and as close to 50% of the total counts for |01> and... | b7565de2e47ba99e93b387ba954fdc29f44805e8 | 13,673 |
def default_copy(original_content):
"""Copy all fields of the original content object exactly as they are
and return a new content object which is different only in its pk.
NOTE: This will only work for very simple content objects. This will
throw exceptions on one2one and m2m relationships. And it mig... | d0a6fca858e34b8a7ae26ed9693a894cf2b2473f | 13,674 |
def build_normalized_request_string(ts, nonce, http_method, host, port, request_path, ext):
"""Implements the notion of a normalized request string as described in
http://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac-02#section-3.2.1"""
normalized_request_string = \
ts + '\n' + \
nonce +... | 6a7f397738b852116cbaf249c846f58b482fdca1 | 13,675 |
def rivers_with_station(stations):
"""Given list of stations (MonitoringStation object), return the
names of the rivers that are being monitored"""
# Collect all the names of the rivers in a set to avoid duplicate entries
rivers = {station.river for station in stations}
# Return a list for conveni... | c099af2eb0f869c6f1e3270ee089f54246779e2d | 13,677 |
import requests
import json
def pinterest_shares(url):
"""pinterest share count"""
try:
pinterest_url = 'http://api.pinterest.com/v1/urls/count.json?url=' \
+ url
response = requests.get(pinterest_url).text\
.replace('receiveCount(', '')\
... | 097a587778b1b21ceb84664b644cdbc6bb4619c3 | 13,678 |
import math
def get_deltas(radians):
"""
gets delta x and y for any angle in radians
"""
dx = math.sin(radians)
dy = -math.cos(radians)
return dx, dy | 032acb537373d0ee18b721f04c95e75bb1572b1b | 13,679 |
from typing import Dict
def mrr(benchmark: Dict, results: Dict, repo: str) -> float:
"""
Calculate the MRR of the prediction for a repo.
:param benchmark: dictionary with the real libraries from benchmark.
:param results: dictionary with the predicted libraries.
:param repo: full name of the repo.... | b057c93cc807244e4d5e8e94772877273ac1041c | 13,680 |
def hook_get_load_batch_query(table: str, start_index: int,
end_index: int) -> str:
"""Returns the query that loads the BQ data.
Here it's possible to filter just new customers or other customer
groups.
Args:
table: A string representing the full path of the BQ table where th... | 6a99cf04214a815249a01b6cf5040bdb93b73fb8 | 13,681 |
def elf_segment_names(elf):
"""Return a hash of elf segment names, indexed by segment number."""
table = {}
seg_names_sect = elf.find_section_named(".segment_names")
if seg_names_sect is not None:
names = seg_names_sect.get_strings()[1:]
for i in range(len(names)):
table[i... | 4af46fb35c9808f8f90509417d52e7ce4eb2770e | 13,682 |
def line_line_closest_points(A1, C1, A2, C2):
"""
>>> print line_line_closest_points(Ux,Ux,Uy,Uy)
(Vec( 0.000000, 0.000000, 0.000000 ), Vec( 0.000000, 0.000000, 0.000000 ))
>>> print line_line_closest_points(Ux,Uy,Uy,Uz)
(Vec( 0.000000, 1.000000, 0.000000 ), Vec( 0.000000, 1.000000, 1.000000 ))
... | 211d19b67fb56d00ae1276ebd62e9e979c4d5295 | 13,683 |
def segment_spectrum_batch(spectra_mat, w=50, dw=25):
"""
Segment multiple raman spectra into overlapping windows
Args:
spectra_mat (2D numpy array): array of input raman spectrum
w (int, optional): length of window. Defaults to 50.
dw (int, optional): step size. Defaults to 25.
... | 956791e2957f4810726d1d94549f79f3d83c8d21 | 13,684 |
def readvar(fni,varname,latrange=[],prange=[]):
"""reads variable from netcdf object in varname
fni is a Dataset variable"""
tsv = fni.variables[varname]
ts=tsv[:]
# try:
# ts = np.array(ts,dtype='float32')*float(tsv.scale_factor)+float(tsv.add_offset)
# except AttributeError:
# x=0 # dummy statement
tr... | 2c987fa20c76911442cdcbba48f7b215350e0484 | 13,685 |
def transform_url(private_urls):
"""
Transforms URL returned by removing the public/ (name of the local folder with all hugo html files)
into "real" documentation links for Algolia
:param private_urls: Array of file links in public/ to transform into doc links.
:return new_private_urls: A list of do... | 17a5c720103294b7535c76d0e8994c433cfe7de3 | 13,688 |
import os
import argparse
def _dependent_globals(this_script, cwd=os.curdir):
"""Compute set of related globals that depend on this script's path."""
script_dir = os.path.dirname(this_script)
# This script lives under 'build/rbe', so the path to the root is '../..'.
default_project_root = os.path.rea... | 392452de8f0e591c1bedca7b3aad4df359d29367 | 13,689 |
def cosine_similarity(intersection_num, all_items_num,
first_set_len, second_set_len):
"""
Count cosine similarity based on intersection data
:param intersection_num: len of intersection of two sets
:param all_items_num: num of all items, for example, sum of views
:param first_... | 90a8be939730307069f6758fe6a93299d6484b42 | 13,690 |
import random
def random_walk(graph, node, steps=8):
"""
Given a graph and a specific node within the graph, returns a node after steps random edge jumps
:param graph:
A networkx graph
:param node:
Any node within the graph
:param steps:
The number of steps within the random walk
:return:
A node within... | ad75cadc8e1df8edf5ebbb030de9b80076ab1f4c | 13,691 |
from typing import List
from typing import Any
def get_last_key_from_integration_context_dict(feed_type: str, integration_context: List[Any] = []) -> \
str:
"""
To get last fetched key of feed from integration context.
:param feed_type: Type of feed to get last fetched key.
:param integration... | 64eeb53cf00636dfc73866c64c77e2964149209e | 13,692 |
import re
def english_syllables(word):
"""Simple heuristic for the number of syllables in an English word. 91% agreement with CMUDict."""
pos = ["[aeiouy]+", "[^cgj]eo|[^cgst]ia|ii|[^cgstx]io|io$|[^g]iu|[^qg]ua|[^g]uo", "^mc|(s|th)ms?$", "[aeiouy]ing"]
neg = ["[aeiouy]n?[^aeiouy]h?e$", "[aeiouy]([^aeiouyt... | 000a353633c25067472c131c78a8c16eda45b522 | 13,693 |
def parse_file(data_dict):
""" takes the streptomedb dictionary and returns a list of lists with
NPs which is easy to use
data_dict: strep dictionary created with make_dict()
"""
key_list = []
for key in data_dict.keys():
key_list += [key]
value_list = []
for value in d... | ad1c80729bf38b868c839aef2b9b6d76d1ad17d5 | 13,694 |
import math
def _parseSeconds(data):
"""
Formats a number of seconds into format HH:MM:SS.XXXX
"""
total_seconds = data.total_seconds()
hours = math.floor(total_seconds / 3600)
minutes = math.floor((total_seconds - hours * 3600) / 60)
seconds = math.floor(total_seconds - hours * 3600 - min... | b01a66f66dc3cdc930aff29069c865cab5278d08 | 13,695 |
import os
import requests
def check_exists(item, rest_url):
"""
Checks the existence of item in ES
@param item: item to check
@param rest_url: rest API endpoint
@return: True if item exists
"""
ptype = "container"
if item.startswith("job"):
ptype = "job_spec"
elif item.sta... | f2445ce2926745333fe307ae3a226a428aa2089f | 13,698 |
from pathlib import Path
def generate_filename(candidate: Path) -> Path:
"""Generate a filename which doesn't exist on the disk. This is not atomic."""
orig = candidate
i = 0
while candidate.exists():
stem = orig.stem
candidate = orig.with_stem(f"{stem}-{i}")
i += 1
return... | 4a304b30aac5091e8a3f59db3d7d293b272b92ef | 13,699 |
from typing import Optional
def code_block(text: str, language: Optional[str]) -> str:
"""Formats text for discord message as code block"""
return f"```{language or ''}\n" f"{text}" f"```" | c54d5b3e6f456745817efd03b89bd56d7fe4794e | 13,700 |
import os
def get_last_bounce(data_file_name):
"""
Find the index of the last bounce and return it.
"""
if not os.path.exists(data_file_name):
return None
with open(data_file_name, 'r') as data_file:
lines = data_file.readlines()
if len(lines) == 0:
return None
... | d7a18e4581220f720e160e44896a76e77351e9c0 | 13,701 |
def Fredkin_check(function):
"""Decorator to check the arguments of calling Fredkin gate.
Arguments:
function {} -- The tested function
"""
def wrapper(self, control_qubit):
"""Method to initialize Fredkin gate.
Arguments:
control_qubit {Qubit} -- Possible valu... | 7b62bc1998baffcffa896a6a549c3044ebbc9abd | 13,703 |
def current_scopes():
"""
init security setting
:return: pending
"""
return [] | 2aa8500f0c1487723d74d975cf9e50f92904e1de | 13,704 |
def urlsplit(url):
""" Splits a URL like "https://example.com/a/b?c=d&e#f" into a tuple:
("https", ["example", "com"], ["a", "b"], ["c=d", "e"], "f")
A trailing slash will result in a correspondingly empty final path component.
"""
split_on_anchor = url.split("#", 1)
split_on_query = split_o... | 47cd2b556f842dd3ed499f841ff41d16c0747cbc | 13,708 |
def rotate_key(element):
"""Returns a new key-value pair of the same size but with a different key."""
(key, value) = element
return key[-1] + key[:-1], value | e9407e87a24571bb17e484d7954764dce38003dc | 13,709 |
import math
def hypotenuse_length(leg_a, leg_b):
"""Find the length of a right triangle's hypotenuse
:param leg_a: length of one leg of triangle
:param leg_b: length of other leg of triangle
:return: length of hypotenuse
>>> hypotenuse_length(3, 4)
5
"""
return math.sqrt(leg_a**2... | 7a59ede73301f86a8b6ea1ad28490b151ffaa08b | 13,710 |
def make_rowcol(string):
"""
Creates a rowcol function similar to the rowcol function of a view
Arguments:
string -- The string on which the rowcol function should hold
Returns:
A function similar to the rowcol function of a sublime text view
"""
rowlens = [len(x) + 1 for x in string.s... | 87a0c162c69dd8f1e4e50f3b40da8772e645772e | 13,713 |
def commonPoints(lines):
"""
Given a list of lines, return dictionary - vertice -> count. Where count
specifies how many lines share the vertex.
"""
count = {}
for l in lines:
for c in l.coords:
count[c] = count.get(c, 0) + 1
return count | 1b838ddd4d6a2539b0270cd319a2197e90372c3a | 13,716 |
import os
def fullpath(path):
"""Expands ~ and returns an absolute path"""
return os.path.abspath(os.path.expanduser(path)) | 9299d60d67214a19fd0c2739beda4fa3b55ac38a | 13,718 |
import os
def add_meta_and_doc_file(test_name, json_name):
"""
create
.meta/tests.toml
.meta/config.json
.docs/instructions.md (based on ../problem-specifications/exercises/[EXERCISE]/description.md)
for test_name
Not yet implemented.
"""
test_dir_name = os.pa... | 1181e82b627175c885ae34b01d6e8a811793956f | 13,719 |
def isostring(dt):
"""Convert the datetime to ISO 8601 format with no microseconds. """
if dt:
return dt.replace(microsecond=0).isoformat() | db7326e53402c0982514c4516971b4460840aa20 | 13,720 |
import base64
def image_encoder(img_path):
"""Function to verify API status.
Parameters
----------
img_path : str
The path to the image to be encoded.
Returns
-------
encoded_img : str
A UTF-8 string containing the encoded image.
"""
with open(img_pat... | 7ef4c5c4a0fad340ab50c798e70b0f0c4ceb0d22 | 13,721 |
def inject_menu_items() -> dict:
"""Defines items of navbar"""
return dict(menu_items=[
{
'title': '<i class="fa fa-home" aria-hidden="true"></i> Home',
'url': '/',
'function_name': 'home',
'children': None
},
{
'title': '<i cla... | dfca070335ed11a60cc721056de6a90f62f66749 | 13,722 |
def filenameDictForDataPacketType(dataPacketType):
"""
Return a dict of fileDescriptors for a given DataPacket type.
"""
foo = dataPacketType(None, None)
return foo.filenames | 6853add9035e3b7aad86a001ee7f46e5e69336a8 | 13,723 |
def git_origin_url(git_repo): # pylint: disable=redefined-outer-name
"""
A fixture to fetch the URL of the online hosting for this repository. Yields
None if there is no origin defined for it, or if the target directory isn't
even a git repository.
"""
if git_repo is None:
return None
... | d1f301a31aca6fae2f687d2b58c742ee747c4114 | 13,724 |
from typing import Any
def argument(*name_or_flags: Any, **kwargs: Any) -> tuple:
"""Convenience function to properly format arguments to pass to the
subcommand decorator.
"""
return (list(name_or_flags), kwargs) | 22b2cbda7a3c2e4113c47896d60290b124cf85f1 | 13,725 |
import subprocess
import numpy as np
def get_free_gpu():
"""Selects the gpu with the most free memory
"""
output = subprocess.Popen('nvidia-smi -q -d Memory |grep -A4 GPU|grep Free', stdout=subprocess.PIPE,
shell=True).communicate()[0]
output = output.decode("ascii")
... | 4432dda1b27cb7c913d9dd20348b9ac86ee39faa | 13,728 |
import os
def read_file(filename):
"""Reading file from filesystem."""
result = ''
# Checking if file exists
if not os.path.isfile(filename):
# If file does not exists, return suitable information
return "file '" + filename + "' not found"
else:
# If ile exists open it.
... | 6ef21d08745d302bc1aadeabc0e779a425b1b7f5 | 13,729 |
def special_len(tup):
"""
comparison function that will sort a document:
(a) according to the number of segments
(b) according to its longer segment
"""
doc = tup[0] if type(tup) is tuple else tup
return (len(doc), len(max(doc, key=len))) | 81154c8e1b31dc37cffc43dfad608a5cd5281e4c | 13,730 |
import os
def assemble_paths_list():
"""Returns a list of paths to search for libraries and headers.
"""
PATHS = [
("/usr/lib", "/usr/include"),
("/usr/lib64", "/usr/include"),
("/usr/X11/lib", "/usr/X11/include"),
("/usr/X11R6/lib", "/usr/X11R6/include"),
... | 9c2f3c1883f241884c5b3b15ee06c8036252ae26 | 13,731 |
def opener(wrapped, instance, args, kwargs):
"""
opener(yaml.load)("conf.yaml")
opener(json.load)("conf.json")
"""
path = args[0]
with open(path) as f:
return wrapped(f) | 05c42f0e668f2419b4e478e8602c056a8cda634b | 13,732 |
def make_header_lines(all_bits):
"""
Formats header lines
"""
lines = []
# Bit names
bit_names = ["%d_%d" % (b[0], b[1]) for b in all_bits]
bit_len = 6
for i in range(bit_len):
line = ""
for j in range(len(all_bits)):
bstr = bit_names[j].ljust(bit_len).replac... | 6c48eb125f39ca55ae47c5f6a21732fdb60c9de0 | 13,733 |
def _pair_product(p, i, j):
"""Return product of counts of i and j from data."""
try:
return sum(p[i].values())*sum(p[j].values())
except KeyError:
return 0 | 7a7a19d62544ee88f6755c64f08438c0ab95033f | 13,735 |
from typing import Optional
def optional_arg_return(some_str: Optional[str]) -> Optional[int]:
"""Optional type in argument and return value."""
if not some_str:
return None # OK
# Mypy will infer the type of some_str to be str due to the check against None
return len(some_str) | 8125965fb1fe1f11f4f5045afc8107bcdfc95fc0 | 13,736 |
import os
def get_failure_report_path(sample_alignment, report_filename):
"""Returns full path to given report for ExperimentSampleToAlignment.
"""
return os.path.join(sample_alignment.get_model_data_dir(), report_filename) | 2979f8d772633ebbcd1d20895987d52d1efdbf36 | 13,738 |
import cProfile
import time
import pstats
def profile(fn):
"""
Profile the decorated function, storing the profile output in /tmp
Inspired by
https://speakerdeck.com/rwarren/a-brief-intro-to-profiling-in-python
"""
def profiled_fn(*args, **kwargs):
filepath = "/tmp/%s.profile" % fn.__... | aaf1711fefee698ff5456e120dcc06cbb8c22a8f | 13,739 |
import asyncio
def _ensure_coroutine_function(func):
"""Return a coroutine function.
func: either a coroutine function or a regular function
Note a coroutine function is not a coroutine!
"""
if asyncio.iscoroutinefunction(func):
return func
else:
async def coroutine_function(... | e8271691abe4d4b7b965efe561f137adf77f6b4f | 13,740 |
import os
def load_samples(sample_file_path):
"""Read in sample file, returning a flat list of all samples inside"""
samples = []
print("Reading: {}".format(sample_file_path))
with open(os.path.abspath(sample_file_path), "r") as sample_file:
for sample in sample_file:
samples.appen... | bf854993a9e3b3bac6e7f3804f1a24c4b45ff7bc | 13,741 |
def interpolate_value(x, y, t):
"""Find the value of x: y(x) = t."""
if t > max(y) or t < min(y):
raise RuntimeError("t outside of [%f, %f]" % (min(y), max(y)))
for j in range(1, len(x)):
x0 = x[j - 1]
y0 = y[j - 1]
x1 = x[j]
y1 = y[j]
if (y0 - t) * (y1 - ... | cebddb77534a5a09b825fa08c1083c2dc65db5d8 | 13,742 |
def pwd(session, *_):
"""Prints the current directory"""
print(session.env.pwd)
return 0 | 0f63b0483453f30b9fbaf5f561cb8eb90f38e107 | 13,743 |
def percent_replies(user):
"""
description:
en: Percent of comments that are replies.
de: Prozent der Kommentare, die Antworten gibt.
type: float
valid: probability
"""
return sum(1 if c.get('parent_id', '') else 0 for c in user['comments'])/len(user['comments']) | 2e9f78fa41742cbc9a6d6a692b9acf41200d4146 | 13,744 |
def list_roles(*args):
"""DEPRECATED: Use list"""
return list(*args) | 397cafd85ab863edf08d12ba647bcb670c371eed | 13,745 |
def feature_list_and_dict(features):
"""
Assign numerical indices to a global list of features
:param features: iterable of feature names
:return: sorted list of features, dict mapping features to their indices
"""
feature_list = sorted(features)
feature_dict = {feat:i for i, feat in enumera... | 11006cdc4871c339cf3936a1734f012f21d92459 | 13,746 |
def load_weights(network, filename):
"""
Loads a model’s weights
filename is the path of the file that the model should be loaded from
Returns: the loaded model
"""
network.load_weights(filename)
return None | 583003f0232fdfdf06eb172db97d22440877cb53 | 13,747 |
def compute_St(data):
"""
Given a dataset, computes the variance matrix of its features.
"""
n_datapoints, n_features = data.shape
# Computing the 'mean image'. A pixel at position (x,y) in this image is the
# mean of all the pixels at position (x,y) of the images in the dataset.
# This cor... | 99f55de9c19f7304136e5737d9acba0e6de4d2fd | 13,748 |
def metamodel_to_swagger_type_converter(input_type):
"""
Converts API Metamodel type to their equivalent Swagger type.
A tuple is returned. first value of tuple is main type.
second value of tuple has 'format' information, if available.
"""
input_type = input_type.lower()
if input_type == 'd... | a1f01124546acc3035d3db3329b0194ac65c2f17 | 13,750 |
import os
import glob
def version_file_name(file_name):
""" Versions file name with .v{i}. Returns new file name with latest i """
file_path = os.path.dirname(file_name)
file_name = os.path.basename(file_name)
files = glob.glob(os.path.join(file_path, file_name + '*'))
def in_list(i, files):
... | 3de20a26d695dff2679946ae3033f2e7fe29bff1 | 13,751 |
def is_instance(arg, types, allow_none=False):
"""
>>> is_instance(1, int)
True
>>> is_instance(3.5, float)
True
>>> is_instance('hello', str)
True
>>> is_instance([1, 2, 3], list)
True
>>> is_instance(1, (int, float))
True
>>> is_instance(3.5, (int, float))
True
... | 52149919b010909614c7dc83e189fa3b8a950393 | 13,752 |
def derivative_2nd(f,x,h):
"""function to calaculate 2nd derivative"""
h = float(h)
func=f(x)
return (f(x+h)-(2*func)+(f(x-h)))/(h*h) | 6c420bf2cf8cff27fb3e1f022d67d62bf38c9631 | 13,753 |
def get_fire_mode(weapon):
"""Returns current fire mode for a weapon."""
return weapon['firemodes'][weapon['firemode']] | 691fc5e9b3ce40e51ab96930086f8d57e5fa6284 | 13,754 |
def data_to_str(data, contents_ignore_fields, grab_only_fields):
"""
desc: recursively converts all data to a single concatenated string
only works for strings, lists and dicts
"""
c = ""
if type(data) == list:
for d in data:
c += " " + data_to_str(d, contents_ignore_fields, grab_only_fi... | e66bcea4b40f48166bb256b06f8595604e5d8f62 | 13,756 |
def depth_first_ordering(adjacency, root):
"""Compute depth-first ordering of connected vertices.
Parameters
----------
adjacency : dict
An adjacency dictionary. Each key represents a vertex
and maps to a list of neighboring vertex keys.
root : str
The vertex from which to s... | fcff465cfaa2e3a500e8d177e6b9e78cc66bc21d | 13,757 |
def encode_dxt1(image):
"""Encode a PIL Image into DXT1 (stored in bytearray)."""
pixels = image.load()
# you can access the colours in the image by indexing:
# pixels[x, y]
# => (red, green, blue)
# for example, pixels[0, 0] returns (r, g, b) for the top-left pixel
# for more info, see the ... | 5bc6eae61b57de9e81743e5c72725f7c6f62b34f | 13,758 |
from typing import List
from typing import Tuple
from textwrap import dedent
def get_rt_object_to_complete_texts() -> List[Tuple[str, str]]:
"""Returns a list of tuples of riptable code object text with associated completion text."""
return [
(
dedent(
'''Dataset({_k: list(... | 007d2291fd922aab5627783897a56cd5fd715f98 | 13,760 |
import token
import requests
def create_mirror(gitlab_repo, github_token, github_user):
"""Creates a push mirror of GitLab repository.
For more details see:
https://docs.gitlab.com/ee/user/project/repository/repository_mirroring.html#pushing-to-a-remote-repository-core
Args:
- gitlab_repo: Git... | 2a5d7e01ca04a6dcb09d42b5fc85092c3476af0d | 13,761 |
def genelist_mask(candidates, genelist, whitelist=True, split_on_dot=True):
"""Get a mask for genes on or off a list
Parameters
----------
candidates : pd.Series
Candidate genes (from matrix)
genelist : pd.Series
List of genes to filter against
whitelist : bool, default True
... | 53e1f80de097311faddd4bfbff636729b076c984 | 13,762 |
from datetime import datetime
def writenow():
"""Return utcnow() as ISO foramat string"""
return datetime.isoformat(datetime.utcnow()) | 19a0e4653bfa7cfab2528e81317fd2399ca630d5 | 13,763 |
def parse_releases(list):
"""
Parse releases from a MangaUpdate's search results page.
Parameters
----------
list : BeautifulSoup
BeautifulSoup object of the releases section of the search page.
Returns
-------
releases : list of dicts
List of recent releases found by t... | e7e93130732998b919bbd2ac69b7fc36c20dd62d | 13,764 |
def read_data_with_ref(source_path, target_path, ref_path):
"""Read sentences and parallel sentence references."""
with open(source_path, "r", encoding="utf-8") as source_file,\
open(target_path, "r", encoding="utf-8") as target_file:
source_lines = [l for l in source_file]
targ... | 1ce3d768ddb5d4de0f72cbe0633dfafe20bdc2c0 | 13,765 |
def _linkify(value):
"""create link format"""
out = []
for link in value:
out.append(','.join(list(link)))
return '^'.join(out) | 1fa2020148ef1fd7ba7f10eecb54836517ff0abd | 13,766 |
import torch
def get_packed_sequence_info(packed):
"""Get `batch_sizes` and `sorted_indices` of `PackedSequence`.
Args:
packed (object): Packed sequences. If it contains multiple
`PackedSequence`s, then only one of them are sampled assuming that
all of them have same `batch_si... | f3540bfe63d5ef72ecb1df20e09dd249310508b7 | 13,768 |
def ouverture_image(largeur, hauteur):
"""
génère la balise ouvrante pour décrire une image SVG des
dimensions indiquées. Les paramètres sont des entiers.
Remarque : l’origine est en haut à gauche et l’axe des Y est
orienté vers le bas.
"""
balise = "<svg xmlns='http://www.w3.org/2000/svg' v... | da53a8d8e45df8d54bb63dcf8f88b2465af486aa | 13,770 |
def list_size_reducer(reduction_factor, your_list):
"""_summary_
Parameters:
reduction_factor (int): _description_
your_list (list): _description_
Returns:
reduced_list (_type_): _description_
"""
# input type checking
assert type(reduction_factor) == int, 'reduction_fact... | 0ed7dbff4a0b27146ffa1f44ce9e517bc4c632b0 | 13,772 |
import requests
import json
def request_data(url: str, where_clause: str = "1=1") -> dict:
"""
Requests data from the ArcGIS api and retuens the response in JSON format.
"""
params = {
"referer": "https://www.mywebapp.com",
"user-agent": "python-requests/2.9.1",
"where": where... | 61ce82eb38f48805d62cdf8c9927f2607411281e | 13,773 |
def Sqrt(x):
"""Square root function."""
return x ** 0.5 | e726dfad946077826bcc19f44cd6a682c3b6410c | 13,774 |
def hello(friend_name):
"""Says 'Hello!' to a friend."""
return "Hello, {}!".format(friend_name.title()) | 706c5a2d3f7ebdf9c7b56e49bb0541655c191505 | 13,775 |
def _get_story_duration(story_tag):
"""
Return the sum of the text time and media time, or return None if not found
"""
try:
metadata = story_tag.find('mosExternalMetadata')
payload = metadata.find('mosPayload')
except AttributeError:
return 0
try:
return float(p... | df7f90eb6a02c0e8f9e6deaa45770fdc03c79a50 | 13,776 |
def generate_image(model, landmark, e_vector, device):
"""
Generator generate image from landmark and e_vector
Args:
model(nn.Module) : Generator model which generate image from landmark and e_vector.
landmark(tensor) : Landmark which type is torch.tensor.
e_vector(tensor)
... | 1c0ee6ca116b663ab0d257d6e7c9a1e7a85aaa37 | 13,777 |
import uuid
def set_compose_session(request):
"""Initialize a new "compose" session.
It is used to keep track of attachments defined with a new
message. Each new message will be associated with a unique ID (in
order to avoid conflicts between users).
:param request: a Request object.
:return... | 57384af709ce69d648bf85bce0c8a157fa5627c4 | 13,778 |
def CreateLessThanOrEqualRegex(number):
""" Return a regular expression to test whether an integer less than or equal
to 'number' is present in a given string.
"""
# In three parts, build a regular expression that match any numbers smaller
# than 'number'.
# For example, 78656 would give a regular expr... | 1de3074ede96b2a2bd0a28cb3f0167da7a767d40 | 13,779 |
def allowed_attrs(attrs, new=False):
"""Only allow href, target, rel and title."""
allowed = [
(None, 'href'),
(None, 'target'),
(None, 'rel'),
(None, 'title'),
'_text',
]
return dict((k, v) for k, v in attrs.items() if k in allowed) | 28f7e310f1ff1cbec58ea505c179494491af7171 | 13,780 |
import subprocess
def create_sparse_dmg(name, out_path):
"""Creates a sparseimage (auto resizing read/write image) with the specified volume name at out_path."""
print('Creating disk image (%s)...' % out_path)
return subprocess.call([
'hdiutil', 'create',
'-volname', name,
'-type', 'SPARSE',
'-l... | 3696ba86fe5713df1b219e92d7394685c606f529 | 13,781 |
import requests
import json
def get_iam_token(oauth_token):
"""
Получение IAM-токена.
@param oauth_token: OAuth-токен в сервисе Яндекс.OAuth
@return: (str) - IAM-токен.
"""
url = 'https://iam.api.cloud.yandex.net/iam/v1/tokens'
data = {'yandexPassportOauthToken': oauth_token}
with requ... | 939b4a512d20e5dd71c576f84d5a6ae10fb0e7e9 | 13,782 |
import requests
def ack_url(url):
""" 访问网页 返回页面信息"""
headers = {
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36"}
response = requests.get(url=url, headers=headers)
return response.text | 8fa3f9c2b8983d45523461c0fa28cf9746d572c7 | 13,783 |
import curses
def _alternative_left_right(term):
"""_alternative_left_right(T) -> dict
Return dict of sequences ``term._cuf1``, and ``term._cub1``,
valued as ``KEY_RIGHT``, ``KEY_LEFT`` when appropriate if available.
some terminals report a different value for *kcuf1* than *cuf1*, but
actually s... | ffdbdbc3327af956c39ca1f806935c5dc651ff9b | 13,786 |
def gfMDS_make_cmd_string(info):
"""
Purpose:
Construct the command line options string passed to the MDS C code.
Usage:
Author: PRI
Date: May 2018
"""
# create the input files string
in_files = info["in_file_paths"][0]
for in_file in info["in_file_paths"][1:]:
in_files ... | 72a446bed8925b6b9ef20ebe21d2eb49982b86c2 | 13,787 |
def get_initial_state(inp):
"""
return tuple of (terminals,initial assignments) where terminals is a dictionnay key = target and value is a
list of start and end coordinates
"""
terminals = {}
assignments = {}
for row_ind in range(len(inp)):
for col_ind in range(len(inp[row_ind]... | 65189f967af0eaa41b914f2c2dd79f7e875fdafd | 13,789 |
def count_digit(value):
"""Count the number of digits in the number passed into this function"""
digit_counter = 0
while value > 0:
digit_counter = digit_counter + 1
value = value // 10
return digit_counter | f9b1738804b0a40aa72283df96d2707bcfd7e74c | 13,790 |
def prepare_service(data):
"""Prepare service for catalog endpoint
Parameters:
data (Union[str, dict]): Service ID or service definition
Returns:
Tuple[str, dict]: str is ID and dict is service
Transform ``/v1/health/state/<state>``::
{
"Node": "foobar",
... | 5af6f0ae150fe21cd41d1ab14aa129d07efa08c5 | 13,792 |
def func_1(x: float, a: float, b: float) -> float:
""" Test function. """
return x + a + b | 776ad7473aa52b16fcd759e376f5f47a51c73013 | 13,795 |
import socket
def get6addr(name):
"""Get IPv6 address for name. If necessary, an IPv4 over IPv6 address."""
try:
addr = socket.getaddrinfo(name, 'domain', family=socket.AF_INET6)
except socket.gaierror:
addr = socket.getaddrinfo(name, 'domain')
addr6 = '::ffff:' + addr[0][4][0]
... | 4ed93d37bf891b80a8a3ad0ff4eee3c1db643733 | 13,796 |
import os
def update_fields(base_dict, fields_to_check, print_text, field_required,
check_type):
"""
For a subset of fields in a dictionary, prompts the user to provide updated
values.
Parameters
----------
base_dict : Dictionary
The fiducial dictionary we're updati... | 5a79a3d11e6c100f4ed9e5f983f610486e5a402f | 13,798 |
def get_sys_uptime():
"""
:return: (uptime, idle) in seconds
"""
f = open("/proc/uptime") # %f(uptime) %f(idle) , all in seconds
uptime = f.read()
f.close()
uptime, idle = uptime.split(" ")
return float(uptime), float(idle) | 71406d10728820680046a2137129a7410f16cd78 | 13,799 |
import json
def parse_fio_output_file(fpath: str) -> dict:
""" Read and parse json from fio json outputs """
lines = []
with open(fpath, 'r') as fiof:
do_append = False
for l in fiof:
if l.startswith('{'):
do_append = True
if do_append:
... | ce4efcd3f0508179971788a2c19a7f278d887a79 | 13,800 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.