content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import requests
def http_get(url, fout=None):
"""Download a file from http. Save it in a file named by fout"""
print('requests.get({URL}, stream=True)'.format(URL=url))
rsp = requests.get(url, stream=True)
if rsp.status_code == 200 and fout is not None:
with open(fout, 'wb') as prt:
... | 6eded3d27a9d949f379ab9ff6316afc45e19c0b5 | 676,774 |
def getClusterTL(ndPage,lClusters,dIds):
"""
get tl nodes per cluster
"""
dTLCluster={}
for i,c in enumerate(lClusters):
dTLCluster[i]=[]
lIds=c.get('content').split()
for id in lIds:
try:dTLCluster[i].append(dIds[id])
except KeyError:pass
# ... | 85b62f85ad1cb842e6f342a9f2cb7e9b33a463d0 | 676,776 |
import time
def getTime():
"""Returns current local time."""
t = time.time()
currentTime = time.strftime("%Y-%m-%d %H:%M %Z", time.localtime(t))
return currentTime | aa14a622fdd877ecd004408dece62e20648d25eb | 676,777 |
def XDown(data, names, normed = None, **kargs):
"""
good for normalised illumina data, returns the fold2up/down data
"""
X = kargs["X"]
if normed:
norm_value = data[normed]
for c in data:
if c != normed:
normed_data = (data[c] / data[normed])
... | 84e1f4e0a262190575d7040c11dcab5b529545cb | 676,778 |
def get_nested_list_len(lst):
"""
Returns the combined length of all lists within a list. Non-recursive, so only goes one level deep
"""
ls_len = 0
if lst:
for item in lst:
ls_len += len(item)
return ls_len | 4d8ef8dedc4346991d0355ebcd2b3d9456c09194 | 676,779 |
from datetime import datetime
import sys
def complement_year(date_ref, m, d):
""" 年を補完して日付を作る
年が不明の月日をのうち基準日に近いものを選ぶ。
探す範囲は、基準日の年を Y として Y±1 年。
Parameters
----------
date_ref, datetime : 規準日
m, int : 月
d, int : 日
Returns
-------
date, datetime : 年を補完した日付
... | ea1495bd3315de07015bad23a7a2d8633cbf24f9 | 676,781 |
import random
def sampling_iterable_shuffler(iterables_):
"""
Python Package based shuffler.
:param iterables_: List of iterable container
:return:
"""
return random.sample(iterables_, len(iterables_)) | d2e78926c174906f1c41a97daf6b99b921fdd4c3 | 676,782 |
def get_historical_date(data_point):
"""Returns the date of a DATA_POINT"""
try:
return data_point['begins_at'][0:10]
except:
return None | 38bc71c3ccf01ec62be0f65d2d2264a0e036ea57 | 676,783 |
import yaml
def read_yaml(yaml_file):
"""Read a yaml file.
Args:
yaml_file (str): Full path of the yaml file.
Returns:
data (dict): Dictionary of yaml_file contents. None is returned if an
error occurs while reading.
"""
data = None
with open(yaml_file) as f:
... | b2a50ea3421489e327aa84c142dd54ace08f3811 | 676,784 |
def Hourly_stats_trends(dataArray, inputField):
"""
Create hourly stats and trends for device data across days
"""
#get length of retrieved data
dataLength = len(dataArray)
#initalize hourlyData
hourlyData = []
#loop through data for the device
for x in range(0, dataLength):
... | feb3ae2357d23a713535e1fcc7d1dc317cb22254 | 676,785 |
def safe_zip(sequence1, sequence2):
"""zip with safeguarding on the length
"""
assert len(sequence1) == len(sequence2)
return zip(sequence1, sequence2) | 83590107ac0f03282246b8ec9bbf47d1e3f14843 | 676,786 |
def c_escaped_string(data: bytes):
"""Generates a C byte string representation for a byte array
For example, given a byte sequence of [0x12, 0x34, 0x56]. The function
generates the following byte string code:
{"\x12\x34\x56", 3}
"""
body = ''.join([f'\\x{b:02x}' for b in data])
ret... | b2262fcb655ba6d4251856e97c1e0d92ae739784 | 676,787 |
def new_masked_mac(mac, mask):
"""
make masked mac string.
"""
return "{0}/{1}".format(mac, mask) | 4246465f24f78076ac91dee08d30497087b20250 | 676,788 |
def test_object_type(obj: object, thetype: type):
"""Tests if the given object is of the specified type. Returns a Boolean True or False.
Examples:
>>> myint = 34
>>> test_object_type(myint, int)
True
>>> isinstance(myint, int)
True
>>> test_object_type(myint, s... | 226c90e3fa97337af53e6c8ae70dcd0c7861e513 | 676,789 |
import re
def remove_leading_space(string: str) -> str:
"""
Remove the leading space of a string at every line.
:param string: String to be processed
:type string: str
:return: Result string
:rtype: str
**Example:**
.. code-block:: python
string = " Hello \\nWorld!"
... | 2bf2fb4158f1efe52d6efd861013633b34b21985 | 676,790 |
def qb_account(item_title):
"""
Given an item title, returns the appropriate QuickBooks class and account
Parameter: item_title
Returns: item_class, item_account
Note that this is only guaranteed to work for Ticketleap sales, not
PayPal invoices.
"""
if 'Northern' in item... | a067aed1bfbcca07f4968c08f1c1f400a6cb735e | 676,791 |
def bottom_row(matrix):
"""
Return the last (bottom) row of a matrix.
Returns a tuple (immutable).
"""
return tuple(matrix[-1]) | f56ad2f96e7a8559fad018208274d04efcd8880b | 676,792 |
def merge_sorted_cookie_lists(listA, listB):
"""Takes in two order lists of cookies and merges them together"""
if type(listA) != list or type(listB) != list:
raise TypeError(
"Both arguments for merge_sorted_cookie_lists must be of type list.")
final_list = []
listA_length = len(li... | 2ecebe039e57353ef97e0fd497d66c50a390726f | 676,794 |
from typing import Dict
def success_of_action_dict(**messages) -> Dict:
"""Parses the overall success of a dictionary of actions, where the key is an action name and the value is a dictionarised Misty2pyResponse. `overall_success` is only true if all actions were successful.
Returns:
Dict: The dictio... | 542725d492df7758e9b90edf8d18a935c824e18a | 676,795 |
import torch
def cal_normal(v, dim=-1, keepdim=False):
"""
:return:
"""
normal = (torch.sum(v ** 2, dim=dim, keepdim=keepdim)) ** 0.5
return normal | 835e62c20e1beeac93747ca909ca936548cd9066 | 676,796 |
import torch
def torch_pc_from_disparity(disp, stereo_calib_f, stereo_calib_baseline,
stereo_calib_centre_u, stereo_calib_centre_v,
flatten_order='C'):
"""Transforms disparity map to 3d point cloud
Args:
disp: disparity map
stereo_calib_... | 05ab90a337bbe6e2baa13b5bcd720d529036b3fd | 676,797 |
def roznice_skonczone(tab_y):
"""
obliczanie tabeli różnic skończonych
:param tab_y: tabeli wartości funkcji
:return: lista list różnic skończonych
"""
liczba_wezlow_interpolacji = len(tab_y)
delta_y = [[]]
delta_y[0] = tab_y
for licznik in range(1, liczba_wezlow_interpolacji):
... | 8c8c519605374daf8da512fc8cf75c3c2d14d81e | 676,798 |
def find_gc(seq: str) -> float:
""" Calculate GC content """
if not seq:
return 0
gc = len(list(filter(lambda base: base in 'CG', seq.upper())))
return (gc * 100) / len(seq) | faee3142885b7de8d31b8677465675696fa03a86 | 676,799 |
def set_to_list_geo(set_tranches, points_on_line):
"""
Convert set of (startnode, endnode) to a list of coordinate data of each node
:param set_tranches: tuples with unique edges (startnode, endnode)
:type set_tranches: set(int, int)
:param points_on_line: information about every node in study case... | 1a3b29dd1df35242e75e1bc27431fd4bcad6ad59 | 676,800 |
def encode_target(df, target_column, label_map):
"""Add column to df with integers for the target.
Args
----
df -- pandas DataFrame.
target_column -- column to map to int, producing
new Target column.
Returns
-------
df_mod -- modified DataFrame.
targets -- lis... | 2fe6a9b66fb25292c994336d5820442fb7d41984 | 676,801 |
import math
def is_prime(n):
"""Determine if a number is prime
Args:
n (int): Any integer
Returns:
[logical]: True if n is prime, False if n is not prime
"""
if n % 2 == 0 and n > 2:
return False
return all(n % i for i in range(3, int(math.sqrt(n)) + 1, 2)) | e00503da8d664f59b96ca074f4b9bcc4574be54d | 676,802 |
from typing import Counter
def word_count(text):
""" """
text = text.lower()
skips = ['.',',',';','?',':','!','"',"'"]
for ch in skips:
text = text.replace(ch," ")
# word_counts = {}
# for word in text.split(" "):
# if word in word_counts:
# word_counts[word] += 1... | 9d818b8f40b5a25751cd58044765f7edcf1575bd | 676,803 |
def get_status(guess, actual):
"""
根据猜测的单词和实际单词,获取状态码
:param guess: 猜测的单词
:param actual: 实际的单词
:return: 状态码
"""
status = 0
base = 1
for i in range(len(guess)):
c = guess[i]
if c == actual[i]:
status += 2 * base
elif c in actual:
status ... | a7b0e983bcc6c248c6d69cf4ba3e8934d0474b64 | 676,804 |
def getCpAdminId():
"""
Get cpadmin ID
"""
return '-777' | a73e365d05ffaf037feb792e262160faa9707266 | 676,805 |
def choose_tests(ARG_selectionlist: list, ARG_choicelist: list) -> list:
"""This function prompts the user to select certain tests to run."""
print ()
print (f"The selected tests are: {ARG_selectionlist}")
print (f"The available tests are:")
num = 0
for item in ARG_choicelist:
num = num ... | 582f4cbea494c2e947134e5801da7cc0cebec33b | 676,806 |
def clip(value, min, max):
"""Clips (limits) the value to the given limits.
The output is at least `min`, at most `max` and `value` if that value
is between the `min` and `max`.
Args:
value: to be limited to [min, max]
min: smallest acceptable value
max: greatest acceptable val... | 52ed454dbf3b39c841fd39560fb4cb4ea358b1e8 | 676,807 |
import hashlib
import os
def hash_directory(path):
"""Recursively hashes the contents of a directory and returns the hex value.
:param path: The path to the directory
:return: SHA1 hash
:rtype: str
"""
dir_hash = hashlib.sha1()
for root, dirs, files in os.walk(path):
for names i... | ad6e7d199230fa764734298b9a66c0a2cd155bc0 | 676,809 |
def calcuInbreedCoeff(gt):
"""
Calculating the inbreeding coefficient by GT fields of VCF.
Args:
`gt`: A list. Genotype fields of all the samples.
"""
ref_count, het_count, hom_count, n = 0, 0, 0, 0
for g in gt:
gs = g.split('/') if '/' in g else g.split('|')
if '.' not ... | f7a497b5ff0082d667cde9b821f2afb77299f8fb | 676,810 |
import math
def problem_03_prime_factor(number):
""" Problem 3: Determines the largest prime factor for a number.
Args:
number (int): The number to determine the largest prime factor of.
"""
def prime_factors(case):
result = []
if case % 2 and case > 2 == 0:
result... | bb367cb781640b87aef53fa6c9d7da643c10031f | 676,811 |
def is_variable_geometry(xmldoc):
"""
Tries to guess whether the calculation involves changes in
geometry.
"""
itemlist = xmldoc.getElementsByTagName('module')
for item in itemlist:
# Check there is a step which is a "geometry optimization" one
if 'dictRef' in list(item.attri... | fb6ba41fcc92acfefb7817de3b3f7cc91d16afaa | 676,812 |
import os
def get_files(top, include=None, exclude=None):
"""Get all fullpath files in top directory"""
if not top:
raise ValueError('Top must be not null')
results = []
for root, dirs, files in os.walk(top):
for f in files:
if include:
if f in include:... | e225979b0f85aa63b95d30b5d8a572b1503d7585 | 676,813 |
import os
def CleanScreen():
"""
Cleans the screen.
"""
return lambda: os.system('cls') | cc87de10dfb5d13a93128621781719190a2a7a60 | 676,814 |
import argparse
def get_argument_parser():
"""
Return argument parser.
:return: parser
"""
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
description="ARM App manager test case generator",
)
parser.add_argument(
"-o",
... | 1c608fb3092a7c87b2cd3c719213a2a049f8f8b3 | 676,815 |
def GetMediaComponents(media_str, media_dict, mixAttr, mix):
"""
Args:
media_str: (str) Media name
media_dict: (d)
media (str) -> list<compound_l>
where compound_l list<compound (str), concentration (str), units (str)>
e.g. [Ammonium chloride, 0.25, g... | a2b855fb9c194a22a39fb75fb6975bd546fac727 | 676,816 |
def convertConfigDict(origDict, sep="."):
"""
For each key in the dictionary of the form <section>.<option>,
a separate dictionary for is formed for every "key" - <section>,
while the <option>s become the keys for the inner dictionary.
Returns a dictionary of dictionary.
"""
... | da4952ee883cd3d2d0d01e64f9055c22a277a16f | 676,817 |
def parse_csv_data(csv_filename: str) -> list[str]:
"""Returns a list of strings representing each row in a given file"""
file = open("data/" + csv_filename, "r", encoding="utf-8")
lstrows = []
for line in file:
lstrows.append(line.rstrip())
file.close()
return lstrows | f4c4fe8d1f5b1cf1f0355269dc2a566603e2dd55 | 676,818 |
def merge_means(mu1, mu2, n1, n2):
"""Merges means. Requires n1 + n2 > 0."""
total = n1 + n2
return (n1 * mu1 + n2 * mu2) / total | 22659748d2046e0eb78b8210fbf62bd9e57b447f | 676,819 |
def int2bool(intvar):
"""Method converts number to bool
Args:
intvar (int): number
Returns:
bool: result
"""
result = False
intvar = int(intvar)
if intvar > 0:
result = True
return result | 92c69d90055c8365c0c1241db8eafa210c97c051 | 676,820 |
import six
def get_comparable_revisits(query_metadata_table):
"""Return a dict location -> set of revisit locations for that starting location."""
revisit_origins = {
query_metadata_table.get_revisit_origin(location)
for location, _ in query_metadata_table.registered_locations
}
inter... | 02c8bd7c028f3ce688098cc836b0e174e1113dc6 | 676,821 |
import time
def base_info():
"""需要修改租户"""
tenant_code = 'ghac'
now_time = time.strftime('%Y%m%d%H%M', time.localtime())
return tenant_code + '-' + now_time + '-temp' | 111bdc49784bbfc10f37324357bb02dc7510c21c | 676,822 |
def torch_to_np(images):
"""Transforms the unnormalized output of a gan into a numpy array
Args:
images (torch.tensor): unnormalized output of a gan
Returns:
(numpy.array)
"""
return ((images.clamp(min=-1, max=1) + 1) / 2).permute(0, 2, 3, 1).cpu().detach().numpy() | 136788112a33ee80a88b4931973416bb0b2bd466 | 676,824 |
import string
import random
def generate_id():
"""Generate unique id for the order"""
alphabet = string.ascii_letters.upper() + string.digits
order_id = ''.join(random.choice(alphabet) for i in range(8))
return order_id | 2200c2d09df76dd5b45180ea0ca1422482408fcc | 676,825 |
def lookup_dunder_prop(obj, props, multi=False):
"""
Take an obj and lookup the value of a related attribute
using __ notation.
For example if Obj.a.b.c == "foo" then lookup_dunder (Obj, "a__b__c") == "foo"
"""
try:
if "__" in props:
head, tail = props.split("__", 1)
... | 58e173c161d2b846b2e8268698c4ea73f21381f0 | 676,826 |
def compose_plots(objects, epoch, title=''):
"""Compose a single plot from several objects associated with
subplots of a single figure.
Parameters
----------
objects: list of plot objects
Plot objects returned using one of the 'build' methods of the
Replay class. All the correspondi... | 8820bdf7595a9551674562c99a2e44d17db2b1c2 | 676,827 |
import operator
def filter_prefix(candidates: set[str], prefix: str = '', ones_operator=operator.ge) -> int:
"""Filter a set of binary number strings by prefix, returning a single int.
This function considers a set of candidate strings, which must encode
valid binary numbers. They are iteratively filtere... | 32480781186e0c347c954c3b63dc988274fb4f8d | 676,828 |
import torch
def precisionk(actual, predicted, topk=(1, 5)):
"""
Computes the precision@k for the specified values of k.
# Parameters
actual : `Sequence[Sequence[int]]`, required
Actual labels for a batch sized input.
predicted : `Sequence[Sequence[int]]`, required
Predicted labels f... | 1cb21a572b46f8f35396efb4e79df09ae51ebbfa | 676,829 |
import math
def tdis(x, n):
"""
【函数说明】
功能:标准正态分布的概率密度函数(t Distribution)
参数:
+ x:[float 浮点型] 某个样本点(x)的横坐标值
+ n:[float 浮点型]
返回值:
+ [float 浮点型] 该样本点(x)处的概率密度
"""
y = math.gamma((n+1)/2)/(math.sqrt(math.pi*n) *
math.gamma(n/2)) * (1+(x**2/n))**(-(n+... | 338bb4364017daf063b6fd339898b762fe319389 | 676,830 |
def medhx_6a_notes(studydata, column, context):
"""Please append " times" to each number."""
return column.mask(column.notna(), column.astype(str) + ' times' ) | 43dc785383955e0d7a4f2b9cf3c5edd4b0d1a3b0 | 676,831 |
def image_size(img):
"""
Gets the size of an image eg. 350x350
"""
return tuple(img.shape[1:: -1]) | 6df3b7cf05f6388930235603111572254fa89c10 | 676,832 |
def revcomp(s):
"""Returns the reverse compliment of a sequence"""
t = s[:]
t.reverse()
rc = {'A':'T', 'C':'G', 'G':'C', 'T':'A', 'N':'N'}
t = [rc[x] for x in t]
return t | f0378f8595e6902bed46bda0b8689f34df34f07f | 676,834 |
def parse_visitor(d):
""" Used to parse name of visiting team.
"""
return str(d.get("tUNaam", "")) | c715f0888dbcfef614ba3f519d60d80f9eb76bee | 676,835 |
def get_values(map, key):
"""
Get teh value for the key and remove the path from the route map
Args:
map:
key:
Returns:
"""
res = None
for t in map:
if t[0] == key:
res = t[1]
map.remove(t)
return map, res | 3bc2c190561c6043df7c0ff90f9c042445da12d5 | 676,836 |
def relu(x, c = 0):
"""
Compute the value of the relu function with parameter c, for a given point x.
:param x: (float) input coordinate
:param c: (float) shifting parameter
:return: (float) the value of the relu function
"""
return c + max(0.0, x) | b25cda42282ab723fa4448d378ece0f6519c1e2e | 676,838 |
import os
def get_file_parts(filename):
"""Extracts the basename and extension parts of a filename.
Identifies the extension as everything after the last period in filename.
Args:
filename: string containing the filename
Returns:
A tuple of:
A string containing the basename... | 9d0cf5159000f4c136f92ab45f85984ff58b3481 | 676,839 |
def GetPODAttrsValue(obj_def, exceptions=None):
"""Returns a list of values for attributes in POD object definitions.
This method does not work for instances. It also will not return private
data members.
Args:
obj_def: The object definition. (class definition)
exceptions: Attributes to ignore. (list... | cd0594307ec5417fdee778146c08557e216bf321 | 676,841 |
import struct
def wire_msg_from_msg(msg):
"""Converts the given msg to wire format.
Args:
msg ([uint64_t, capnp_obj]): A 2-element list, where the first element is the capnp id of
the message, and the second element is the capnp object.
"""
wire_msg = []
# Pack first element a... | 8bcb7523f8a136f12ddf5418d716eb6b724627be | 676,844 |
import os
def _read_requirements(file_name):
"""
Returns list of required modules for 'install_requires' parameter. Assumes
requirements file contains only module lines and comments.
"""
requirements = []
with open(os.path.join(file_name)) as f:
for line in f:
if not line.s... | aee1640c380d4ec0d284c084d643c2146a9204ac | 676,845 |
def removeCharsetFromMime(s):
"""
Löscht z.B. die Zeichenkette C{UTF-8} aus der Zeichenkette
C{text/xml;UTF-8} heraus, sodass nur C{text/xml} zurückgegeben wird.
B{Beispiel}:
>>> s = "text/xml;UTF-8"
>>> removeCharsetFromMime(s)
"text/xml"
@param s: Zeichenkette C{text/xml;UTF-8}
... | 710f1d3593846b275477d1428da7ae76bba81d2b | 676,846 |
def accessedTable(
data,
sql,
verbose):
"""Extract the accessed table from the specified data"""
# making function more explicit
data = data
sql = sql
verbose = verbose
# inform user of program progress
if verbose >= 2:
print(
"Extracting the ... | c8c177cfc30b26000a194add5e5f3ced9fcf72be | 676,847 |
import glob
import os
def find_env_paths_in_basedirs(base_dirs):
"""Returns all potential envs in a basedir"""
# get potential env path in the base_dirs
env_path = []
for base_dir in base_dirs:
env_path.extend(glob.glob(os.path.join(
os.path.expanduser(base_dir), '*', '')))
# s... | 1587cf50eff41ea67e1b3a5277df8eb5352f69ed | 676,848 |
def finish(result, num_run):
"""
:param result: str, the string that composed randomly by H and T
:param num_run: int, the number of runs that the player decided
:return: bool, return when the result fits the number of runs
"""
n = 0
for i in range(len(result)-2):
if result[i] == result[i+1] and result[i+1] !=... | 1f8031cf02188604994df94ce3bb22c37201b977 | 676,849 |
from pathlib import Path
def is_notebook(path: Path) -> bool:
"""
Checks whether the given file path is Jupyter Notebook or not.
Parameters
----------
path: Path
Path of the file to check whether it is Jupyter Notebook or not.
Returns
------
Returns True when file is Jupyter N... | b1400fb72af69204d62ef81f6abaa13a6859ba5a | 676,850 |
def is_highlighted_ins(e):
"""Returns True if e matches the following pattern:
<ins>highlighted</ins> text:
See `fragment_chunks` comment for the details
"""
if len(e) != 0:
return False
if not e.text:
return False
if e.text != 'highlighted':
return False
i... | e5d60aef35f3085f3105fc23d3420200e36341bf | 676,851 |
import re
def build_main_content(mc_lines, ref_map):
"""
Builds main content lines but renumbering the footnotes. Filters any
footnotes in the main content with their new re-numbered instances.
"""
outlines = []
# Since we're re-filtering the same line multiple times, we replace
# <sup></... | 0cb7872b6fcc32e0a7b27eb39468ba0fdaf55212 | 676,852 |
async def admin(mixer):
"""Generate an admin user."""
admin = mixer.blend('example.models.User', email='admin@example.com', is_super=True)
admin.password = admin.generate_password('pass')
return await admin.save(force_insert=True) | 6c51b6849d5ae0dbbaac6e1efd53f0766ebf96fb | 676,853 |
def bw24(x):
"""Return the bit weight of the lowest 24 bits of x"""
x = (x & 0x555555) + ((x & 0xaaaaaa) >> 1)
x = (x & 0x333333) + ((x & 0xcccccc) >> 2)
x = (x + (x >> 4)) & 0xf0f0f
return (x + (x >> 8) + (x >> 16)) & 0x1f | 72ec0e3f920c79f37e2dd3cbd571e6bfe07eb92e | 676,854 |
import time
def toJulian(year, month, day):
"""
Use time functions
"""
dateString = str(year) + ' ' + str(month) + ' ' + str(day) + ' UTC'
tup = time.strptime(dateString, '%Y %m %d %Z')
sec = time.mktime(tup)
days = (sec - time.timezone) / 86400.0 # Cancel time zone correction
jday = ... | 0bd16482e7d2a87bd628b6d6e485573de1e5c379 | 676,855 |
def project_data(samples, U, K):
"""
Computes the reduced data representation when
projecting only on to the top "K" eigenvectors
"""
# Reduced U is the first "K" columns in U
reduced_U = U[:, :K]
return samples.dot(reduced_U) | a955adeaa6b45fd3d46cc3866e6acf414769692c | 676,857 |
def num_ast_nodes(repo):
"""Total number of ast nodes; a measure of code volume."""
nodes = sum(count for count in repo._calc('ast_node_counts').values())
nodes += 1 # used as relative, don't want 0
return nodes | beee1635f6ef7cd82ad802bd8548101ad504d1d6 | 676,859 |
def ROStime_to_NTP64(ROStime):
""" Convert rospy.Time object to a 64bit NTP timestamp
@param ROStime: timestamp
@type ROStime: rospy.Time
@return: 64bit NTP representation of the input
@rtype: int
"""
NTPtime = ROStime.secs << 32
# NTPtime |= nanoseconds * 2^31 / 1x10^9
NTPtime |= i... | 4f0cb267ce37fee3671a705ff292c31c6d7e3f28 | 676,860 |
import zipfile
import os
def create_zip(path, zip_filename):
"""save content to file.
Args:
path: directory to zip
zip_filename: full path to new created zip file.
"""
try:
ziph = zipfile.ZipFile(zip_filename, "w", zipfile.ZIP_DEFLATED)
for root, _, files in os.walk(path):
for file2 in... | f24278d76372ce2ac48b3773a5f3198b09542c07 | 676,861 |
def _minmax(dataframe):
"""Transform features by rescaling each feature to the range between 0 and 1.
The transformation is given by:
scaled_value = (feature_value - min) / (mix - min)
where min, max = feature_range.
This transformation is often used as an alternative to zero mean,
unit v... | d82711eeb7204213b4499df450c1d92258bf4c80 | 676,863 |
def test_integrity(param_test):
"""
Test integrity of function
"""
# find the test that is performed and check the integrity of the output
index_args = param_test.default_args.index(param_test.args)
# Removed because of:
# https://travis-ci.org/neuropoly/spinalcordtoolbox/jobs/482061826
... | c098bb775d85e89f9c82b30428279fd5906e8930 | 676,865 |
def reverse_dict(dictionary):
"""Reverse a dictionary.
Keys become values and vice versa.
Parameters
----------
dictionary : dict
Dictionary to reverse
Returns
-------
dict
Reversed dictionary
Raises
------
TypeError
If there is a value which is un... | f904adeee1e6ed25995d16a080c557dcbea5fa1e | 676,866 |
def dtft(xn):
"""离散时间傅里叶变换
:Parameters:
- xn: 离散非周期序列,序列只能有1个自变量
:Returns: 频谱密度函数(周期连续信号),自变量为Omega(用W表示)
"""
raise Exception("Can't sum from -oo to oo")
n = tuple(xn.free_symbols)[0]
W = sy.symbols('W')
r = (n, -sy.oo, sy.oo)
xW = sy.Sum(xn * sy.exp(-sy.I * W * n), r)
... | 2df9df6d45113d2161d9b076eded1c62663b76a0 | 676,867 |
import os
def get_all_ini_files():
"""
collect all ini files in the current folder
:return: a list of sorted file names
"""
current_path = os.getcwd()
all_files = os.listdir(current_path)
ini_files = []
for item in all_files:
if os.path.isfile(item) and item.endswith('.ini'):... | 669c3acc71bc109188a7ff85ac159a447f1a4b88 | 676,868 |
def expp_xor_indep(p1, p2):
"""
Probability of term t1 XOR t2 being 1 if t1 is 1 with p1 and t2 is 1 with p2.
t1 and t2 has to be independent (no common sub-term).
Due to associativity can be computed on multiple terms: t1 ^ t2 ^ t3 ^ t4 = (((t1 ^ t2) ^ t3) ^ t4) - zipping.
XOR:
a b | r
... | d1f59639472c25d257776a8e8a420856e38cfdd8 | 676,869 |
def noOut(_):
"""Outputs nothing."""
return None | 2eff0768a4861b023fa055b0a34c1ffae6988740 | 676,870 |
import torch
def conv3x3(in_channel, out_channel, stride=1, padding=1,dilation=1, bias=True):
"""3x3 convolution with padding"""
return torch.nn.Conv2d(in_channel,
out_channel,
kernel_size=(3,3),
stride=(stride,stride),
... | f8eb7ceb844dd9527c9159e17209fbd547fc7dd9 | 676,871 |
def length_of_range(range):
"""Helper- returns the length of a range from start to finish in ms"""
return range[1] - range[0] | d4a3a423c85310d3d679ffe97fc37ff88f406c7c | 676,872 |
def listify(x, none_value=[]):
"""Make a list of the argument if it is not a list."""
if isinstance(x, list):
return x
elif isinstance(x, tuple):
return list(x)
elif x is None:
return none_value
else:
return [x] | 3382cf9389815737085d58d000c454e56b0ca906 | 676,873 |
import os
def safe_pjoin(dirname, *args):
"""
Join path components with os.path.join, skipping the first component
if it is None.
"""
if dirname is None:
return os.path.join(*args)
else:
return os.path.join(dirname, *args) | a80a3571866d81153dc0f88b4a636bcc3aeebd70 | 676,874 |
import argparse
def parameter_parser():
"""
A method to parse up command line parameters. By default it gives an embedding of the partial NCI1 graph dataset.
The default hyperparameters give a good quality representation without grid search.
Representations are sorted by ID.
"""
parser = argp... | 3f89bf6c6f5420d321b5caa0e68aadd33e1aa51e | 676,875 |
def EqualVersions(version, baseline):
"""Test that a version is acceptable as compared to the baseline.
Meant to be used to compare version numbers as returned by a package itself
and not user input.
Args:
version: distutils.version.LooseVersion.
The version that is being checked.
baseline: di... | 65d499363236ae295008ac3d4e2c61c181d1546b | 676,876 |
import os
def exists(file_name):
""" Checks to see if a file exists.
Args:
file_name: The file to check if it exists.
Returns:
True if it exists, False otherwise.
"""
return os.path.exists(file_name) | 4ab168e06c233ec83f9553189e97c6ab337520cd | 676,877 |
import os
def incoming_paths(root_dir, parent_dir):
"""Create a set of paths in which the victims of tree conflicts are
children of PARENT_DIR. ROOT_DIR should be a shallower directory
in which items "F1" and "D1" can pre-exist and be shared across
multiple parent dirs."""
return {
'F1' : os.pa... | a0fd9da9ffcae7f5452c10544912183bcefba83f | 676,878 |
def unique(iterable):
"""Return an iterable of the same type which contains unique items.
This function assumes that:
type(iterable)(list(iterable)) == iterable
which is true for tuples, lists and deques (but not for strings)
>>> unique([1, 2, 3, 1, 2, 3, 4, 2, 3, 4, 1, 1, 2])
[1, 2, 3, 4]
... | c65a7e4f75d9678e28e70e4a1a2b2679a02bab8d | 676,879 |
def qc_syntax_test(self):
"""
It verifies that wf.data contains the recomentated data structure to pass
the rest of the QC test. Each parameter (for example, TEMP) and each index
(for example, TIME) must have a column with the flags of the values
(for example, TEMP_QC and TIME_QC).
Returns
... | e151f3e407dcc43096903f82f5a15d614f6a4b2a | 676,880 |
def modified(number, percent):
"""return the amount (or any other number) with added margin given by percent parameter
(result has type float)
"""
if percent:
return number * (100 + percent) / 100.
else:
return float(number) | 7421d717caed71da840d0bae644a1f95d517777b | 676,881 |
def print_bytearray(array: bytearray) -> str:
"""Outputs string of all bytes in HEX without any formatting.
Parameters
----------
array : byte array
The byte array to be printed.
Returns
-------
str
A string representation of the byte array in HEX format.
"""
string... | 1f672598153f676169d93c330e16c591794651b3 | 676,882 |
def format_size(size):
"""Convert a size in bytes into a human readable string.
Example
-------
::
>>>format_size(2.25*1024)
'2.25 kB'
Parameters
----------
size : int
Size in bytes.
Returns
-------
str
"""
for unit in ['bytes', 'kB', 'MB']:
... | 0d3a0e300a49fee425c15c6e67a96ab8c27204f4 | 676,883 |
def get_row_nnz(mat, row):
"""Return the number of nonzeros in row.
"""
return mat.indptr[row+1] - mat.indptr[row] | a588e245763eb1cd237c9d2f71efacd7b27387c8 | 676,884 |
def vector(v, specs):
"""
Stub for conversion that isn't needed in python case.
(Convert a 1D numpy array to python.)
Parameters
----------
v : numpy array
1D array to convert.
specs : dictionary
Dictionary of user-specified and default parameters to formatting
Returns... | eb18cfd60e6fe83b479e2823b196e20e669fcfe2 | 676,885 |
def test():
""" Return a test message.
"""
return 'The web server is up and running.' | 1cedf1302fdf5bca3a5259bd57a0e78b789e40b5 | 676,886 |
def NEST(*args):
""" NEST generates nested names for steps """
return '.'.join(args) | 435bc01a7e56de5d864ef44420b9f4fa1f6db64c | 676,887 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.