uid stringlengths 24 24 | split stringclasses 1
value | category stringclasses 2
values | content stringlengths 5 482k | signature stringlengths 1 14k | suffix stringlengths 1 482k | prefix stringlengths 9 14k | prefix_token_count int64 3 5.01k | prefix_token_budget int64 64 256 | element_token_count int64 1 292k | signature_token_count int64 1 5.01k | prefix_context_token_count int64 0 255 | repo stringlengths 7 112 | path stringlengths 4 208 | language stringclasses 1
value | name stringlengths 1 218 | qualname stringlengths 1 218 | start_line int64 1 26.7k | end_line int64 1 26.7k | signature_start_line int64 1 26.7k | signature_end_line int64 1 26.7k | source_hash stringlengths 40 40 | source_dataset stringclasses 1
value | source_split stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d4ee8086d4b50a11179572f8 | train | function | def implies(a, b):
return not a or b
| def implies(a, b):
| return not a or b
| n'
# TODO - keep track of several seeds to use
def set_deterministic(seed=0):
random.seed(seed)
import numpy
numpy.random.seed(seed)
# TODO - still not quite deterministic
# NOTE - it may be because of set iteration
def implies(a, b):
| 64 | 64 | 13 | 6 | 57 | nishadg246/stripstream-ivan-nishad | stripstream/utils.py | Python | implies | implies | 26 | 27 | 26 | 26 | cf174d5a010c0b15cb10a3c02fc47ca703576764 | bigcode/the-stack | train |
8c35270077f0dd91e9904412 | train | function | def remove_dir(d):
if os.path.exists(d):
shutil.rmtree(d)
| def remove_dir(d):
| if os.path.exists(d):
shutil.rmtree(d)
| with open(filename, 'rb') as f:
return pickle.load(f)
def ensure_dir(f):
d = os.path.dirname(f)
if not os.path.exists(d):
os.makedirs(d)
def safe_remove(p):
if os.path.exists(p):
os.remove(p)
def remove_dir(d):
| 64 | 64 | 18 | 5 | 59 | nishadg246/stripstream-ivan-nishad | stripstream/utils.py | Python | remove_dir | remove_dir | 84 | 86 | 84 | 84 | a83494dbbf5d2ca0e2be1d911c68c324e58639f9 | bigcode/the-stack | train |
a3d3e867216f68d87c900a12 | train | function | def first(function, iterable):
for item in iterable:
if function(item):
return item
return None
| def first(function, iterable):
| for item in iterable:
if function(item):
return item
return None
| =1):
n = start
while n < end:
yield n
n += step
def argmin(function, sequence):
values = list(sequence)
scores = [function(x) for x in values]
return values[scores.index(min(scores))]
def first(function, iterable):
| 63 | 64 | 25 | 6 | 58 | nishadg246/stripstream-ivan-nishad | stripstream/utils.py | Python | first | first | 45 | 49 | 45 | 45 | dea3f5cc4af0a9e5c147605a55178ee10f755a76 | bigcode/the-stack | train |
ab50a57bc814874947dea7ce | train | function | def write_pickle(filename, data): # NOTE - cannot pickle lambda or nested functions
with open(filename,'wb') as f:
pickle.dump(data, f)
| def write_pickle(filename, data): # NOTE - cannot pickle lambda or nested functions
| with open(filename,'wb') as f:
pickle.dump(data, f)
| sequence[i]
##################################################
def read(filename):
with open(filename, 'r') as f:
return f.read()
def write(filename, string):
with open(filename, 'w') as f:
f.write(string)
def write_pickle(filename, data): # NOTE - cannot pickle lambda or nested functions
| 64 | 64 | 34 | 17 | 47 | nishadg246/stripstream-ivan-nishad | stripstream/utils.py | Python | write_pickle | write_pickle | 67 | 69 | 67 | 67 | 13c8e405d3c74f7596438979b42a72c560138fb5 | bigcode/the-stack | train |
500e927cf2bdd8c2b54f3041 | train | function | def set_deterministic(seed=0):
random.seed(seed)
import numpy
numpy.random.seed(seed)
| def set_deterministic(seed=0):
| random.seed(seed)
import numpy
numpy.random.seed(seed)
| (n=85):
return '\n'+n*'-'+'\n'
def header(s, n=10):
return '\n' + n*'-' + s + n*'-'+'\n'
# TODO - keep track of several seeds to use
def set_deterministic(seed=0):
| 64 | 64 | 24 | 9 | 54 | nishadg246/stripstream-ivan-nishad | stripstream/utils.py | Python | set_deterministic | set_deterministic | 19 | 22 | 19 | 19 | 6aa4fb8e2222277556258a229f93fd5c95795907 | bigcode/the-stack | train |
e95e9260443ef423276e57a9 | train | function | def set_union(sequence):
return set().union(*sequence) | def set_union(sequence):
| return set().union(*sequence) | Thistle',
'Tomato', 'Turquoise', 'Violet', 'Wheat', 'Yellow', 'YellowGreen']
GRAPH_VIZ_SHAPES = ['box', 'oval', 'square', 'circle']
# http://www.graphviz.org/doc/info/shapes.html
def set_union(sequence):
| 64 | 64 | 13 | 5 | 58 | nishadg246/stripstream-ivan-nishad | stripstream/utils.py | Python | set_union | set_union | 114 | 115 | 114 | 114 | 79dc05318994e4b169ffd5b0eab06a85041f6c80 | bigcode/the-stack | train |
6a1f56f9d6bc5eaa202b6e4e | train | function | def random_sequence(sequence):
indices = range(len(sequence))
shuffle(indices)
for i in indices:
yield sequence[i]
| def random_sequence(sequence):
| indices = range(len(sequence))
shuffle(indices)
for i in indices:
yield sequence[i]
| argmin(function, sequence):
values = list(sequence)
scores = [function(x) for x in values]
return values[scores.index(min(scores))]
def first(function, iterable):
for item in iterable:
if function(item):
return item
return None
def random_sequence(sequence):
| 64 | 64 | 27 | 5 | 58 | nishadg246/stripstream-ivan-nishad | stripstream/utils.py | Python | random_sequence | random_sequence | 51 | 55 | 51 | 51 | 5722824d4e46f570c431cb943d72a37abeca1b09 | bigcode/the-stack | train |
1c6faa2ac94afff297ffe11b | train | function | def flatten(iterable_of_iterables):
return (item for iterables in iterable_of_iterables for item in iterables)
| def flatten(iterable_of_iterables):
| return (item for iterables in iterable_of_iterables for item in iterables)
| istic(seed=0):
random.seed(seed)
import numpy
numpy.random.seed(seed)
# TODO - still not quite deterministic
# NOTE - it may be because of set iteration
def implies(a, b):
return not a or b
##################################################
def flatten(iterable_of_iterables):
| 64 | 64 | 26 | 8 | 56 | nishadg246/stripstream-ivan-nishad | stripstream/utils.py | Python | flatten | flatten | 31 | 32 | 31 | 31 | f3f82a49906aa2c037f4d5ad2c1ce59b53914d3d | bigcode/the-stack | train |
545d59aac3c677c72cfaad99 | train | class | class TestUtils(unittest.TestCase):
"""Testing methods for util functions."""
def setUp(self):
"""Initialize the test variables and configuration."""
self.current_dir = os.path.dirname(os.path.abspath(__file__))
def test_parsed_columns(self):
"""Check column parsing has the desired... | class TestUtils(unittest.TestCase):
| """Testing methods for util functions."""
def setUp(self):
"""Initialize the test variables and configuration."""
self.current_dir = os.path.dirname(os.path.abspath(__file__))
def test_parsed_columns(self):
"""Check column parsing has the desired effect."""
df = pandas.Data... | # -*- coding: utf-8 -*-
"""Unit tests for utils module."""
import os
import filecmp
import unittest
import pandas
import etlstat.text.utils as utils
class TestUtils(unittest.TestCase):
| 44 | 86 | 288 | 7 | 36 | masego24/etlstat | etlstat/text/test/test_utils.py | Python | TestUtils | TestUtils | 11 | 39 | 11 | 11 | 6590b35594138c9f962203fae142b88e59b1d590 | bigcode/the-stack | train |
95bcd60b61e700da3a247910 | train | function | def write_quotes(quotes):
with open("quotes.csv", "w", encoding='utf-8', newline= '') as file:
headers = ["text", "author", "bio-link"]
csv_writer = DictWriter(file, fieldnames=headers)
csv_writer.writeheader()
for quote in quotes:
csv_writer.writerow(quote)
| def write_quotes(quotes):
| with open("quotes.csv", "w", encoding='utf-8', newline= '') as file:
headers = ["text", "author", "bio-link"]
csv_writer = DictWriter(file, fieldnames=headers)
csv_writer.writeheader()
for quote in quotes:
csv_writer.writerow(quote)
| ").get_text(),
"bio-link": quote.find("a")["href"]
})
next_btn = soup.find(class_="next")
url = next_btn.find("a")["href"] if next_btn else None
sleep(2)
return quotes_list
def write_quotes(quotes):
| 64 | 64 | 72 | 6 | 57 | James-AR/scraping_game | scraper.py | Python | write_quotes | write_quotes | 30 | 36 | 30 | 30 | 8806626250d2d9a2a9983dfe9827232851da4e7e | bigcode/the-stack | train |
9d79de7603d1809a18852f23 | train | function | def scrape_quotes():
quotes_list = []
url = "/page/1"
while url:
response = requests.get(f"{BASE_URL}{url}")
response.encoding = 'utf-8'
print(f"scraping {BASE_URL}{url}")
soup = BeautifulSoup(response.text, 'html.parser')
quotes = soup.find_all(class_="quote")
... | def scrape_quotes():
| quotes_list = []
url = "/page/1"
while url:
response = requests.get(f"{BASE_URL}{url}")
response.encoding = 'utf-8'
print(f"scraping {BASE_URL}{url}")
soup = BeautifulSoup(response.text, 'html.parser')
quotes = soup.find_all(class_="quote")
for quote ... | import requests
from bs4 import BeautifulSoup
from random import choice
from time import sleep
from csv import DictWriter
BASE_URL = "http://quotes.toscrape.com/"
def scrape_quotes():
| 43 | 64 | 171 | 4 | 39 | James-AR/scraping_game | scraper.py | Python | scrape_quotes | scrape_quotes | 9 | 28 | 9 | 9 | 9e95346981c97cdef9cbcdf9cf38186ab46feb1a | bigcode/the-stack | train |
339ecb09b001c1f275f2bf90 | train | class | class CSIVXFlexOS(pulumi.CustomResource):
def __init__(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
api_version: Optional[pulumi.Input[str]] = None,
kind: Optional[pulumi.Input[str]] = None,
metadata... | class CSIVXFlexOS(pulumi.CustomResource):
| def __init__(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
api_version: Optional[pulumi.Input[str]] = None,
kind: Optional[pulumi.Input[str]] = None,
metadata: Optional[pulumi.Input[pulumi.InputType['... | # coding=utf-8
# *** WARNING: this file was generated by crd2pulumi. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from ... import _utilities, _tables
from . import outp... | 121 | 256 | 1,032 | 12 | 109 | pulumi/pulumi-kubernetes-crds | operators/dell-csi-operator/python/pulumi_pulumi_kubernetes_crds_operators_dell_csi_operator/storage/v1/CSIVXFlexOS.py | Python | CSIVXFlexOS | CSIVXFlexOS | 17 | 118 | 17 | 17 | e548fb441cdd462af03ebba9c81e5e8c3b8fe623 | bigcode/the-stack | train |
86f5815df375e5ea3a6216b4 | train | function | def get_item(dictionary, item):
return dictionary.get(item)
| def get_item(dictionary, item):
| return dictionary.get(item)
| from django.template import Library
def get_item(dictionary, item):
| 13 | 64 | 13 | 7 | 5 | pixan198/developer-search | search/templatetags/search_extras.py | Python | get_item | get_item | 4 | 5 | 4 | 4 | ab8ecbc9a7144753d9fc1004a472eb16afd3726e | bigcode/the-stack | train |
9b4b0e5543e3ab0d0c159c73 | train | function | def parse_haproxy_conf(file_path):
section_regex = r'^(\w+)'
option_regex = r'^(?:\s+)(\w+(?:\s+\w+)*?)\s+([\w/]*)$'
return generic_ini_style_conf_parser(file_path, section_regex,
option_regex)
| def parse_haproxy_conf(file_path):
| section_regex = r'^(\w+)'
option_regex = r'^(?:\s+)(\w+(?:\s+\w+)*?)\s+([\w/]*)$'
return generic_ini_style_conf_parser(file_path, section_regex,
option_regex)
| {}
match_option = re.match(option_regex, line)
if match_option and current_section:
option = re.sub(r'\s+', ' ', match_option.group(1))
config[current_section][option] = match_option.group(2)
return config
def parse_haproxy_conf(file_path):
| 64 | 64 | 68 | 9 | 54 | strider/validations-common | validations_common/library/haproxy_conf.py | Python | parse_haproxy_conf | parse_haproxy_conf | 65 | 69 | 65 | 65 | 988da93a373edd8f5c7cf45eabd458d34f96a76f | bigcode/the-stack | train |
bd8aa75c177dff981b53bd26 | train | function | def main():
module = AnsibleModule(
argument_spec=yaml_safe_load(DOCUMENTATION)['options']
)
haproxy_conf_path = module.params.get('path')
try:
config = parse_haproxy_conf(haproxy_conf_path)
except IOError:
module.fail_json(msg="Could not open the haproxy conf file at: '%s'... | def main():
| module = AnsibleModule(
argument_spec=yaml_safe_load(DOCUMENTATION)['options']
)
haproxy_conf_path = module.params.get('path')
try:
config = parse_haproxy_conf(haproxy_conf_path)
except IOError:
module.fail_json(msg="Could not open the haproxy conf file at: '%s'" %
... | _path):
section_regex = r'^(\w+)'
option_regex = r'^(?:\s+)(\w+(?:\s+\w+)*?)\s+([\w/]*)$'
return generic_ini_style_conf_parser(file_path, section_regex,
option_regex)
def main():
| 64 | 64 | 108 | 3 | 61 | strider/validations-common | validations_common/library/haproxy_conf.py | Python | main | main | 72 | 85 | 72 | 72 | ef549741168faf605239ec08606d32086a26d018 | bigcode/the-stack | train |
663f53b1e8db65c817fae406 | train | function | def generic_ini_style_conf_parser(file_path, section_regex, option_regex):
config = {}
current_section = None
with open(file_path) as config_file:
for line in config_file:
match_section = re.match(section_regex, line)
if match_section:
current_section = match_... | def generic_ini_style_conf_parser(file_path, section_regex, option_regex):
| config = {}
current_section = None
with open(file_path) as config_file:
for line in config_file:
match_section = re.match(section_regex, line)
if match_section:
current_section = match_section.group(1)
config[current_section] = {}
m... | . Luckily They have
# a syntax approaching ini config file so they are relatively easy to parse.
# This generic ini style config parser is not perfect -- it can ignore some
# valid options -- but good enough for our use case.
def generic_ini_style_conf_parser(file_path, section_regex, option_regex):
| 64 | 64 | 129 | 15 | 49 | strider/validations-common | validations_common/library/haproxy_conf.py | Python | generic_ini_style_conf_parser | generic_ini_style_conf_parser | 49 | 62 | 49 | 49 | f77b0bfe2cfcf38875b08de3f75ea45e2f7f4fda | bigcode/the-stack | train |
0d41a6dec34bd78f11a05f80 | train | class | class PlasticcTransformer:
def __init__(self, make_splines=False):
self.make_splines = make_splines
def __call__(self, curve, meta):
"Converts the dataframe/series into tensors"
curve = torch.from_numpy(curve[['mjd', 'flux', 'flux_err']].values).float()
curve[:, 0] = curve[:, 0]... | class PlasticcTransformer:
| def __init__(self, make_splines=False):
self.make_splines = make_splines
def __call__(self, curve, meta):
"Converts the dataframe/series into tensors"
curve = torch.from_numpy(curve[['mjd', 'flux', 'flux_err']].values).float()
curve[:, 0] = curve[:, 0] - curve[0, 0] # the time ... | _workers,
shuffle=True)
def val_dataloader(self):
return data.DataLoader(self.plasticc_val, batch_size=self.batch_size, num_workers=self.num_workers,
shuffle=True)
def test_dataloader(self):
return data.DataLoader(self.plasticc_test... | 88 | 88 | 295 | 5 | 83 | kschamplin/astro-classifier-neo | src/pytorch_test/plasticc/datasets.py | Python | PlasticcTransformer | PlasticcTransformer | 61 | 83 | 61 | 61 | 5e3c266e6e3360143d5280e1246a78fc31dcee12 | bigcode/the-stack | train |
d6c9ef3eb96c2b7f251820d6 | train | function | def _gunzip(data_dir):
# unzips all the files
# get list of all gz files
gzs = data_dir.glob('*.gz')
for gzpath in tqdm(gzs):
with gzip.open(gzpath, 'rb') as input_file:
with open(gzpath.parent / gzpath.stem, 'wb') as output:
shutil.copyfileobj(input_file, output)
| def _gunzip(data_dir):
# unzips all the files
# get list of all gz files
| gzs = data_dir.glob('*.gz')
for gzpath in tqdm(gzs):
with gzip.open(gzpath, 'rb') as input_file:
with open(gzpath.parent / gzpath.stem, 'wb') as output:
shutil.copyfileobj(input_file, output)
| for data in r.iter_content(bs):
dest.write(data)
pbar.update(len(data))
md5.update(data)
print(md5.hexdigest())
pbar.close()
def _gunzip(data_dir):
# unzips all the files
# get list of all gz files
| 64 | 64 | 89 | 25 | 39 | kschamplin/astro-classifier-neo | src/pytorch_test/plasticc/datasets.py | Python | _gunzip | _gunzip | 117 | 124 | 117 | 119 | dd7b1e1759bd7731a51f4a549f943eb65fd23305 | bigcode/the-stack | train |
61d7113edec499b4915cc456 | train | class | class PlasticcDataModule(LightningDataModule):
def __init__(self, data_path: Path = Path("./data"), download=False, batch_size: int = 50, num_workers=8, use_splines=False):
super().__init__()
self.data_path = Path(data_path)
self.download = download
self.batch_size = batch_size
... | class PlasticcDataModule(LightningDataModule):
| def __init__(self, data_path: Path = Path("./data"), download=False, batch_size: int = 50, num_workers=8, use_splines=False):
super().__init__()
self.data_path = Path(data_path)
self.download = download
self.batch_size = batch_size
self.num_workers = num_workers
self.... | # Handles the plasticc dataset loading/conversion
import torch
import torch.utils.data as data
from torchvision import transforms
import pandas as pd
import pyarrow.feather as feather
from pytorch_lightning import LightningDataModule
from pathlib import Path
from tqdm.auto import tqdm
import torchcde
import hashlib
imp... | 115 | 118 | 396 | 11 | 103 | kschamplin/astro-classifier-neo | src/pytorch_test/plasticc/datasets.py | Python | PlasticcDataModule | PlasticcDataModule | 21 | 57 | 21 | 21 | 2fff1b75137072958d09e332be614b7f0fae621e | bigcode/the-stack | train |
3d30fa89c192b73395799281 | train | function | def _download(data_dir):
# create data dir
if not data_dir.exists():
data_dir.mkdir()
# scrape the file list
print("Gathering file list")
files = requests.get(
"https://zenodo.org/api/records/2539456").json()['files']
files = [f for f in files if f['key'] not in blacklist]
f... | def _download(data_dir):
# create data dir
| if not data_dir.exists():
data_dir.mkdir()
# scrape the file list
print("Gathering file list")
files = requests.get(
"https://zenodo.org/api/records/2539456").json()['files']
files = [f for f in files if f['key'] not in blacklist]
for f in tqdm(files):
# TODO: add checks... | )
m = int(meta['true_target'])
# convert the target to the 0-14 class layout.
m = torch.tensor(class_id_to_target[m])
return curve, m
blacklist = [
"plasticc_modelpar.tar.gz"
]
def _download(data_dir):
# create data dir
| 67 | 67 | 226 | 12 | 55 | kschamplin/astro-classifier-neo | src/pytorch_test/plasticc/datasets.py | Python | _download | _download | 90 | 114 | 90 | 91 | 2a33fb826b8712aaae059141883ccd6c14ddb009 | bigcode/the-stack | train |
6b019752769e1e9bd2b334e6 | train | function | def _process_plasticc_csv(curve_table: pd.DataFrame, meta_table: pd.DataFrame, name: str, data_dir: Path):
"Converts a plasticc curve/metadata table to pivoted feather tables"
curve_table['passband'] = curve_table['passband'].map(passband_map)
curve_ids = curve_table['object_id'].unique()
pivoted_resul... | def _process_plasticc_csv(curve_table: pd.DataFrame, meta_table: pd.DataFrame, name: str, data_dir: Path):
| "Converts a plasticc curve/metadata table to pivoted feather tables"
curve_table['passband'] = curve_table['passband'].map(passband_map)
curve_ids = curve_table['object_id'].unique()
pivoted_result = curve_table.groupby(['object_id', 'mjd', 'passband']).sum().unstack('passband').reset_index()
new_m... | as input_file:
with open(gzpath.parent / gzpath.stem, 'wb') as output:
shutil.copyfileobj(input_file, output)
def _process_plasticc_csv(curve_table: pd.DataFrame, meta_table: pd.DataFrame, name: str, data_dir: Path):
| 64 | 64 | 189 | 31 | 33 | kschamplin/astro-classifier-neo | src/pytorch_test/plasticc/datasets.py | Python | _process_plasticc_csv | _process_plasticc_csv | 127 | 136 | 127 | 127 | 34f2ef9f1420fd925b0213c61abd1d1ce60783d9 | bigcode/the-stack | train |
38c36c30665fa018cc36ebb5 | train | function | def _zenodo_convert(data_dir: Path):
"""Converts the original plasticc CSVs to our new format"""
train_curves = pd.read_csv(data_dir / "plasticc_train_lightcurves.csv")
train_meta = pd.read_csv(data_dir / "plasticc_train_metadata.csv")
_process_plasticc_csv(train_curves, train_meta, "plasticc_train", da... | def _zenodo_convert(data_dir: Path):
| """Converts the original plasticc CSVs to our new format"""
train_curves = pd.read_csv(data_dir / "plasticc_train_lightcurves.csv")
train_meta = pd.read_csv(data_dir / "plasticc_train_metadata.csv")
_process_plasticc_csv(train_curves, train_meta, "plasticc_train", data_dir=data_dir)
test_curves = [(... | we have.
feather.write_feather(pivoted_result, data_dir / f"{name}_curves.feather", compression="zstd")
feather.write_feather(new_meta, data_dir / f"{name}_meta.feather", compression="zstd")
def _zenodo_convert(data_dir: Path):
| 64 | 64 | 185 | 10 | 54 | kschamplin/astro-classifier-neo | src/pytorch_test/plasticc/datasets.py | Python | _zenodo_convert | _zenodo_convert | 139 | 149 | 139 | 139 | 7be8e0ad16deb13dd52a8609bb206231f408f94a | bigcode/the-stack | train |
8da2426ff711571df2ae7935 | train | class | class PlasticcDataset(torch.utils.data.Dataset):
"Loads a single curve/meta pair from the converted plasticc dataset"
def __init__(self, file_name, data_dir, transform=None):
# load the data using memory-map
data_dir = Path(data_dir)
self.curves = feather.read_feather(data_dir / f"{file... | class PlasticcDataset(torch.utils.data.Dataset):
| "Loads a single curve/meta pair from the converted plasticc dataset"
def __init__(self, file_name, data_dir, transform=None):
# load the data using memory-map
data_dir = Path(data_dir)
self.curves = feather.read_feather(data_dir / f"{file_name}_curves.feather", memory_map=True)
... | c_test_light*.csv")]
test_meta = pd.read_csv(data_dir / "plasticc_test_metadata.csv")
for cur in test_curves:
df = pd.read_csv(cur[0])
_process_plasticc_csv(df, test_meta, f"plasticc_test_{cur[1].group(0)}", data_dir=data_dir)
class PlasticcDataset(torch.utils.data.Dataset):
| 82 | 82 | 276 | 9 | 73 | kschamplin/astro-classifier-neo | src/pytorch_test/plasticc/datasets.py | Python | PlasticcDataset | PlasticcDataset | 152 | 179 | 152 | 152 | e2d4e95d7157e17f62e16207bda6301220fa34cf | bigcode/the-stack | train |
cb4c0fd90c49195ef3ec892e | train | function | def main():
infile = open('p_distance.dat', 'r')
string = ''
for line in infile:
string += line
string = string.replace(' ', '')
string = string.replace('\n','')
a = []
for i in string:
a += i
b = [
a[:10],
a[10:20],
a[20:30],
a[30:40]
... | def main():
| infile = open('p_distance.dat', 'r')
string = ''
for line in infile:
string += line
string = string.replace(' ', '')
string = string.replace('\n','')
a = []
for i in string:
a += i
b = [
a[:10],
a[10:20],
a[20:30],
a[30:40]
]
in... | T','C','C','A','T','T','T','T'],
['G','T','T','C','C','A','T','T','T','A']
]
Pass the list to the get_p_distance_matrix function as an argument
Display the p distance matrix to screen
'''
def main():
| 64 | 64 | 106 | 3 | 61 | acc-cosc-1336/cosc-1336-spring-2018-ZachariahClymerAcc | src/homework/main/main_homework7.py | Python | main | main | 18 | 35 | 18 | 18 | 508793fe64c5738677d43b66d827547e31e7d94c | bigcode/the-stack | train |
401e0921f904d0cf46557190 | train | class | class ChemSys(SimpleNEQSys):
var_tokens = 'NH3 NH4p Hp OHm H2O'
param_tokens = 'Kw Ka ' + ' '.join(['init_'+x for x in var_tokens.split()])
@property
def exprs(self):
NH3, NH4p, Hp, OHm, H2O, Kw, Ka = [
self[token] for token in ('NH3', 'NH4p', 'Hp',
... | class ChemSys(SimpleNEQSys):
| var_tokens = 'NH3 NH4p Hp OHm H2O'
param_tokens = 'Kw Ka ' + ' '.join(['init_'+x for x in var_tokens.split()])
@property
def exprs(self):
NH3, NH4p, Hp, OHm, H2O, Kw, Ka = [
self[token] for token in ('NH3', 'NH4p', 'Hp',
'OHm', 'H2O', 'Kw', 'Ka'... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import division, print_function
"""
Example of a 4 dimensional root finidng problem (chemical
acid/base equilbria)
"""
from sympy import pprint
from symneqsys import SimpleNEQSys, Problem
from symneqsys.minpack import MINPACK_Solver
class ChemSys(SimpleN... | 83 | 101 | 338 | 8 | 74 | bjodah/symneqsys | examples/chem_equil.py | Python | ChemSys | ChemSys | 17 | 37 | 17 | 17 | 058f83e80f51032e7098e9698aaeed4ec5c30a1b | bigcode/the-stack | train |
9f87e7f6191ac82b438edae4 | train | function | def main(Sys, logger=None):
"""
Solve the example system using Levenberg-Marquardt algorithm
from Netlib's MINPACK fortran code.
"""
sys = Sys()
print('Variables:')
pprint(sys.v)
print('Expressions:')
for expr in sys.exprs:
pprint(expr)
print('Jacobian:')
pprint(sys.... | def main(Sys, logger=None):
| """
Solve the example system using Levenberg-Marquardt algorithm
from Netlib's MINPACK fortran code.
"""
sys = Sys()
print('Variables:')
pprint(sys.v)
print('Expressions:')
for expr in sys.exprs:
pprint(expr)
print('Jacobian:')
pprint(sys.jac)
solver = MINPACK_So... | init['NH4p'] +
init['Hp']+init['OHm']+2*init['H2O']), # prsrv H atoms
OHm+H2O-init['OHm']-init['H2O'], # preservation of O atoms
NH4p+Hp-OHm-(init['NH4p']+init['Hp'] -
init['OHm']) # preservation of charge
]
def main(Sys, logger=None):
| 102 | 103 | 346 | 7 | 95 | bjodah/symneqsys | examples/chem_equil.py | Python | main | main | 40 | 76 | 40 | 40 | 0b1eda2f4e6498b33a39e2040b22f10958fe60cc | bigcode/the-stack | train |
a1e43dda20cff3552bcb469e | train | class | class DGCMomentumOptimizer(Optimizer):
"""
:api_attr: Static Graph
DGC (Deep Gradient Compression) Momentum Optimizer. Original paper is https://arxiv.org/abs/1712.01887
DGC reduces the communication bandwidth by sending only the important gradients (sparse update):\
only gradients larger than a... | class DGCMomentumOptimizer(Optimizer):
| """
:api_attr: Static Graph
DGC (Deep Gradient Compression) Momentum Optimizer. Original paper is https://arxiv.org/abs/1712.01887
DGC reduces the communication bandwidth by sending only the important gradients (sparse update):\
only gradients larger than a threshold are transmitted.
To avo... | .Block)
velocity_acc = self._get_accumulator(self._velocity_acc_str,
param_and_grad[0])
lr = self._create_param_lr(param_and_grad)
if framework.in_dygraph_mode():
_, _ = core.ops.momentum(param_and_grad[0], param_and_grad[1],
... | 256 | 256 | 3,834 | 8 | 247 | laipaang/Paddle | python/paddle/fluid/optimizer.py | Python | DGCMomentumOptimizer | DGCMomentumOptimizer | 1,071 | 1,483 | 1,071 | 1,071 | 4e5bc08e0858b0ef94295eed83d747a70901df3b | bigcode/the-stack | train |
3db4ef3ed65d06d0480a22fc | train | class | class AdamaxOptimizer(Optimizer):
"""
The Adamax optimizer is implemented based on the Adamax Optimization
in Section 7 of `Adam paper <https://arxiv.org/abs/1412.6980>`_.
The Adamax algorithm is a variant of the Adam algorithm based on the infinite norm,
which makes the learning rate update algori... | class AdamaxOptimizer(Optimizer):
| """
The Adamax optimizer is implemented based on the Adamax Optimization
in Section 7 of `Adam paper <https://arxiv.org/abs/1412.6980>`_.
The Adamax algorithm is a variant of the Adam algorithm based on the infinite norm,
which makes the learning rate update algorithm more stable and simple.
T... | 2": [moment2],
"Beta1Pow": [beta1_pow_acc],
"Beta2Pow": [beta2_pow_acc]
}
outputs = {
"ParamOut": [param_and_grad[0]],
"Moment1Out": [moment1],
"Moment2Out": [moment2],
"Beta1PowOut": [beta1_pow_acc],
"Beta2PowOut": [bet... | 256 | 256 | 1,632 | 7 | 248 | laipaang/Paddle | python/paddle/fluid/optimizer.py | Python | AdamaxOptimizer | AdamaxOptimizer | 1,982 | 2,151 | 1,982 | 1,982 | fdb270fcb6453d27460e67eb4b185880033ac9cd | bigcode/the-stack | train |
8e516ae5a5ce7c1246113b2a | train | class | class AdagradOptimizer(Optimizer):
"""
The Adaptive Gradient optimizer (Adagrad for short) can adaptively assign
different learning rates to individual parameters.
The parameter ``param_out`` update rule with gradient ``grad``:
.. math::
moment\_out &= moment + grad * grad
param\... | class AdagradOptimizer(Optimizer):
| """
The Adaptive Gradient optimizer (Adagrad for short) can adaptively assign
different learning rates to individual parameters.
The parameter ``param_out`` update rule with gradient ``grad``:
.. math::
moment\_out &= moment + grad * grad
param\_out &= param - \\frac{learning\_ra... | ars_coeff = float(lars_coeff)
self._lars_weight_decay = float(lars_weight_decay)
def _create_accumulators(self, block, parameters):
assert isinstance(block, framework.Block)
for p in parameters:
self._add_accumulator(self._velocity_acc_str, p)
def _append_optimize_op(self,... | 256 | 256 | 1,108 | 7 | 248 | laipaang/Paddle | python/paddle/fluid/optimizer.py | Python | AdagradOptimizer | AdagradOptimizer | 1,600 | 1,713 | 1,600 | 1,600 | ea1d5361378c2402d8c581f63e9c059e508b0195 | bigcode/the-stack | train |
63cef2b8a60918359d849631 | train | class | class AdamOptimizer(Optimizer):
"""
The Adam optimizer uses an optimization described at the end
of section 2 of `Adam paper <https://arxiv.org/abs/1412.6980>`_ ,
it can dynamically adjusts the learning rate of each parameter using
the 1st moment estimates and the 2nd moment estimates of the gradien... | class AdamOptimizer(Optimizer):
| """
The Adam optimizer uses an optimization described at the end
of section 2 of `Adam paper <https://arxiv.org/abs/1412.6980>`_ ,
it can dynamically adjusts the learning rate of each parameter using
the 1st moment estimates and the 2nd moment estimates of the gradient.
The parameter ``para... | ization=regularization,
grad_clip=grad_clip,
name=name)
self.type = "adagrad"
self._epsilon = epsilon
self.initial_accumulator_value = initial_accumulator_value
def _create_accumulators(self, block, parameters):
assert isinstance(block, framework.Block)
... | 256 | 256 | 2,705 | 6 | 249 | laipaang/Paddle | python/paddle/fluid/optimizer.py | Python | AdamOptimizer | AdamOptimizer | 1,716 | 1,979 | 1,716 | 1,716 | 482b2d4da792eabbea1ae419fa6a429568b6a8a4 | bigcode/the-stack | train |
34b7db6e43715b704d58a29a | train | class | class AdadeltaOptimizer(Optimizer):
"""
**Notes: This API does not support sparse parameter optimization.**
Adadelta Optimizer. Please refer to this for details:
`ADADELTA: AN ADAPTIVE LEARNING RATE METHOD <https://arxiv.org/abs/1212.5701>`_.
The update is done as follows:
.. math::
... | class AdadeltaOptimizer(Optimizer):
| """
**Notes: This API does not support sparse parameter optimization.**
Adadelta Optimizer. Please refer to this for details:
`ADADELTA: AN ADAPTIVE LEARNING RATE METHOD <https://arxiv.org/abs/1212.5701>`_.
The update is done as follows:
.. math::
E(g_t^2) &= \\rho * E(g_{t-1}^2) + (... | ,
grad_clip=grad_clip,
name=name)
self.type = "decayed_adagrad"
self._decay = decay
self._epsilon = epsilon
def _create_accumulators(self, block, parameters):
assert isinstance(block, framework.Block)
for p in parameters:
self._add_accumu... | 256 | 256 | 1,204 | 8 | 247 | laipaang/Paddle | python/paddle/fluid/optimizer.py | Python | AdadeltaOptimizer | AdadeltaOptimizer | 2,359 | 2,475 | 2,359 | 2,359 | 490f3350e13d9371e2f9a2c6d9ee3c230d6a30dd | bigcode/the-stack | train |
ea99b6f96a737b6b9c75e7b6 | train | class | class FtrlOptimizer(Optimizer):
"""
FTRL (Follow The Regularized Leader) Optimizer.
The paper that proposed Follow The Regularized Leader (FTRL):
(https://www.eecs.tufts.edu/~dsculley/papers/ad-click-prediction.pdf)
.. math::
&new\_accum = squared\_accum + grad^2
&if (lr\_power ... | class FtrlOptimizer(Optimizer):
| """
FTRL (Follow The Regularized Leader) Optimizer.
The paper that proposed Follow The Regularized Leader (FTRL):
(https://www.eecs.tufts.edu/~dsculley/papers/ad-click-prediction.pdf)
.. math::
&new\_accum = squared\_accum + grad^2
&if (lr\_power == -0.5):
&\quad linea... | framework.Block.")
momentum_acc = self._get_accumulator(self._momentum_acc_str,
param_and_grad[0])
mean_square_acc = self._get_accumulator(self._mean_square_acc_str,
param_and_grad[0])
mean_grad_acc = ... | 256 | 256 | 1,520 | 7 | 248 | laipaang/Paddle | python/paddle/fluid/optimizer.py | Python | FtrlOptimizer | FtrlOptimizer | 2,666 | 2,822 | 2,666 | 2,666 | 4e12eee9969ed66053fe27a273d2ce52915946b8 | bigcode/the-stack | train |
c54b1687afdcaa2aa6d0dc6c | train | class | class ExponentialMovingAverage(object):
"""
:api_attr: Static Graph
Compute the moving average of parameters with exponential decay.
Given a parameter :math:`\\theta`, its exponential moving average (EMA)
will be
.. math::
\\text{EMA}_0 & = 0
\\text{EMA}_t & = \\text{decay} * \\text{... | class ExponentialMovingAverage(object):
| """
:api_attr: Static Graph
Compute the moving average of parameters with exponential decay.
Given a parameter :math:`\\theta`, its exponential moving average (EMA)
will be
.. math::
\\text{EMA}_0 & = 0
\\text{EMA}_t & = \\text{decay} * \\text{EMA}_{t-1} + (1 - \\text{decay}) * \\the... | (train_program, startup_program):
# build net
data = fluid.data(name='X', shape=[None, 1], dtype='float32')
hidden = fluid.layers.fc(input=data, size=10)
loss = fluid.layers.mean(hidden)
optimizer = fluid.optimizer.Momentum(learning_rate=0.... | 256 | 256 | 2,082 | 7 | 249 | laipaang/Paddle | python/paddle/fluid/optimizer.py | Python | ExponentialMovingAverage | ExponentialMovingAverage | 3,306 | 3,553 | 3,306 | 3,306 | 3714d869c937a29d448db7caddedda54356aec81 | bigcode/the-stack | train |
d815196dbee4e2ecee8d5918 | train | class | class SGDOptimizer(Optimizer):
"""
Optimizer of the stochastic gradient descent algorithm.
.. math::
param\_out = param - learning\_rate * grad
Parameters:
learning_rate (float|Variable): The learning rate used to update parameters. \
Can be a float value or a Variable wit... | class SGDOptimizer(Optimizer):
| """
Optimizer of the stochastic gradient descent algorithm.
.. math::
param\_out = param - learning\_rate * grad
Parameters:
learning_rate (float|Variable): The learning rate used to update parameters. \
Can be a float value or a Variable with one float value as data eleme... | Set of ``Variable`` or ``Variable.name`` that don't need
to be updated. The default value is None.
Returns:
tuple: tuple (optimize_ops, params_grads), A list of operators appended
by minimize and a list of (param, grad) variable pairs, param is
``Parameter`... | 256 | 256 | 862 | 6 | 249 | laipaang/Paddle | python/paddle/fluid/optimizer.py | Python | SGDOptimizer | SGDOptimizer | 842 | 933 | 842 | 842 | ebc1b871039f507177be476f8738dab766fd229f | bigcode/the-stack | train |
577ed9f7200b0581afacc274 | train | class | class LarsMomentumOptimizer(Optimizer):
"""
Momentum optimizer with LARS support
The update equations are as follows:
.. math::
& local\_learning\_rate = learning\_rate * lars\_coeff * \\
\\frac{||param||}{||gradient|| + lars\_weight\_decay * ||param||}
& velocity = mu * ve... | class LarsMomentumOptimizer(Optimizer):
| """
Momentum optimizer with LARS support
The update equations are as follows:
.. math::
& local\_learning\_rate = learning\_rate * lars\_coeff * \\
\\frac{||param||}{||gradient|| + lars\_weight\_decay * ||param||}
& velocity = mu * velocity + local\_learning\_rate * (gradie... | dgc_params_grads = []
# DGC clip and regularization in optimizer.backward
for param, grad in params_grads:
if not self._is_use_dgc(param, grad):
not_dgc_params_grads.append((param, grad))
else:
dgc_params_grads.append((param, grad))
... | 256 | 256 | 1,064 | 7 | 248 | laipaang/Paddle | python/paddle/fluid/optimizer.py | Python | LarsMomentumOptimizer | LarsMomentumOptimizer | 1,486 | 1,597 | 1,486 | 1,486 | 21583c5604d26a62a6056d945378c2196f34c0c9 | bigcode/the-stack | train |
52c94554942b30c7a1c60cf8 | train | class | class PipelineOptimizer(object):
"""
:api_attr: Static Graph
Pipeline Optimizer
Train with pipeline mode. The program will be split by cut_list.
If the len of cut_list is k, then the whole program (including \
backward part) will be split to 2*k-1 sections.
So the length of place_lis... | class PipelineOptimizer(object):
| """
:api_attr: Static Graph
Pipeline Optimizer
Train with pipeline mode. The program will be split by cut_list.
If the len of cut_list is k, then the whole program (including \
backward part) will be split to 2*k-1 sections.
So the length of place_list and concurrency_list must be al... | ema_t = param_ema * self._decay_var + param * (
1 - self._decay_var)
layers.assign(input=ema_t, output=param_ema)
# for fp16 params
for param_ema, master_ema in param_master_emas:
default_main_program().global_block().append_op... | 256 | 256 | 2,668 | 5 | 251 | laipaang/Paddle | python/paddle/fluid/optimizer.py | Python | PipelineOptimizer | PipelineOptimizer | 3,556 | 3,855 | 3,556 | 3,556 | 1a4f0ad117ad422078b64a2fb95ab4b0402372ea | bigcode/the-stack | train |
06a1b7406bce7ecc8b77280b | train | class | class DecayedAdagradOptimizer(Optimizer):
"""
The Decayed Adagrad optimizer can be seen as an Adagrad algorithm that introduces
the decay rate to solve the problem of a sharp drop in the learning rate
during model training when using the AdagradOptimizer.
The parameter ``param_out`` update rule wit... | class DecayedAdagradOptimizer(Optimizer):
| """
The Decayed Adagrad optimizer can be seen as an Adagrad algorithm that introduces
the decay rate to solve the problem of a sharp drop in the learning rate
during model training when using the AdagradOptimizer.
The parameter ``param_out`` update rule with gradient ``grad``:
.. math::
... | ._sigma = sigma
'''
Note(wangzhongpu):
This property is only used for debugging, do not need to set it!
Dpsgd operator use time(NULL) as random seed to generate random number.
However, during debugging, we need determinated result, so we will set self._seed to a fixed number.
... | 256 | 256 | 1,060 | 9 | 246 | laipaang/Paddle | python/paddle/fluid/optimizer.py | Python | DecayedAdagradOptimizer | DecayedAdagradOptimizer | 2,249 | 2,356 | 2,249 | 2,249 | f67a2938443b2b021a800b775d2a2fb65ac992a3 | bigcode/the-stack | train |
aa36804f04d6c59ee4e1edd8 | train | class | class MomentumOptimizer(Optimizer):
"""
Simple Momentum optimizer with velocity state
This optimizer has a flag for Nestrov Momentum.
The update equations are as follows:
.. math::
& velocity = mu * velocity + gradient
& if (use\_nesterov):
&\quad param = param - (gr... | class MomentumOptimizer(Optimizer):
| """
Simple Momentum optimizer with velocity state
This optimizer has a flag for Nestrov Momentum.
The update equations are as follows:
.. math::
& velocity = mu * velocity + gradient
& if (use\_nesterov):
&\quad param = param - (gradient + mu * velocity) * learning\_... | _list=fetch_list)
"""
def __init__(self,
learning_rate,
parameter_list=None,
regularization=None,
grad_clip=None,
name=None):
assert learning_rate is not None
super(SGDOptimizer, self).__init__(
le... | 256 | 256 | 1,163 | 6 | 249 | laipaang/Paddle | python/paddle/fluid/optimizer.py | Python | MomentumOptimizer | MomentumOptimizer | 936 | 1,068 | 936 | 936 | d6af7022d78f0abc70296fed9e3a8193399a8fd1 | bigcode/the-stack | train |
c508147febed03c12182e9de | train | class | class DpsgdOptimizer(Optimizer):
"""
We implement the Dpsgd optimizer according to CCS16 paper -
Deep Learning with Differential Privacy.
Examples:
.. code-block:: python
import paddle.fluid as fluid
import numpy
# First create the Executor.
place = flu... | class DpsgdOptimizer(Optimizer):
| """
We implement the Dpsgd optimizer according to CCS16 paper -
Deep Learning with Differential Privacy.
Examples:
.. code-block:: python
import paddle.fluid as fluid
import numpy
# First create the Executor.
place = fluid.CPUPlace() # fluid.CUDAPlace(0... | "ParamOut": param_and_grad[0],
"MomentOut": moment,
"InfNormOut": inf_norm
},
attrs={
"beta1": self._beta1,
"beta2": self._beta2,
"epsilon": self._epsilon
},
stop_gradient=True)
retu... | 226 | 226 | 754 | 8 | 218 | laipaang/Paddle | python/paddle/fluid/optimizer.py | Python | DpsgdOptimizer | DpsgdOptimizer | 2,154 | 2,246 | 2,154 | 2,154 | 3d3ffad4f7a3104c4fd6988174131c7fef948efe | bigcode/the-stack | train |
8897c0825c6e28245c7315f5 | train | class | class ModelAverage(Optimizer):
"""
:api_attr: Static Graph
The ModelAverage optimizer accumulates specific continuous historical parameters
during training. The accumulated historical range can be controlled by the passed
``average_window_rate`` argument. The averaged ``Parameter`` are used in the pr... | class ModelAverage(Optimizer):
| """
:api_attr: Static Graph
The ModelAverage optimizer accumulates specific continuous historical parameters
during training. The accumulated historical range can be controlled by the passed
``average_window_rate`` argument. The averaged ``Parameter`` are used in the prediction,
which usually can... | 1_pow_acc,
"Beta2Pow": beta2_pow_acc
},
outputs={
"ParamOut": param_and_grad[0],
"Moment1Out": moment1,
"Moment2Out": moment2
},
attrs={
"beta1": self._beta1,
"beta2": self._be... | 256 | 256 | 2,808 | 6 | 249 | laipaang/Paddle | python/paddle/fluid/optimizer.py | Python | ModelAverage | ModelAverage | 2,997 | 3,303 | 2,997 | 2,997 | ffd8b4b69432d1e055a383e07571407122b60ed9 | bigcode/the-stack | train |
5fab9401c97075fedc3b28a0 | train | class | class Optimizer(object):
"""Optimizer Base class.
Define the common interface of an optimizer.
User should not use this class directly,
but need to use one of it's implementation.
"""
@imperative_base.no_grad
def __init__(self,
learning_rate,
parameter_lis... | class Optimizer(object):
| """Optimizer Base class.
Define the common interface of an optimizer.
User should not use this class directly,
but need to use one of it's implementation.
"""
@imperative_base.no_grad
def __init__(self,
learning_rate,
parameter_list=None,
... |
from .initializer import Constant
from .layer_helper import LayerHelper
from .layers import ops
from .regularizer import append_regularization_ops
from .dygraph import base as imperative_base
from .dygraph import no_grad
from .dygraph.learning_rate_scheduler import LearningRateDecay
from paddle.fluid import core
from ... | 256 | 256 | 6,602 | 5 | 251 | laipaang/Paddle | python/paddle/fluid/optimizer.py | Python | Optimizer | Optimizer | 55 | 839 | 55 | 55 | 6a62039d0feef0deb3c6daf2bb336ea89f7fdbc0 | bigcode/the-stack | train |
b74fa6cb72833e1aef7734b5 | train | class | class LambOptimizer(AdamOptimizer):
"""
LAMB (Layer-wise Adaptive Moments optimizer for Batching training) Optimizer.
LAMB Optimizer is designed to scale up the batch size of training without losing
accuracy, which supports adaptive element-wise updating and accurate layer-wise
correction. For mo... | class LambOptimizer(AdamOptimizer):
| """
LAMB (Layer-wise Adaptive Moments optimizer for Batching training) Optimizer.
LAMB Optimizer is designed to scale up the batch size of training without losing
accuracy, which supports adaptive element-wise updating and accurate layer-wise
correction. For more information, please refer to `Lar... | ._squared_acc_str, p)
self._add_accumulator(self._linear_acc_str, p)
def _append_optimize_op(self, block, param_and_grad):
if not isinstance(block, framework.Block):
raise TypeError("block is not instance of framework.Block.")
squared_acc = self._get_accumulator(self._squar... | 256 | 256 | 1,520 | 7 | 248 | laipaang/Paddle | python/paddle/fluid/optimizer.py | Python | LambOptimizer | LambOptimizer | 2,825 | 2,972 | 2,825 | 2,825 | 4f223ede34293a4c2a9b6599f5ce3913c33c4326 | bigcode/the-stack | train |
c60095e1d9ab547bcdffb098 | train | class | class RecomputeOptimizer(Optimizer):
"""
:api_attr: Static Graph
Recompute Optimizer Wrapper
Normally, a training step contains three sub-steps: first, run forward
Operators to calculate the loss; second, run backward Operators to
calculate gradient of the parameters; third, apply optimization ... | class RecomputeOptimizer(Optimizer):
| """
:api_attr: Static Graph
Recompute Optimizer Wrapper
Normally, a training step contains three sub-steps: first, run forward
Operators to calculate the loss; second, run backward Operators to
calculate gradient of the parameters; third, apply optimization method
to update the value of the... | set(), "output_set": set()}
program_list.append(ptmp)
else:
program_list = self._split_program(program, self._cut_list)
for p in program_list:
self._create_vars(p["program"].block(0), program)
whole_parameters = [e.name for e in program.block(0).all_p... | 256 | 256 | 2,440 | 7 | 249 | laipaang/Paddle | python/paddle/fluid/optimizer.py | Python | RecomputeOptimizer | RecomputeOptimizer | 3,858 | 4,147 | 3,858 | 3,858 | bbe5272abbedb0c8b95b567bb498e37bc1936464 | bigcode/the-stack | train |
e274fb29db458ce1c4d7a675 | train | class | class LookaheadOptimizer(object):
"""
:api_attr: Static Graph
This implements the Lookahead optimizer of the
paper : https://arxiv.org/abs/1907.08610.
Lookahead keeps two sets of params: the fast_params and
the slow_params. inner_optimizer update fast_params every
training step. Lookahead u... | class LookaheadOptimizer(object):
| """
:api_attr: Static Graph
This implements the Lookahead optimizer of the
paper : https://arxiv.org/abs/1907.08610.
Lookahead keeps two sets of params: the fast_params and
the slow_params. inner_optimizer update fast_params every
training step. Lookahead updates the slow_params and fast_pa... | fc_1, pred])
params_grads = sgd.backward(
cost,
startup_program=None,
parameter_list=None,
no_grad_set=None)
optimize_ops = sgd.apply_optimize(
cost, startup_program=None,... | 256 | 256 | 1,221 | 6 | 249 | laipaang/Paddle | python/paddle/fluid/optimizer.py | Python | LookaheadOptimizer | LookaheadOptimizer | 4,150 | 4,304 | 4,150 | 4,150 | 08b7abd5c08ad34b7d3b9e0c303867b76742e1e3 | bigcode/the-stack | train |
66e67f10881a79e21ef9fbae | train | class | class RMSPropOptimizer(Optimizer):
"""
Root Mean Squared Propagation (RMSProp) is an unpublished, adaptive learning
rate method. The original slides proposed RMSProp: Slide 29 of
http://www.cs.toronto.edu/~tijmen/csc321/slides/lecture_slides_lec6.pdf .
The original equation is as follows:
.. ... | class RMSPropOptimizer(Optimizer):
| """
Root Mean Squared Propagation (RMSProp) is an unpublished, adaptive learning
rate method. The original slides proposed RMSProp: Slide 29 of
http://www.cs.toronto.edu/~tijmen/csc321/slides/lecture_slides_lec6.pdf .
The original equation is as follows:
.. math::
r(w, t) & = \\rho r... | )
self._add_accumulator(self._avg_squared_update_acc_str, p)
def _append_optimize_op(self, block, param_and_grad):
if not isinstance(block, framework.Block):
raise TypeError("block is not instance of framework.Block.")
avg_squared_grad_acc = self._get_accumulator(
... | 256 | 256 | 1,867 | 7 | 248 | laipaang/Paddle | python/paddle/fluid/optimizer.py | Python | RMSPropOptimizer | RMSPropOptimizer | 2,478 | 2,663 | 2,478 | 2,478 | 7c39fdaec9fab0a9fcda66a297d4856bafff14d6 | bigcode/the-stack | train |
be0e96a39245268918008ae7 | train | function | @app.route('/testme')
def home():
return 'success'
| @app.route('/testme')
def home():
| return 'success'
| '''
from flask import Flask, request, make_response
'''
from flask import Flask,request, make_response,jsonify
app = Flask(__name__)
@app.route("/")
def hello2():
return "Hello2 again, Universal!"
@app.route('/testme')
def home():
| 55 | 64 | 14 | 9 | 46 | kif-mohammed/python-docs-hello-world | app.py | Python | home | home | 12 | 14 | 12 | 13 | 8a44cc8023fbc8349b78b3e2b8081a081c57baaa | bigcode/the-stack | train |
4c104c6efe50177c79d180d7 | train | function | @app.route("/")
def hello2():
return "Hello2 again, Universal!"
| @app.route("/")
def hello2():
| return "Hello2 again, Universal!"
| '''
from flask import Flask, request, make_response
'''
from flask import Flask,request, make_response,jsonify
app = Flask(__name__)
@app.route("/")
def hello2():
| 37 | 64 | 16 | 7 | 30 | kif-mohammed/python-docs-hello-world | app.py | Python | hello2 | hello2 | 8 | 10 | 8 | 9 | 8d822091b117ba6b835fd6df0e353c3e5d07826e | bigcode/the-stack | train |
23d354bcf84339c4543659d0 | train | function | def duplicates(contacts, folder):
print("Checking duplicates for "+folder)
names = list(contacts.keys())
duplicates = []
for idx, name1 in enumerate(names[:-1]):
sname1 = tuple(sorted(name1.split(" ")))
for name2 in names[idx+1:]:
sname2 = tuple(sorted(name2.split(" ")))
... | def duplicates(contacts, folder):
| print("Checking duplicates for "+folder)
names = list(contacts.keys())
duplicates = []
for idx, name1 in enumerate(names[:-1]):
sname1 = tuple(sorted(name1.split(" ")))
for name2 in names[idx+1:]:
sname2 = tuple(sorted(name2.split(" ")))
if sname1 == sname2:
... | cardlib.collect_attributes(vcards)
vcardlib.set_name(attributes)
new = vcardlib.build_vcard(attributes)
print(new.prettyPrint())
obj = {"vcard":new, "filenames":filenames}
merged.append(obj)
return merged
def duplicates(contacts, folder):
| 64 | 64 | 139 | 7 | 56 | balrok/pythonstuff | radicale/contact_diff.py | Python | duplicates | duplicates | 97 | 110 | 97 | 97 | 42706572afd37af7dc11aaf638ba4f9f50a109bf | bigcode/the-stack | train |
8ef158b1a77e3bb892baff70 | train | function | def run(folder_a, folder_b):
print(folder_a)
print(folder_b)
c_a = get_contacts(folder_a)
c_b = get_contacts(folder_b)
all = {}
for name in c_a:
all[name] = c_a[name][:]
for name in c_b:
if name not in all:
all[name] = c_b[name][:]
else:
all[n... | def run(folder_a, folder_b):
| print(folder_a)
print(folder_b)
c_a = get_contacts(folder_a)
c_b = get_contacts(folder_b)
all = {}
for name in c_a:
all[name] = c_a[name][:]
for name in c_b:
if name not in all:
all[name] = c_b[name][:]
else:
all[name].extend(c_b[name][:])
... | _name = selected_name.replace("/", "_")
filename = os.path.join(out_dir, selected_name + ".vcf")
with open(filename, 'w') as c_file:
c_file.write(file_content)
obj["new_filename"] = filename
return changes
def run(folder_a, folder_b):
| 64 | 64 | 117 | 8 | 55 | balrok/pythonstuff | radicale/contact_diff.py | Python | run | run | 52 | 70 | 52 | 52 | fbac539036220174418da43bf38c2aed907b16ed | bigcode/the-stack | train |
d57365cad6402be545f1b9d7 | train | function | def write_changes(out_dir, changes):
if not os.path.exists(out_dir):
os.makedirs(out_dir)
for obj in changes:
vcard = obj["vcard"]
# collect names
available_names = vcardlib.collect_vcard_names(vcard)
# select the most relevant name
selected_name = vcardlib.select... | def write_changes(out_dir, changes):
| if not os.path.exists(out_dir):
os.makedirs(out_dir)
for obj in changes:
vcard = obj["vcard"]
# collect names
available_names = vcardlib.collect_vcard_names(vcard)
# select the most relevant name
selected_name = vcardlib.select_most_relevant_name(available_names)
... | ["new_filename"]
old = obj["filenames"]
for f in old:
print("rm "+shlex.quote(f))
print("ln -s "+shlex.quote(os.path.abspath(new))+" "+shlex.quote(f))
#os.remove(f)
def write_changes(out_dir, changes):
| 64 | 64 | 148 | 8 | 56 | balrok/pythonstuff | radicale/contact_diff.py | Python | write_changes | write_changes | 35 | 50 | 35 | 35 | ff279b3c4945c2bcaa3a934e1be8bfef878faf2f | bigcode/the-stack | train |
d767347cbfaedb96605169a6 | train | function | def main():
parser = argparse.ArgumentParser(description="Compare two folders containing vcards")
parser.add_argument(dest="input", nargs=2)
parser.add_argument(dest="output", nargs="?")
parser.add_argument("-s", dest="symlink", action="store_true")
args = parser.parse_args()
print(args.input)
... | def main():
| parser = argparse.ArgumentParser(description="Compare two folders containing vcards")
parser.add_argument(dest="input", nargs=2)
parser.add_argument(dest="output", nargs="?")
parser.add_argument("-s", dest="symlink", action="store_true")
args = parser.parse_args()
print(args.input)
print(arg... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import vobject
import argparse
import os
import shlex
import vcardlib
def main():
| 37 | 64 | 128 | 3 | 33 | balrok/pythonstuff | radicale/contact_diff.py | Python | main | main | 10 | 24 | 10 | 10 | cc64857d912a88bbc9d6ea8948f5dff440ef67db | bigcode/the-stack | train |
153f37a48b6c49611682e089 | train | function | def write_symlinks(changes):
for obj in changes:
new = obj["new_filename"]
old = obj["filenames"]
for f in old:
print("rm "+shlex.quote(f))
print("ln -s "+shlex.quote(os.path.abspath(new))+" "+shlex.quote(f))
| def write_symlinks(changes):
| for obj in changes:
new = obj["new_filename"]
old = obj["filenames"]
for f in old:
print("rm "+shlex.quote(f))
print("ln -s "+shlex.quote(os.path.abspath(new))+" "+shlex.quote(f))
| (args.output)
changes = run(*args.input)
if args.output:
changes = write_changes(args.output, changes)
if args.symlink:
if not args.output:
raise Exception("Symlink only when output")
write_symlinks(changes)
def write_symlinks(changes):
| 64 | 64 | 68 | 8 | 56 | balrok/pythonstuff | radicale/contact_diff.py | Python | write_symlinks | write_symlinks | 26 | 32 | 26 | 26 | 07d9f0ea5cf2a56c02be2c357239987330afc24a | bigcode/the-stack | train |
bfe3d7cb93ec7c4b4d349b33 | train | function | def get_contacts(folder):
contacts = {}
for f in os.listdir(folder):
if f.endswith(".vcf"):
vcard = vobject.readOne(open(os.path.join(folder, f)).read())
name = vcard.contents['fn'][0].value
if name not in contacts:
contacts[name] = []
cont... | def get_contacts(folder):
| contacts = {}
for f in os.listdir(folder):
if f.endswith(".vcf"):
vcard = vobject.readOne(open(os.path.join(folder, f)).read())
name = vcard.contents['fn'][0].value
if name not in contacts:
contacts[name] = []
contacts[name].append({"vcard"... | name1 == sname2:
print("Found duplicate "+name1 + " -> "+name2)
duplicates.append((name1, name2))
for name1, name2 in duplicates:
contacts[name1].extend(contacts[name2])
del contacts[name2]
def get_contacts(folder):
| 64 | 64 | 95 | 5 | 59 | balrok/pythonstuff | radicale/contact_diff.py | Python | get_contacts | get_contacts | 112 | 121 | 112 | 112 | 7cc840191c8d05610c2da0ee6d68e183dea15975 | bigcode/the-stack | train |
cbfd5aeddadddc6d52e55127 | train | function | def remove_same_symlinks(all):
for name in all:
if len(all[name])>1:
realpathes = {}
for v in all[name]:
p = os.path.join(v["folder"], v["file"])
realpathes[os.path.realpath(p)] = v
all[name] = list(realpathes.values())
return all
| def remove_same_symlinks(all):
| for name in all:
if len(all[name])>1:
realpathes = {}
for v in all[name]:
p = os.path.join(v["folder"], v["file"])
realpathes[os.path.realpath(p)] = v
all[name] = list(realpathes.values())
return all
| all[name] = c_b[name][:]
else:
all[name].extend(c_b[name][:])
all = remove_same_symlinks(all)
duplicates(all, "all")
return merge_duplicates(all)
# removes symlinks to the same file
def remove_same_symlinks(all):
| 64 | 64 | 79 | 8 | 55 | balrok/pythonstuff | radicale/contact_diff.py | Python | remove_same_symlinks | remove_same_symlinks | 73 | 81 | 73 | 73 | 18947a2e7675d7907ce8df0185aa7b5e2055b44f | bigcode/the-stack | train |
32fb76f9e62422c37de01456 | train | function | def merge_duplicates(all):
merged = []
for name in all:
if len(all[name])>1:
vcards = [v["vcard"] for v in all[name]]
filenames = [os.path.join(v["folder"], v["file"]) for v in all[name]]
attributes = vcardlib.collect_attributes(vcards)
vcardlib.set_name(a... | def merge_duplicates(all):
| merged = []
for name in all:
if len(all[name])>1:
vcards = [v["vcard"] for v in all[name]]
filenames = [os.path.join(v["folder"], v["file"]) for v in all[name]]
attributes = vcardlib.collect_attributes(vcards)
vcardlib.set_name(attributes)
new ... | >1:
realpathes = {}
for v in all[name]:
p = os.path.join(v["folder"], v["file"])
realpathes[os.path.realpath(p)] = v
all[name] = list(realpathes.values())
return all
def merge_duplicates(all):
| 64 | 64 | 122 | 5 | 58 | balrok/pythonstuff | radicale/contact_diff.py | Python | merge_duplicates | merge_duplicates | 83 | 95 | 83 | 83 | 6f8013f41e5389cf49cd5d84455aa8baaa9c4979 | bigcode/the-stack | train |
4b183847ee43c436277750e5 | train | class | class Repository:
__car_data = {}
@classmethod
def all_cars(cls, limit=None):
cls.__load_data()
cars = list(cls.__car_data.values())
if limit:
cars = cars[:limit]
return cars
@classmethod
def car_by_id(cls, car_id):
cls.__load_data()
re... | class Repository:
| __car_data = {}
@classmethod
def all_cars(cls, limit=None):
cls.__load_data()
cars = list(cls.__car_data.values())
if limit:
cars = cars[:limit]
return cars
@classmethod
def car_by_id(cls, car_id):
cls.__load_data()
return cls.__car_dat... | import csv
import os
import uuid
class Repository:
| 12 | 91 | 304 | 3 | 8 | turing4ever/restful-services-in-pyramid | src/nearly_restful/02_CRUD_svc2_restful_auto_service/restful_auto_service/data/repository.py | Python | Repository | Repository | 6 | 59 | 6 | 6 | 3f8d1827403496ce46813b8e9c01136b97e5f71c | bigcode/the-stack | train |
f19c1141726297620fac13cf | train | function | def get_version(rel_path):
init_content = (here / rel_path).read_text(encoding='utf-8')
for line in init_content.split('\n'):
if line.startswith('__version__'):
delim = '"' if '"' in line else "'"
return line.split(delim)[1]
else:
raise RuntimeError("Unable to find ve... | def get_version(rel_path):
| init_content = (here / rel_path).read_text(encoding='utf-8')
for line in init_content.split('\n'):
if line.startswith('__version__'):
delim = '"' if '"' in line else "'"
return line.split(delim)[1]
else:
raise RuntimeError("Unable to find version string.")
| from setuptools import setup, find_packages
import pathlib
here = pathlib.Path(__file__).parent.resolve()
long_description = (here / 'README.md').read_text(encoding='utf-8')
def get_version(rel_path):
| 46 | 64 | 77 | 6 | 40 | valgur/QuaPy | setup.py | Python | get_version | get_version | 9 | 16 | 9 | 9 | 25c97ad3b461431729e43d41987598f33b5952bf | bigcode/the-stack | train |
b1979bfc14fbbc9714c5a53a | train | function | def get_redirected_url(url: str):
"""
Given a URL, returns the URL it redirects to or the
original URL in case of no indirection
"""
import requests
with requests.Session() as session:
with session.get(url, stream=True, allow_redirects=True) as response:
if response.history:... | def get_redirected_url(url: str):
| """
Given a URL, returns the URL it redirects to or the
original URL in case of no indirection
"""
import requests
with requests.Session() as session:
with session.get(url, stream=True, allow_redirects=True) as response:
if response.history:
return response.u... | .request
from typing import Optional
from urllib.parse import urlparse
from torch.utils.model_zoo import tqdm
from torchvision.datasets.utils import (
check_integrity,
extract_archive,
download_file_from_google_drive,
)
from vissl.utils.io import makedir
def get_redirected_url(url: str):
| 64 | 64 | 83 | 9 | 54 | ankitshah009/vissl | vissl/utils/download.py | Python | get_redirected_url | get_redirected_url | 24 | 36 | 24 | 24 | 75a1d5365204d0b2def3f37f91e6ad926f25b011 | bigcode/the-stack | train |
86b36d34f6d878052e7585c2 | train | function | def _get_google_drive_file_id(url: str) -> Optional[str]:
parts = urlparse(url)
if re.match(r"(drive|docs)[.]google[.]com", parts.netloc) is None:
return None
match = re.match(r"/file/d/(?P<id>[^/]*)", parts.path)
if match is None:
return None
return match.group("id")
| def _get_google_drive_file_id(url: str) -> Optional[str]:
| parts = urlparse(url)
if re.match(r"(drive|docs)[.]google[.]com", parts.netloc) is None:
return None
match = re.match(r"/file/d/(?P<id>[^/]*)", parts.path)
if match is None:
return None
return match.group("id")
| =io.DEFAULT_BUFFER_SIZE
):
file.write(block)
progress_bar.update(len(block))
# The following methods are copied from torchvision, but we use PathManager
# instead of `os` lib to support multiple distributed file systems.
def _get_google_drive_file_id... | 64 | 64 | 87 | 15 | 49 | ankitshah009/vissl | vissl/utils/download.py | Python | _get_google_drive_file_id | _get_google_drive_file_id | 92 | 102 | 92 | 92 | 468a391f4279121715f2d84aa4808757396b677d | bigcode/the-stack | train |
ed6d0b2588ffa9206afc9327 | train | function | def download_google_drive_url(url: str, output_path: str, output_file_name: str):
"""
Download a file from google drive
Downloading an URL from google drive requires confirmation when
the file of the size is too big (google drive notifies that
anti-viral checks cannot be performed on such files)
... | def download_google_drive_url(url: str, output_path: str, output_file_name: str):
| """
Download a file from google drive
Downloading an URL from google drive requires confirmation when
the file of the size is too big (google drive notifies that
anti-viral checks cannot be performed on such files)
"""
import requests
with requests.Session() as session:
# Firs... | BNZBtViDHQ6_Ewsp
"""
splits = view_url.split("/")
assert splits[-1] == "view"
file_id = splits[-2]
return f"https://drive.google.com/uc?export=download&id={file_id}"
def download_google_drive_url(url: str, output_path: str, output_file_name: str):
| 77 | 78 | 263 | 20 | 57 | ankitshah009/vissl | vissl/utils/download.py | Python | download_google_drive_url | download_google_drive_url | 56 | 87 | 56 | 56 | 58b7e9108daad7265b22d2f72e3d724b220c60b4 | bigcode/the-stack | train |
1fdca6b156b4ebf693b09b09 | train | function | def _urlretrieve(url: str, filename: str, chunk_size: int = 1024) -> None:
with open(filename, "wb") as fh:
with urllib.request.urlopen(
urllib.request.Request(url, headers={"User-Agent": "vissl"})
) as response:
with tqdm(total=response.length) as pbar:
for c... | def _urlretrieve(url: str, filename: str, chunk_size: int = 1024) -> None:
| with open(filename, "wb") as fh:
with urllib.request.urlopen(
urllib.request.Request(url, headers={"User-Agent": "vissl"})
) as response:
with tqdm(total=response.length) as pbar:
for chunk in iter(lambda: response.read(chunk_size), ""):
if... | None
match = re.match(r"/file/d/(?P<id>[^/]*)", parts.path)
if match is None:
return None
return match.group("id")
def _urlretrieve(url: str, filename: str, chunk_size: int = 1024) -> None:
| 64 | 64 | 107 | 24 | 40 | ankitshah009/vissl | vissl/utils/download.py | Python | _urlretrieve | _urlretrieve | 105 | 115 | 105 | 105 | 64fda16764bc262ccaf0c0dd7292ed005146e2e7 | bigcode/the-stack | train |
c0d377ca4e76b8ad97ecfc2e | train | function | def download_and_extract_archive(
url: str,
download_root: str,
extract_root: Optional[str] = None,
filename: Optional[str] = None,
md5: Optional[str] = None,
remove_finished: bool = False,
) -> None:
download_root = os.path.expanduser(download_root)
if extract_root is None:
extr... | def download_and_extract_archive(
url: str,
download_root: str,
extract_root: Optional[str] = None,
filename: Optional[str] = None,
md5: Optional[str] = None,
remove_finished: bool = False,
) -> None:
| download_root = os.path.expanduser(download_root)
if extract_root is None:
extract_root = download_root
if not filename:
filename = os.path.basename(url)
download_url(url, download_root, filename, md5)
archive = os.path.join(download_root, filename)
print("Extracting {} to {}".... | not found or corrupted.")
def download_and_extract_archive(
url: str,
download_root: str,
extract_root: Optional[str] = None,
filename: Optional[str] = None,
md5: Optional[str] = None,
remove_finished: bool = False,
) -> None:
| 63 | 64 | 147 | 58 | 5 | ankitshah009/vissl | vissl/utils/download.py | Python | download_and_extract_archive | download_and_extract_archive | 173 | 191 | 173 | 180 | 968cbbf2fabea8e7110399be850f78eff723da37 | bigcode/the-stack | train |
8d5ca64bdc3df319509fe506 | train | function | def to_google_drive_download_url(view_url: str) -> str:
"""
Utility function to transform a view URL of google drive
to a download URL for google drive
Example input:
https://drive.google.com/file/d/137RyRjvTBkBiIfeYBNZBtViDHQ6_Ewsp/view
Example output:
https://drive.google.com/uc?... | def to_google_drive_download_url(view_url: str) -> str:
| """
Utility function to transform a view URL of google drive
to a download URL for google drive
Example input:
https://drive.google.com/file/d/137RyRjvTBkBiIfeYBNZBtViDHQ6_Ewsp/view
Example output:
https://drive.google.com/uc?export=download&id=137RyRjvTBkBiIfeYBNZBtViDHQ6_Ewsp
... | irection
"""
import requests
with requests.Session() as session:
with session.get(url, stream=True, allow_redirects=True) as response:
if response.history:
return response.url
else:
return url
def to_google_drive_download_url(view_url: str) ->... | 64 | 64 | 159 | 14 | 49 | ankitshah009/vissl | vissl/utils/download.py | Python | to_google_drive_download_url | to_google_drive_download_url | 39 | 53 | 39 | 39 | 1baee744397b72ae86f5c3e8970f70d10377c6b3 | bigcode/the-stack | train |
fafcec5310467e7cf62d5b83 | train | function | def download_url(
url: str,
root: str,
filename: Optional[str] = None,
md5: Optional[str] = None,
) -> None:
"""Download a file from a url and place it in root.
Args:
url (str): URL to download file from
root (str): Directory to place downloaded file in
filename (str, op... | def download_url(
url: str,
root: str,
filename: Optional[str] = None,
md5: Optional[str] = None,
) -> None:
| """Download a file from a url and place it in root.
Args:
url (str): URL to download file from
root (str): Directory to place downloaded file in
filename (str, optional): Name to save the file under.
If None, use the basename of the URL.
md5 (st... | 1024) -> None:
with open(filename, "wb") as fh:
with urllib.request.urlopen(
urllib.request.Request(url, headers={"User-Agent": "vissl"})
) as response:
with tqdm(total=response.length) as pbar:
for chunk in iter(lambda: response.read(chunk_size), ""):
... | 126 | 126 | 420 | 37 | 89 | ankitshah009/vissl | vissl/utils/download.py | Python | download_url | download_url | 118 | 170 | 118 | 123 | ca698710ef134c797f9527212541689e7ae7c077 | bigcode/the-stack | train |
05341c0942e5b703ce0ab3f7 | train | function | def fit_fun(t, A, f, phi, C):
return A * np.sin(2 * np.pi * f * t + phi) + C
| def fit_fun(t, A, f, phi, C):
| return A * np.sin(2 * np.pi * f * t + phi) + C
| ins):
idx = bins_vals[vb] == b
y_binned[i] = np.mean(yvec2[idx])
y_errors[i] = np.std(yvec2[idx])
return bins, y_binned, y_errors
def fit_fun(t, A, f, phi, C):
| 64 | 64 | 34 | 13 | 50 | charlesblakemore/opt_lev_analysis | scripts/general_analysis/binning_test.py | Python | fit_fun | fit_fun | 30 | 31 | 30 | 30 | cee9dc8f97443c715c88c2f0835b522a6abd7cb6 | bigcode/the-stack | train |
6a7c3319cfd7eb43f471c012 | train | function | def sbin_pn(xvec, yvec, bin_size=1., vel_mult = 0.):
#Bins yvec based on binning xvec into bin_size for velocities*vel_mult>0.
fac = 1./bin_size
bins_vals = np.around(fac*xvec)
bins_vals /= fac
bins = np.unique(bins_vals)
y_binned = np.zeros_like(bins)
y_errors = np.zeros_like(bins)
if v... | def sbin_pn(xvec, yvec, bin_size=1., vel_mult = 0.):
#Bins yvec based on binning xvec into bin_size for velocities*vel_mult>0.
| fac = 1./bin_size
bins_vals = np.around(fac*xvec)
bins_vals /= fac
bins = np.unique(bins_vals)
y_binned = np.zeros_like(bins)
y_errors = np.zeros_like(bins)
if vel_mult:
vb = np.gradient(xvec)*vel_mult>0.
yvec2 = yvec[vb]
else:
vb = yvec == yvec
yvec2 = yv... | .pyplot as plt
import scipy.interpolate as interp
import scipy.optimize as optimize
import scipy
def sbin_pn(xvec, yvec, bin_size=1., vel_mult = 0.):
#Bins yvec based on binning xvec into bin_size for velocities*vel_mult>0.
| 64 | 64 | 209 | 45 | 18 | charlesblakemore/opt_lev_analysis | scripts/general_analysis/binning_test.py | Python | sbin_pn | sbin_pn | 8 | 27 | 8 | 9 | 18d5a1617867d5de84876ea6b0e8873a103010da | bigcode/the-stack | train |
d69a86ccfbdfcd06f0eca848 | train | function | def generalization_test(scale=20):
print('Generalization test...')
# Test case parameters
reaction_mech = {
'Schirmeister': '../KM/2009_Schirmeister_EDC/chem_annotated_irreversible.cti'
}
pressure_0 = 12.4
CCl4_X_0 = 1000
CHCl3_X_0 = 200
Tri_X_0 = 200
CP_X_0 = 200... | def generalization_test(scale=20):
| print('Generalization test...')
# Test case parameters
reaction_mech = {
'Schirmeister': '../KM/2009_Schirmeister_EDC/chem_annotated_irreversible.cti'
}
pressure_0 = 12.4
CCl4_X_0 = 1000
CHCl3_X_0 = 200
Tri_X_0 = 200
CP_X_0 = 200
T_list = [320, 348, 374.7, 399.3... | elif single:
if not os.path.exists(os.path.join(PLOTPATH, "predict")):
os.mkdir(os.path.join(PLOTPATH, "predict"))
plt.savefig(os.path.join(
PLOTPATH, 'predict', '{}.png'.format(name)))
elif iter_CCl4 is True:
if not os.path.exists(os.pa... | 256 | 256 | 4,365 | 8 | 247 | WesleyLeeNTU/EDC | Coke/ML/ML_model_cokingV2.py | Python | generalization_test | generalization_test | 588 | 964 | 588 | 589 | f34d84fbcef625578fe9e9aebb605317cc873ca8 | bigcode/the-stack | train |
02cacbc84fd3caa88b0489be | train | function | def predict(reaction_mech, T_list, pressure_0, CCl4_X_0, CHCl3_X_0, Tri_X_0, CP_X_0,
mass_flow_rate, n_steps, n_pfr, length, area, save_fig=False, name='predict', fold_no=None, iter_CCl4=False, FPC=True, print_cracking=False, loss=False, single=False):
"""
Load the saved parameters of StandardSca... | def predict(reaction_mech, T_list, pressure_0, CCl4_X_0, CHCl3_X_0, Tri_X_0, CP_X_0,
mass_flow_rate, n_steps, n_pfr, length, area, save_fig=False, name='predict', fold_no=None, iter_CCl4=False, FPC=True, print_cracking=False, loss=False, single=False):
| """
Load the saved parameters of StandardScaler() and rebuild the ML model to
do predictions.
=============== =============================================================
Attribute Description
=============== =============================================================
`react... | 0)
print(f'Testset loss for {fold_no}: {loss:.4f}')
return loss, acc*100
else:
loss, acc, *is_anything_else_being_returned = model.evaluate(
x=X_test, y=y_test, batch_size=batch_size)
# print(is_anything_else_being_returned)
textstr = f'Testset loss : {lo... | 255 | 256 | 2,450 | 87 | 168 | WesleyLeeNTU/EDC | Coke/ML/ML_model_cokingV2.py | Python | predict | predict | 385 | 585 | 385 | 386 | 75c8609e870d9364394813b2c41bc73fd13fdb04 | bigcode/the-stack | train |
321e7b5024affa1f5909d522 | train | function | def train_model(X_train=None, X_test=None, y_train=None, y_test=None, fold_no=None, verbose=TRAINING_VERBOSE):
# Set model parameters
# print(np.where(np.isnan(X_train[2])))
# print(np.where(np.isnan(y_train)))
lr = LEARNINGRATE
epoch = EPOCH
batch_size = BATCHSIZE
# Early stopping
... | def train_model(X_train=None, X_test=None, y_train=None, y_test=None, fold_no=None, verbose=TRAINING_VERBOSE):
# Set model parameters
# print(np.where(np.isnan(X_train[2])))
# print(np.where(np.isnan(y_train)))
| lr = LEARNINGRATE
epoch = EPOCH
batch_size = BATCHSIZE
# Early stopping
early_stopping = callbacks.EarlyStopping(
monitor='val_loss', mode='min', patience=200, restore_best_weights=True)
csvLogger_callback = CSVLogger('traininglogs.csv')
# Build model
print('Bulid model..... | f:
pickle.dump(scaler, f)
# Change the shape of X in order to separate to ordinary input (in-out temp) and auxilary input (29-species mass fraction and pressure in ,CCL4 initial ratio,t,tr for every tube)
X_train = [rescaled_X_train[:, 0:2],
rescaled_X_train[:, 2:]... | 189 | 189 | 631 | 58 | 130 | WesleyLeeNTU/EDC | Coke/ML/ML_model_cokingV2.py | Python | train_model | train_model | 321 | 382 | 321 | 325 | 0bc27fece4305187e748a50293b3dd3eae9ca4a8 | bigcode/the-stack | train |
8b5bd5ed081e684a81dd621e | train | function | def build_model(lr=0.001):
first_input = Input(shape=(2,), name='Input_layer_1')
second_input = Input(shape=(36,), name='Input_layer_2')
raw_third_input = Input(shape=(1,), name='Prev_coking')
layer = Dense(6, name='Hinden_layer_1')(first_input)
layer = Activation('relu')(layer)
layer ... | def build_model(lr=0.001):
| first_input = Input(shape=(2,), name='Input_layer_1')
second_input = Input(shape=(36,), name='Input_layer_2')
raw_third_input = Input(shape=(1,), name='Prev_coking')
layer = Dense(6, name='Hinden_layer_1')(first_input)
layer = Activation('relu')(layer)
layer = concatenate([layer, second... | PREDICT = args.no_predict
CPU = args.cpu
TRAINING = args.no_train
GENE = args.no_gene
T_IN = args.no_T_in
FPC = args.FPC
# def root_mean_squared_error(y_true, y_pred):
# return K.sqrt(K.mean(K.square(y_pred - y_true), axis=-1))
def build_model(lr=0.001):
| 88 | 89 | 298 | 10 | 78 | WesleyLeeNTU/EDC | Coke/ML/ML_model_cokingV2.py | Python | build_model | build_model | 188 | 212 | 188 | 188 | 928d8a03c961ec94051bbb02a1c80c7e10234b34 | bigcode/the-stack | train |
405175284d96b6d435000d4c | train | function | def arg_parser():
parser = argparse.ArgumentParser(description='model parameters.')
parser.add_argument('--name', required=True, type=str,
help='name of the experiment')
parser.add_argument(
'--data', default="training_data.csv", help='Training data')
parser.add_arg... | def arg_parser():
| parser = argparse.ArgumentParser(description='model parameters.')
parser.add_argument('--name', required=True, type=str,
help='name of the experiment')
parser.add_argument(
'--data', default="training_data.csv", help='Training data')
parser.add_argument('--no_mass', ... |
EPOCH = 12000
BATCHSIZE = 18
TRAINING_VERBOSE = 0 # 0: quiet 1: line
CSTR = 100
# Genearalization test
MASS_FLOW_RATE = True
CCL4 = True
CHCL3 = True
TRI = True
CP = True
INITAL_PRESSURE = True
NUMBER_OF_TUBES = True
PREDICT_ONLY = False
CPU = 8
TRAINING = True
GENE = True
PREDICT = True
T_IN = True... | 147 | 148 | 495 | 4 | 143 | WesleyLeeNTU/EDC | Coke/ML/ML_model_cokingV2.py | Python | arg_parser | arg_parser | 86 | 124 | 86 | 86 | 076045db081cb9e6ac3aef2ae6fcf0d56a69b02c | bigcode/the-stack | train |
bf76f21ea6144eb8868f6d1a | train | function | def DataPreprocessor():
# Load data
print('Loading data...')
dataframe = read_csv(TRAINING_DATA)
array = dataframe.values
# Separate array into input and output components
X = array[:, 0:-1] # X.shape=(alot,36)
Y = array[:, -1] # Y.shpae=(alot,1)
if DOKFOLD:
scaler =... | def DataPreprocessor():
# Load data
| print('Loading data...')
dataframe = read_csv(TRAINING_DATA)
array = dataframe.values
# Separate array into input and output components
X = array[:, 0:-1] # X.shape=(alot,36)
Y = array[:, -1] # Y.shpae=(alot,1)
if DOKFOLD:
scaler = StandardScaler()
rescaled_X = sc... | _layer')
layer = Activation('relu')(layer)
layer = Dense(83, name='Hinden_layer_4')(layer)
layer = Activation('relu')(layer)
layer = Dense(83, name='Hinden_layer_5')(layer)
layer = Activation('relu')(layer)
layer = Dense(1, name='Hinden_layer_6')(layer)
output = Activation('sigmoid')(... | 227 | 228 | 760 | 10 | 217 | WesleyLeeNTU/EDC | Coke/ML/ML_model_cokingV2.py | Python | DataPreprocessor | DataPreprocessor | 248 | 318 | 248 | 249 | 838fc85dd1b7f5957fa1c238c6a2acb338e38919 | bigcode/the-stack | train |
eff6fb2bb36c5b6a88357282 | train | function | def set_args(args):
global DOKFOLD
global TRAINING_DATA
global NAME
global NUMFOLDS
global RESULTPATH
global PLOTPATH
global LEARNINGRATE
global EPOCH
global BATCHSIZE
global TRAINING_VERBOSE
global CSTR
global MASS_FLOW_RATE
global CCL4
global CHC... | def set_args(args):
| global DOKFOLD
global TRAINING_DATA
global NAME
global NUMFOLDS
global RESULTPATH
global PLOTPATH
global LEARNINGRATE
global EPOCH
global BATCHSIZE
global TRAINING_VERBOSE
global CSTR
global MASS_FLOW_RATE
global CCL4
global CHCL3
global TRI
... | .add_argument('--no_predict', action="store_false", help='no prediction')
parser.add_argument('--cpu', default=8, type=int, help='ncpus')
parser.add_argument('--no_train', action='store_false', help='no training')
parser.add_argument('--no_gene', action='store_false',
help='no ge... | 126 | 126 | 423 | 5 | 120 | WesleyLeeNTU/EDC | Coke/ML/ML_model_cokingV2.py | Python | set_args | set_args | 127 | 181 | 127 | 128 | e066234db661206888cff56ce072706427fe459a | bigcode/the-stack | train |
1664c785c5e1682137f86f11 | train | function | def readme():
with open('README.rst') as f:
return f.read()
| def readme():
| with open('README.rst') as f:
return f.read()
| from setuptools import setup
def readme():
| 9 | 64 | 19 | 4 | 4 | kaustavg/curv | setup.py | Python | readme | readme | 3 | 5 | 3 | 3 | 1acd95168236f446216cb6e7302a47383a4b41b5 | bigcode/the-stack | train |
fafb423ff7b93af88be9bf91 | train | function | def setup_logging(level):
"""
Setup logging level
"""
logging.basicConfig(
format='%(levelname)s: %(message)s',
level=getattr(logging, level.upper())
)
| def setup_logging(level):
| """
Setup logging level
"""
logging.basicConfig(
format='%(levelname)s: %(message)s',
level=getattr(logging, level.upper())
)
| import logging
from gabby.udp_transmitter import UDPTransmitter
from gabby.message import Message
from gabby.topic import Topic
def setup_logging(level):
| 34 | 64 | 42 | 5 | 28 | luanguimaraesla/gabby | examples/udp/transmit.py | Python | setup_logging | setup_logging | 8 | 15 | 8 | 8 | 58d7f4bc072d10beeae2354fa2da29dfe52fd8cf | bigcode/the-stack | train |
dc5bd941671f0cdebc0534d6 | train | class | class mercado(Exchange):
def describe(self):
return self.deep_extend(super(mercado, self).describe(), {
'id': 'mercado',
'name': 'Mercado Bitcoin',
'countries': ['BR'], # Brazil
'rateLimit': 1000,
'version': 'v3',
'has': {
... | class mercado(Exchange):
| def describe(self):
return self.deep_extend(super(mercado, self).describe(), {
'id': 'mercado',
'name': 'Mercado Bitcoin',
'countries': ['BR'], # Brazil
'rateLimit': 1000,
'version': 'v3',
'has': {
'cancelOrder': True,
... | # -*- coding: utf-8 -*-
# PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
# https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
from ccxt.base.exchange import Exchange
import hashlib
from ccxt.base.errors import ExchangeError
from ccxt.base.errors import ArgumentsReq... | 106 | 256 | 4,953 | 5 | 100 | ngugcx/ccxt | python/ccxt/mercado.py | Python | mercado | mercado | 14 | 598 | 14 | 15 | 21a1a5e2eb3ea295c63c525812e6a8761591b54d | bigcode/the-stack | train |
7b9e9d88e7c678dbd434f9f0 | train | class | class RM_Peripheral_FEFILT0(Base_RM_Peripheral):
def __init__(self, rmio, label):
self.__dict__['zz_frozen'] = False
super(RM_Peripheral_FEFILT0, self).__init__(rmio, label,
0xA8040000, 'FEFILT0',
u"",
[])
self.IPVERSION = RM_Register_FEFILT0_IPVERSION(sel... | class RM_Peripheral_FEFILT0(Base_RM_Peripheral):
| def __init__(self, rmio, label):
self.__dict__['zz_frozen'] = False
super(RM_Peripheral_FEFILT0, self).__init__(rmio, label,
0xA8040000, 'FEFILT0',
u"",
[])
self.IPVERSION = RM_Register_FEFILT0_IPVERSION(self.zz_rmio, self.zz_label)
self.zz_rdict['... |
# -*- coding: utf-8 -*-
__all__ = [ 'RM_Peripheral_FEFILT0' ]
from . static import Base_RM_Peripheral
from . FEFILT0_register import *
class RM_Peripheral_FEFILT0(Base_RM_Peripheral):
| 57 | 256 | 1,635 | 14 | 43 | PascalGuenther/gecko_sdk | platform/radio/efr32_multiphy_configurator/host_py_rm_studio_internal/full/efr32xg25/revA0/FEFILT0.py | Python | RM_Peripheral_FEFILT0 | RM_Peripheral_FEFILT0 | 9 | 88 | 9 | 9 | 22343de8bd1a4caefb4a4fa72cd9d12137af2547 | bigcode/the-stack | train |
424aa8fc35c48864bb190320 | train | function | def read_time(measurement, profile, time, t):
year = int(str(time[0])[0:4])
month = int(str(time[0])[4:6])
day = int(str(time[0])[6:8])
time = datetime.timedelta(seconds=time[1])
profile['header']['start'] = datetime.datetime(
year, month, day, 0, 0) + time
if t > 0:
profile['s... | def read_time(measurement, profile, time, t):
| year = int(str(time[0])[0:4])
month = int(str(time[0])[4:6])
day = int(str(time[0])[6:8])
time = datetime.timedelta(seconds=time[1])
profile['header']['start'] = datetime.datetime(
year, month, day, 0, 0) + time
if t > 0:
profile['start'] = (profile['header']['start'] -
... | nc_file.variables['zenithangle'].getValue()
header['deltaT'] = nc_file.variables['measurement_height_resolution'].getValue()
header['rep_rate'] = nc_file.variables['laser_rep_rate'].getValue()
return header
def read_time(measurement, profile, time, t):
| 64 | 64 | 152 | 13 | 50 | sandrarum/inqbus.lidar | inqbus.lidar.components/src/inqbus/lidar/components/read_polly.py | Python | read_time | read_time | 56 | 70 | 56 | 56 | efd48a8d4d420a848e0ee3698829186fe35994cf | bigcode/the-stack | train |
27378982ea0e7994b613f0e6 | train | function | def same_header(h1, h2):
if h1['bins'] != h2['bins']:
return False
elif h1['num_channels'] != h2['num_channels']:
return False
elif h1['time_scales'] != h2['time_scales']:
return False
elif h1['angle'] != h2['angle']:
return False
elif h1['deltaT'] != h2['deltaT']:
... | def same_header(h1, h2):
| if h1['bins'] != h2['bins']:
return False
elif h1['num_channels'] != h2['num_channels']:
return False
elif h1['time_scales'] != h2['time_scales']:
return False
elif h1['angle'] != h2['angle']:
return False
elif h1['deltaT'] != h2['deltaT']:
return False
el... | len(meas_parts[mp]['data'])):
profile = meas_parts[mp]['data'][p]
profile['start'] = profile['start'] + timedelta
profile['stop'] = profile['stop'] + timedelta
measurement['data'].append(profile)
meas_parts[mp] = {}
return measurement
def same... | 77 | 77 | 258 | 9 | 67 | sandrarum/inqbus.lidar | inqbus.lidar.components/src/inqbus/lidar/components/read_polly.py | Python | same_header | same_header | 103 | 130 | 103 | 103 | 5fbe59d8e41f9727378c44f0152d09af40f951e2 | bigcode/the-stack | train |
baa10eccf53f4b89fa54cb85 | train | function | def read_data(measurement, profile, t, nc_file, CHANNEL_IDs):
profile['data'] = []
for ch in range(0, measurement['header']['num_channels']):
if CHANNEL_IDs[ch] != -1:
signal = nc_file.variables['raw_signal'][t, :, ch]
profile['data'].append(signal)
| def read_data(measurement, profile, t, nc_file, CHANNEL_IDs):
| profile['data'] = []
for ch in range(0, measurement['header']['num_channels']):
if CHANNEL_IDs[ch] != -1:
signal = nc_file.variables['raw_signal'][t, :, ch]
profile['data'].append(signal)
| ']['start'] -
measurement['data'][0]['header']['start']).seconds
measurement['data'][t - 1]['stop'] = profile['start']
else:
profile['start'] = 0
def read_data(measurement, profile, t, nc_file, CHANNEL_IDs):
| 64 | 64 | 74 | 18 | 45 | sandrarum/inqbus.lidar | inqbus.lidar.components/src/inqbus/lidar/components/read_polly.py | Python | read_data | read_data | 73 | 78 | 73 | 73 | da461e8d80fa1e79226b1f3d83a2a4248519f40d | bigcode/the-stack | train |
0d55ad2607ce4648b42eb120 | train | function | def read_header(nc_file, CHANNEL_IDs):
header = {}
header['bins'] = nc_file.dimensions['height']
header['num_channels'] = nc_file.dimensions['channel']
header['time_scales'] = 1
header['angle'] = nc_file.variables['zenithangle'].getValue()
header['deltaT'] = nc_file.variables['measurement_heigh... | def read_header(nc_file, CHANNEL_IDs):
| header = {}
header['bins'] = nc_file.dimensions['height']
header['num_channels'] = nc_file.dimensions['channel']
header['time_scales'] = 1
header['angle'] = nc_file.variables['zenithangle'].getValue()
header['deltaT'] = nc_file.variables['measurement_height_resolution'].getValue()
header['r... | '].append(CHANNEL_IDs[ch])
measurement['header']['acqtype'].append(1)
measurement['header']['num_channels'] = len(
measurement['header']['channel_id'])
measurement['header']['time_scales'] = 1
def read_header(nc_file, CHANNEL_IDs):
| 64 | 64 | 110 | 11 | 52 | sandrarum/inqbus.lidar | inqbus.lidar.components/src/inqbus/lidar/components/read_polly.py | Python | read_header | read_header | 43 | 53 | 43 | 43 | b30bbb661224df57849f7ef2fb5c727f303b5f28 | bigcode/the-stack | train |
32e34cc4e4284eb8390ef8b9 | train | function | def read_one_file(
zfilename,
CHANNEL_IDs,
WAVELENGTHS,
SCAT_TYPES,
RANGE_ID,
GROUND_PRES,
GROUND_TEMP):
measurement = {}
measurement['data'] = []
nc_file_name = os.path.splitext(zfilename)[0]
nc_file = netcdf.netcdf_file(nc_file_name, 'r', False,... | def read_one_file(
zfilename,
CHANNEL_IDs,
WAVELENGTHS,
SCAT_TYPES,
RANGE_ID,
GROUND_PRES,
GROUND_TEMP):
| measurement = {}
measurement['data'] = []
nc_file_name = os.path.splitext(zfilename)[0]
nc_file = netcdf.netcdf_file(nc_file_name, 'r', False, 1)
measurement['header'] = read_header(nc_file, CHANNEL_IDs)
shots = nc_file.variables['measurement_shots'].data
times = nc_file.variables['measur... | s,
WAVELENGTHS,
SCAT_TYPES,
RANGE_ID,
GROUND_PRES,
GROUND_TEMP))
if len(meas_parts) > 1:
return combine(meas_parts)
else:
return meas_parts[0]
def read_one_file(
zfilename,
CHANNEL_IDs,
WAVELE... | 96 | 96 | 322 | 40 | 56 | sandrarum/inqbus.lidar | inqbus.lidar.components/src/inqbus/lidar/components/read_polly.py | Python | read_one_file | read_one_file | 163 | 207 | 163 | 170 | fe9e6cb330260415cad6906b6ca54bb7b7fb9452 | bigcode/the-stack | train |
6d68464133b8e23db1d01736 | train | function | def read(
INPATH,
zfilenames,
CHANNEL_IDs,
WAVELENGTHS,
SCAT_TYPES,
RANGE_ID,
GROUND_PRES,
GROUND_TEMP):
zfilenames.sort()
meas_parts = []
for zfilename in zfilenames:
print(zfilename)
meas_parts.append(
read_one_fil... | def read(
INPATH,
zfilenames,
CHANNEL_IDs,
WAVELENGTHS,
SCAT_TYPES,
RANGE_ID,
GROUND_PRES,
GROUND_TEMP):
| zfilenames.sort()
meas_parts = []
for zfilename in zfilenames:
print(zfilename)
meas_parts.append(
read_one_file(
os.path.join(
INPATH,
zfilename),
CHANNEL_IDs,
WAVELENGTHS,
SC... | ['acqtype'] != h2['acqtype']:
return False
return True
def read(
INPATH,
zfilenames,
CHANNEL_IDs,
WAVELENGTHS,
SCAT_TYPES,
RANGE_ID,
GROUND_PRES,
GROUND_TEMP):
| 64 | 64 | 150 | 43 | 20 | sandrarum/inqbus.lidar | inqbus.lidar.components/src/inqbus/lidar/components/read_polly.py | Python | read | read | 133 | 160 | 133 | 141 | f9b7bbae3c1b71e9f75558751a488f4d81949acd | bigcode/the-stack | train |
e4a683435be027eb2ae0aff6 | train | function | def add_general_header_info(measurement, CHANNEL_IDs):
last_profile = measurement['data'][len(measurement['data']) - 1]
last_profile['stop'] = last_profile['start'] + \
int(last_profile['header']['shots'][0] /
measurement['header']['rep_rate'])
range_res = float(measurement['header']['d... | def add_general_header_info(measurement, CHANNEL_IDs):
| last_profile = measurement['data'][len(measurement['data']) - 1]
last_profile['stop'] = last_profile['start'] + \
int(last_profile['header']['shots'][0] /
measurement['header']['rep_rate'])
range_res = float(measurement['header']['deltaT'] * 1E-9 * LIGHT_SPEED / 2)
measurement['head... | import datetime
import os
from scipy.io import netcdf
BG_FIRST = 0
BG_LAST = 251
LIGHT_SPEED = 3E8
def add_general_header_info(measurement, CHANNEL_IDs):
| 46 | 96 | 322 | 13 | 32 | sandrarum/inqbus.lidar | inqbus.lidar.components/src/inqbus/lidar/components/read_polly.py | Python | add_general_header_info | add_general_header_info | 11 | 40 | 11 | 12 | 36aba2c8edf90b686ed9d6e8683fff34897c78ed | bigcode/the-stack | train |
918ae0ee679e224548b79af6 | train | function | def combine(meas_parts):
print('combine')
measurement = meas_parts[0]
for mp in range(1, len(meas_parts)):
if same_header(measurement['header'], meas_parts[mp]['header']):
measurement['header']['stop'] = meas_parts[mp]['header']['stop']
timedelta = (
meas_p... | def combine(meas_parts):
| print('combine')
measurement = meas_parts[0]
for mp in range(1, len(meas_parts)):
if same_header(measurement['header'], meas_parts[mp]['header']):
measurement['header']['stop'] = meas_parts[mp]['header']['stop']
timedelta = (
meas_parts[mp]['header']['start... | s):
profile['data'] = []
for ch in range(0, measurement['header']['num_channels']):
if CHANNEL_IDs[ch] != -1:
signal = nc_file.variables['raw_signal'][t, :, ch]
profile['data'].append(signal)
def combine(meas_parts):
| 64 | 64 | 168 | 6 | 58 | sandrarum/inqbus.lidar | inqbus.lidar.components/src/inqbus/lidar/components/read_polly.py | Python | combine | combine | 81 | 100 | 81 | 81 | b78364cc6fede35d42ab6a7a70bdc815962ff730 | bigcode/the-stack | train |
c9704cc6fdbb701aaac48a7d | train | class | @six.add_metaclass(abc.ABCMeta)
class ProgressivePolicy:
"""The APIs for handling progressive training stages.
Attributes:
cur_model: The model for the current progressive training stage.
cur_train_dataset: The train dataset function for the current stage.
cur_eval_dataset: The eval dataset function fo... | @six.add_metaclass(abc.ABCMeta)
class ProgressivePolicy:
| """The APIs for handling progressive training stages.
Attributes:
cur_model: The model for the current progressive training stage.
cur_train_dataset: The train dataset function for the current stage.
cur_eval_dataset: The eval dataset function for the current stage.
cur_optimizer: The optimizer for... | # Copyright 2021 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | 253 | 256 | 1,139 | 15 | 237 | TensorFlow230/TF230Updates | official/modeling/fast_training/progressive/policies.py | Python | ProgressivePolicy | ProgressivePolicy | 38 | 178 | 38 | 39 | bcc39d0c778004bd18d396565a4f413c6720665b | bigcode/the-stack | train |
eef10b95267daa27d0882b3c | train | class | @dataclasses.dataclass
class ProgressiveConfig(base_config.Config):
pass
| @dataclasses.dataclass
class ProgressiveConfig(base_config.Config):
| pass
|
from typing import Any, Mapping
from absl import logging
import six
import tensorflow as tf
from official.common import streamz_counters
from official.modeling.fast_training.progressive import utils
from official.modeling.hyperparams import base_config
@dataclasses.dataclass
class ProgressiveConfig(base_config.Config... | 64 | 64 | 15 | 12 | 51 | TensorFlow230/TF230Updates | official/modeling/fast_training/progressive/policies.py | Python | ProgressiveConfig | ProgressiveConfig | 33 | 35 | 33 | 34 | ea0af2d8da02fa9350d5172220f3912ba82a9918 | bigcode/the-stack | train |
fb8e3cf03bbe01c446938e83 | train | class | class Model_Faciallandmark(Model):
'''
Class for the Facial landmark Model.
'''
def predict(self, image, offset=10):
'''
This method is meant for running predictions on the input image.
'''
self.image = image.copy()
print('Facial Landmarks predict..')
pre... | class Model_Faciallandmark(Model):
| '''
Class for the Facial landmark Model.
'''
def predict(self, image, offset=10):
'''
This method is meant for running predictions on the input image.
'''
self.image = image.copy()
print('Facial Landmarks predict..')
pre_image = self.preprocess_input(self... | '''
This is a sample class for a model. You may choose to use it as-is or make any changes to it.
This has been provided just to give you an idea of how to structure your model class.
'''
from openvino.inference_engine import IENetwork, IECore
import numpy as np
import os
import cv2
import sys
from base_model import Mo... | 87 | 225 | 752 | 8 | 78 | geochri/Intel_Edge_AI-Computer_Pointer_controller | src/faciallandmarks_model.py | Python | Model_Faciallandmark | Model_Faciallandmark | 13 | 89 | 13 | 13 | 8d8646bef66abdf724aa6d1dbefc200df96d2f09 | bigcode/the-stack | train |
2d7d277f79731d0bf0671cf8 | train | function | def replace_words(text, word_dic):
"""
take a text and <strong class="highlight">replace</strong> <strong class="highlight">words</strong> that match a key in a dictionary with
the associated value, return the changed text
"""
rc = re.compile('|'.join(map(re.escape, word_dic)))
def translate(mat... | def replace_words(text, word_dic):
| """
take a text and <strong class="highlight">replace</strong> <strong class="highlight">words</strong> that match a key in a dictionary with
the associated value, return the changed text
"""
rc = re.compile('|'.join(map(re.escape, word_dic)))
def translate(match):
return word_dic[match.... | from trees.lexicalized_tree import LexicalizedTree
import re
def replace_words(text, word_dic):
| 23 | 64 | 95 | 8 | 14 | Akanni96/feng-hirst-rst-parser | src/prep/prep_utils.py | Python | replace_words | replace_words | 4 | 12 | 4 | 4 | 9213512865dca0f05e7bbcf902c6996220b9165b | bigcode/the-stack | train |
aa879431f68b0148058d87d5 | train | function | def create_lexicalized_tree(unlexicalized_tree, heads):
"""
Creates a lexicalized syntax tree given a MRG-style parse and a Penn2Malt style heads file.
"""
t = unlexicalized_tree.copy(True)
t.lexicalize(heads)
return t
| def create_lexicalized_tree(unlexicalized_tree, heads):
| """
Creates a lexicalized syntax tree given a MRG-style parse and a Penn2Malt style heads file.
"""
t = unlexicalized_tree.copy(True)
t.lexicalize(heads)
return t
| = line.strip()
#print line
if line != '':
parsed_trees.append(LexicalizedTree.fromstring(line, leaf_pattern = '(?<=\\s)[^\)\(]+'))
return parsed_trees
def create_lexicalized_tree(unlexicalized_tree, heads):
| 64 | 64 | 68 | 15 | 48 | Akanni96/feng-hirst-rst-parser | src/prep/prep_utils.py | Python | create_lexicalized_tree | create_lexicalized_tree | 26 | 33 | 26 | 26 | 45f2d1eb29fa15985e60ac48bd9d62cabb5388ef | bigcode/the-stack | train |
2f85160c1043425f0288e96e | train | function | def get_parsed_trees_from_string(tree_strings):
# tree_strings separated by "\n"
parsed_trees = []
for line in tree_strings:
line = line.strip()
#print line
if line != '':
parsed_trees.append(LexicalizedTree.fromstring(line, leaf_pattern = '(?<=\\s)[^\)\(]+'))
ret... | def get_parsed_trees_from_string(tree_strings):
# tree_strings separated by "\n"
| parsed_trees = []
for line in tree_strings:
line = line.strip()
#print line
if line != '':
parsed_trees.append(LexicalizedTree.fromstring(line, leaf_pattern = '(?<=\\s)[^\)\(]+'))
return parsed_trees
| changed text
"""
rc = re.compile('|'.join(map(re.escape, word_dic)))
def translate(match):
return word_dic[match.group(0)]
return rc.sub(translate, text)
def get_parsed_trees_from_string(tree_strings):
# tree_strings separated by "\n"
| 64 | 64 | 84 | 20 | 44 | Akanni96/feng-hirst-rst-parser | src/prep/prep_utils.py | Python | get_parsed_trees_from_string | get_parsed_trees_from_string | 14 | 23 | 14 | 15 | a5ea18374028aa8aa9494498b19e940d95051fa0 | bigcode/the-stack | train |
8afdff8884d5ed90e9e14cb9 | train | class | class Migration(migrations.Migration):
dependencies = [
('robocrm', '0004_auto_20140912_1719'),
]
operations = [
migrations.CreateModel(
name='Officers',
fields=[
('id', models.AutoField(auto_created=True, verbose_name='ID', primary_key=True, seriali... | class Migration(migrations.Migration):
| dependencies = [
('robocrm', '0004_auto_20140912_1719'),
]
operations = [
migrations.CreateModel(
name='Officers',
fields=[
('id', models.AutoField(auto_created=True, verbose_name='ID', primary_key=True, serialize=False)),
('position',... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import officers.models
class Migration(migrations.Migration):
| 35 | 64 | 137 | 7 | 27 | CMU-Robotics-Club/roboticsclub.org | officers/migrations/0001_initial.py | Python | Migration | Migration | 8 | 27 | 8 | 9 | bd51e449fa5366b2ed17f62eb5827cea301cb903 | bigcode/the-stack | train |
a30dc1537a556312febbd0ec | train | class | class TestVote(object):
@responses.activate
def test_vote(self):
responses.add(responses.POST, 'https://buildbox.23.gs/count/', '')
ATestScraper('Test_Test').vote()
| class TestVote(object):
@responses.activate
| def test_vote(self):
responses.add(responses.POST, 'https://buildbox.23.gs/count/', '')
ATestScraper('Test_Test').vote()
| # Copyright (C) 2015-2019 Tobias Gruetzmacher
from __future__ import absolute_import, division, print_function
import responses
from dosagelib import scraper
class ATestScraper(scraper._BasicScraper):
pass
class TestVote(object):
@responses.activate
| 64 | 64 | 46 | 10 | 53 | acaranta/dosage | tests/test_vote.py | Python | TestVote | TestVote | 17 | 22 | 17 | 18 | 552ec1b87488aca138f2872be1b8a311e92655cc | bigcode/the-stack | train |
7794238360ba871dc468dd0b | train | class | class ATestScraper(scraper._BasicScraper):
pass
| class ATestScraper(scraper._BasicScraper):
| pass
| ) 2012-2014 Bastian Kleineidam
# Copyright (C) 2015-2019 Tobias Gruetzmacher
from __future__ import absolute_import, division, print_function
import responses
from dosagelib import scraper
class ATestScraper(scraper._BasicScraper):
| 64 | 64 | 15 | 12 | 51 | acaranta/dosage | tests/test_vote.py | Python | ATestScraper | ATestScraper | 13 | 14 | 13 | 13 | 16f101a0fad42f7208fc84291cff691d9eeb58eb | bigcode/the-stack | train |
29bb9001a56d20f990bd6e38 | train | function | def filter_features_by_cor(df):
m = len(df.columns)
output = df.iloc[:, m - 1]
output_list = output.tolist()
corrcoef_array = []
for i in range(0, m - 2):
input_list = df.iloc[:, i].tolist()
cols = [input_list, output_list]
corrcoef = abs(np.corrcoef(cols))
corrcoe... | def filter_features_by_cor(df):
| m = len(df.columns)
output = df.iloc[:, m - 1]
output_list = output.tolist()
corrcoef_array = []
for i in range(0, m - 2):
input_list = df.iloc[:, i].tolist()
cols = [input_list, output_list]
corrcoef = abs(np.corrcoef(cols))
corrcoef_array = np.append(corrcoef_arr... | def filter_features_by_cor(df):
| 7 | 64 | 191 | 7 | 0 | anaconda121/Data-Science | ML/pearson_correlation_coefficient.py | Python | filter_features_by_cor | filter_features_by_cor | 1 | 22 | 1 | 1 | a62479dbb74b2a80d35ce8ef755ce9e41c71b18a | bigcode/the-stack | train |
d661574025a4368e7ffaf8f6 | train | function | def test_data_loader_env():
replica_index = 0
replica_size = 1
del os.environ["RANK"]
os.environ["REPLICA_SIZE"] = str(replica_size)
os.environ["REPLICA_INDEX"] = str(replica_index)
reload_env()
assert get_replica_size() == replica_size
assert get_replica_index() == replica_index
| def test_data_loader_env():
| replica_index = 0
replica_size = 1
del os.environ["RANK"]
os.environ["REPLICA_SIZE"] = str(replica_size)
os.environ["REPLICA_INDEX"] = str(replica_index)
reload_env()
assert get_replica_size() == replica_size
assert get_replica_index() == replica_index
| )
os.environ["WORLD_SIZE"] = str(world_size)
os.environ["LOCAL_RANK"] = str(local_rank)
reload_env()
assert get_world_size() == world_size
assert get_rank() == rank
assert get_local_rank() == local_rank
def test_data_loader_env():
| 64 | 64 | 84 | 6 | 57 | dumpmemory/PERSIA | test/test_env.py | Python | test_data_loader_env | test_data_loader_env | 27 | 37 | 27 | 27 | 25f1c219bb28c8ee94957ab6fc71a6828017214e | bigcode/the-stack | train |
363f0b5a02a5802a90c98a2b | train | function | def test_nn_worker_env():
rank = 0
local_rank = 0
world_size = 1
os.environ["RANK"] = str(rank)
os.environ["WORLD_SIZE"] = str(world_size)
os.environ["LOCAL_RANK"] = str(local_rank)
reload_env()
assert get_world_size() == world_size
assert get_rank() == rank
assert get_local_ran... | def test_nn_worker_env():
| rank = 0
local_rank = 0
world_size = 1
os.environ["RANK"] = str(rank)
os.environ["WORLD_SIZE"] = str(world_size)
os.environ["LOCAL_RANK"] = str(local_rank)
reload_env()
assert get_world_size() == world_size
assert get_rank() == rank
assert get_local_rank() == local_rank
| import os
from persia.env import (
get_local_rank,
get_rank,
get_world_size,
get_replica_index,
get_replica_size,
reload_env,
)
def test_nn_worker_env():
| 46 | 64 | 94 | 6 | 40 | dumpmemory/PERSIA | test/test_env.py | Python | test_nn_worker_env | test_nn_worker_env | 13 | 24 | 13 | 13 | 1aa746c0d74ed1a5e2b1a3927659a9f7f49e4671 | bigcode/the-stack | train |
eb7ec41157151d0529cd1293 | train | function | def test_collect(tmp_dir, scm, dvc, run_copy):
def collect_outs(*args, **kwargs):
return {
str(out)
for stage in dvc.stage.collect(*args, **kwargs)
for out in stage.outs
}
tmp_dir.dvc_gen("foo", "foo")
run_copy("foo", "bar", single_stage=True)
scm.add... | def test_collect(tmp_dir, scm, dvc, run_copy):
| def collect_outs(*args, **kwargs):
return {
str(out)
for stage in dvc.stage.collect(*args, **kwargs)
for out in stage.outs
}
tmp_dir.dvc_gen("foo", "foo")
run_copy("foo", "bar", single_stage=True)
scm.add([".gitignore", "foo.dvc", "bar.dvc"])
scm.... | getter
import pytest
from funcy import raiser
from dvc.dvcfile import PIPELINE_FILE, FileIsGitIgnored
from dvc.exceptions import NoOutputOrStageError
from dvc.path_info import PathInfo
from dvc.repo import Repo
from dvc.stage.exceptions import (
StageFileDoesNotExistError,
StageFileFormatError,
StageNameU... | 127 | 127 | 426 | 14 | 112 | Sayanta66/dvc | tests/func/test_stage_load.py | Python | test_collect | test_collect | 22 | 60 | 22 | 22 | bc6e063f2e7de85488ea6aa0f16a57110aa56023 | bigcode/the-stack | train |
90355148e20e0b39fba61714 | train | function | def test_collect_glob(tmp_dir, dvc, stages):
assert set(dvc.stage.collect("copy*", glob=True)) == {
stages[key] for key in ["copy-bar-foobar", "copy-lorem-ipsum"]
}
assert set(
dvc.stage.collect("copy-lorem*", glob=True, with_deps=True)
) == {stages[key] for key in ["copy-lorem-ipsum", "... | def test_collect_glob(tmp_dir, dvc, stages):
| assert set(dvc.stage.collect("copy*", glob=True)) == {
stages[key] for key in ["copy-bar-foobar", "copy-lorem-ipsum"]
}
assert set(
dvc.stage.collect("copy-lorem*", glob=True, with_deps=True)
) == {stages[key] for key in ["copy-lorem-ipsum", "lorem-generate"]}
| ", accept_group=True))
== stages_info
)
assert (
set(
dvc.stage.collect_granular(
"build", accept_group=True, with_deps=True
)
)
== stages_info
)
def test_collect_glob(tmp_dir, dvc, stages):
| 64 | 64 | 98 | 13 | 51 | Sayanta66/dvc | tests/func/test_stage_load.py | Python | test_collect_glob | test_collect_glob | 182 | 188 | 182 | 182 | 7bcc6e8e0c56f1a3098cf80739900984c3680210 | bigcode/the-stack | train |
5cb5055f3c1260f31e36bf3e | train | function | def test_collect_generated(tmp_dir, dvc):
d = {
"vars": [{"vars": [1, 2, 3, 4, 5]}],
"stages": {
"build": {"foreach": "${vars}", "do": {"cmd": "echo ${item}"}}
},
}
dump_yaml("dvc.yaml", d)
all_stages = set(dvc.stages)
assert len(all_stages) == 5
assert set(... | def test_collect_generated(tmp_dir, dvc):
| d = {
"vars": [{"vars": [1, 2, 3, 4, 5]}],
"stages": {
"build": {"foreach": "${vars}", "do": {"cmd": "echo ${item}"}}
},
}
dump_yaml("dvc.yaml", d)
all_stages = set(dvc.stages)
assert len(all_stages) == 5
assert set(dvc.stage.collect()) == all_stages
ass... | -foobar"], None)}
assert set(
dvc.stage.collect_granular(
"copy-bar-foobar", accept_group=True, with_deps=True
)
) == {
(stages["copy-bar-foobar"], None),
(stages["copy-foo-bar"], None),
(stages["foo-generate"], None),
}
def test_collect_generated(tmp_dir,... | 87 | 87 | 290 | 10 | 77 | Sayanta66/dvc | tests/func/test_stage_load.py | Python | test_collect_generated | test_collect_generated | 143 | 179 | 143 | 143 | 6685a14adea50c8fe4995c9b88de97870bd1730b | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.