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
7920e5c1eb8215ad8262a439
train
class
class GANLoss(nn.Module): """Define different GAN objectives. The GANLoss class abstracts away the need to create the target label tensor that has the same size as the input. """ def __init__(self, gan_mode, target_real_label=1.0, target_fake_label=0.0): """ Initialize the GANLoss class. ...
class GANLoss(nn.Module):
"""Define different GAN objectives. The GANLoss class abstracts away the need to create the target label tensor that has the same size as the input. """ def __init__(self, gan_mode, target_real_label=1.0, target_fake_label=0.0): """ Initialize the GANLoss class. Parameters: ...
= get_norm_layer(norm_type=norm) if netD == 'basic': # default PatchGAN classifier net = NLayerDiscriminator(input_nc, ndf, n_layers=3, norm_layer=norm_layer) elif netD == 'n_layers': # more options net = NLayerDiscriminator(input_nc, ndf, n_layers_D, norm_layer=norm_layer) elif netD == ...
174
174
581
6
168
johnpeterflynn/surface-texture-inpainting-net
models/gan_networks.py
Python
GANLoss
GANLoss
219
285
219
219
dd4183417b4c2ab4c92bcab5e9584a2db38b6518
bigcode/the-stack
train
dc1dc12d733412634f916c38
train
function
def main(): log = logger('all.log',level='debug') logger('error.log', level='error').logger.error('error') # Set Parameters arg_parser = benchmark_argparser() args = arg_parser.make_args() csv_file_path = args.csv_file_path model_path = args.model_dir precision = args.precision # S...
def main():
log = logger('all.log',level='debug') logger('error.log', level='error').logger.error('error') # Set Parameters arg_parser = benchmark_argparser() args = arg_parser.make_args() csv_file_path = args.csv_file_path model_path = args.model_dir precision = args.precision # System Check ...
#!/usr/bin/python from utils import utilities, read_write_data, benchmark_argparser, run_benchmark_models import sys import os import pandas as pd import gc import warnings warnings.simplefilter("ignore") from utils import logger def main():
54
256
1,127
3
50
zhj-buffer/jetson_benchmarks
benchmark.py
Python
main
main
13
127
13
13
6b1d9c29ccca367e16fc410ae9b1c502ad5af154
bigcode/the-stack
train
8d8c8b6502dfe2308ba9fc6b
train
class
class Equation: def __init__(self, field, intercepX=0, intercepY=0 , time=0): self.Field = field self.X_ball = [] self.Y_ball = [] self.T_ball = [] self.Sy_Robot = [] self.Sx_Robot = [] self.InterceptionPointX = intercepX self.InterceptionPoin...
class Equation:
def __init__(self, field, intercepX=0, intercepY=0 , time=0): self.Field = field self.X_ball = [] self.Y_ball = [] self.T_ball = [] self.Sy_Robot = [] self.Sx_Robot = [] self.InterceptionPointX = intercepX self.InterceptionPointY = intercepY ...
# -*- coding: utf-8 -*- import matplotlib.pyplot as plt import matplotlib.image as mpimg import numpy as np import File_Handling_functions as fh import math as mth ''' Sx = ((-0.008 * pow(t, 3)) - (0.15 * pow(t, 2)) + 2.5 * t + 1) Vx = (((-0.024 * pow(t, 2)) - 0.3 * t + 2.5001) Ax = ((-0.048 * t) - 0.3) ...
193
256
2,651
3
190
antuniooh/PhysicsProject
src/BP_graphs.py
Python
Equation
Equation
20
405
20
20
a129e0be669474fc9aea0ba7617a8c63b4e26113
bigcode/the-stack
train
21970f10d95c4068e07018fb
train
function
def to_sentence(words): sent = '' if len(words) == 0: return sent sent += words[0].title() for word in words: if word == EOS: sent += '.' elif word == EOP: sent += '\n' elif word[0].isalnum(): sent += ' ' sent += word ...
def to_sentence(words):
sent = '' if len(words) == 0: return sent sent += words[0].title() for word in words: if word == EOS: sent += '.' elif word == EOP: sent += '\n' elif word[0].isalnum(): sent += ' ' sent += word else: sen...
return tokens def reduced_text(path=None): if not path: paragraphs = load_from_author('lfrankbaum') else: # SPECIFY A CUSTOM LOAD FUNC HERE paragraphs = load_paragraphs(path) return paragraphs_as_token_stream(paragraphs) def to_sentence(words):
64
64
92
5
59
anishpdoshi/pos-weighted-text-generation
data.py
Python
to_sentence
to_sentence
76
92
76
76
2b9cd32244896d11e49aa9819422f28e6c4a7fe3
bigcode/the-stack
train
adcf965f524be8893f43ef1d
train
function
def reduced_text(path=None): if not path: paragraphs = load_from_author('lfrankbaum') else: # SPECIFY A CUSTOM LOAD FUNC HERE paragraphs = load_paragraphs(path) return paragraphs_as_token_stream(paragraphs)
def reduced_text(path=None):
if not path: paragraphs = load_from_author('lfrankbaum') else: # SPECIFY A CUSTOM LOAD FUNC HERE paragraphs = load_paragraphs(path) return paragraphs_as_token_stream(paragraphs)
pos_tags = nltk.pos_tag(words) tokens.extend((clean_word(word), pos_tag[1]) for word, pos_tag in zip(words, pos_tags)) tokens.append((EOS, 'EOS')) tokens.append((EOP, 'EOP')) return tokens def reduced_text(path=None):
64
64
55
6
57
anishpdoshi/pos-weighted-text-generation
data.py
Python
reduced_text
reduced_text
68
74
68
68
f099b74dc04590ce7b559041d46616cba4f3f833
bigcode/the-stack
train
1df7221ab35dedcc47dfbaed
train
function
def paragraphs_as_tokens(paragraphs): tokens = [] for paragraph in paragraphs: sentences = nltk.tokenize.sent_tokenize(paragraph) for sentence in sentences: words = nltk.tokenize.word_tokenize(sentence) pos_tags = nltk.pos_tag(words) tokens.extend((clean_word(...
def paragraphs_as_tokens(paragraphs):
tokens = [] for paragraph in paragraphs: sentences = nltk.tokenize.sent_tokenize(paragraph) for sentence in sentences: words = nltk.tokenize.word_tokenize(sentence) pos_tags = nltk.pos_tag(words) tokens.extend((clean_word(word), pos_tag[1]) for word, pos_tag i...
, path)) return results else: paragraphs = process_individual_file(path) print('Loaded {} paragraphs from {}'.format(len(paragraphs), filename)) return paragraphs def clean_word(word): return word.strip().lower().replace('_', '') def paragraphs_as_tokens(paragraphs):
63
64
105
8
55
anishpdoshi/pos-weighted-text-generation
data.py
Python
paragraphs_as_tokens
paragraphs_as_tokens
55
66
55
55
43295fec0fa0797f25904936194e45c820fe6a03
bigcode/the-stack
train
2bbd08f0d1242e04e1f8a0cb
train
function
def clean_word(word): return word.strip().lower().replace('_', '')
def clean_word(word):
return word.strip().lower().replace('_', '')
1 print('Loaded {} paragraphs from {} files in {}'.format(len(results), num_files, path)) return results else: paragraphs = process_individual_file(path) print('Loaded {} paragraphs from {}'.format(len(paragraphs), filename)) return paragraphs def clean_word(word):
64
64
16
5
58
anishpdoshi/pos-weighted-text-generation
data.py
Python
clean_word
clean_word
52
53
52
52
f6892bdbbcfe1f60e26fe0e4f42d09cc3ba7b014
bigcode/the-stack
train
b6189d74824e08e78ad16849
train
function
def load_paragraphs(path, to_paragraphs=lambda content: content.split('\n')): def process_individual_file(filepath): with open(os.path.abspath(filepath, 'r')) as f: content = f.read() return to_paragraphs(content) if os.path.isdir(path): results = [] num_fil...
def load_paragraphs(path, to_paragraphs=lambda content: content.split('\n')):
def process_individual_file(filepath): with open(os.path.abspath(filepath, 'r')) as f: content = f.read() return to_paragraphs(content) if os.path.isdir(path): results = [] num_files = 0 for filepath in os.listdir(path): if os.path.isfile(file...
= os.path.join('./datasets', author) else: path = os.path.join('./datasets', author, work) return load_paragraphs(path, to_paragraphs=gut_to_paragraphs) def load_paragraphs(path, to_paragraphs=lambda content: content.split('\n')):
64
64
171
20
44
anishpdoshi/pos-weighted-text-generation
data.py
Python
load_paragraphs
load_paragraphs
29
49
29
30
2cf8076e27116c70ad1ac0227d400fa4bb6eb6fa
bigcode/the-stack
train
3c58724e0ddfc8bf18d679dc
train
function
def load_from_author(author, work=None): def gut_to_paragraphs(content): return list( map( lambda par: par.replace('\n', ' '), filter( # Remove empties lambda par: len(par) > 0, content.split('\n\n') ...
def load_from_author(author, work=None):
def gut_to_paragraphs(content): return list( map( lambda par: par.replace('\n', ' '), filter( # Remove empties lambda par: len(par) > 0, content.split('\n\n') ) ) ) ...
import os import nltk import collections import itertools from nltk import pos_tag from nltk.tokenize import sent_tokenize, word_tokenize EOS = '<EOS>' EOP = '<EOP>' def load_from_author(author, work=None):
52
64
123
9
43
anishpdoshi/pos-weighted-text-generation
data.py
Python
load_from_author
load_from_author
11
27
11
11
d39095d4713b330359a14a48f529539f70957e7c
bigcode/the-stack
train
a5082f87f75f02a3f70bc08a
train
function
def Multiplication(k): """ Generate a function that performs a polynomial multiplication and return coefficients up to degree k """ assert isinstance(k, int) and k > 0 def isum(factors): init = next(factors) return reduce(operator.iadd, factors, init) def mul_function(x1, x2): ...
def Multiplication(k):
""" Generate a function that performs a polynomial multiplication and return coefficients up to degree k """ assert isinstance(k, int) and k > 0 def isum(factors): init = next(factors) return reduce(operator.iadd, factors, init) def mul_function(x1, x2): # prepare indi...
import operator import itertools from future.builtins import range from functools import reduce from losses.logarithm import LogTensor def Multiplication(k):
33
78
261
5
27
liaopeiyuan/ml-arsenal-public
projects/Doodle/earhian/losses/polynomial/multiplication.py
Python
Multiplication
Multiplication
9
40
9
9
851bb72a2d4459568683de8e8331a37752d85b56
bigcode/the-stack
train
57f35d1ab7c34961f5463555
train
function
@log_on_start(DEBUG, "runConcurrently: Starting concurrent execution") @log_on_error(DEBUG, "runConcurrently: Encountered an error during concurrent execution") @log_on_end(DEBUG, "runConcurrently: Finished concurrent execution") def runConcurrently(producer_consumer_list): """ runConcurrently is aFunction that...
@log_on_start(DEBUG, "runConcurrently: Starting concurrent execution") @log_on_error(DEBUG, "runConcurrently: Encountered an error during concurrent execution") @log_on_end(DEBUG, "runConcurrently: Finished concurrent execution") def runConcurrently(producer_consumer_list):
""" runConcurrently is aFunction that uses a concurrent.futures ThreadPoolExecutor to concurrently execute a set of ConsumerProducer functions """ with concurrent.futures.ThreadPoolExecutor(max_workers=len(producer_consumer_list)) as executor: # Create a list to hold the executors created ...
Print the formatted output @log_on_start(DEBUG, "runConcurrently: Starting concurrent execution") @log_on_error(DEBUG, "runConcurrently: Encountered an error during concurrent execution") @log_on_end(DEBUG, "runConcurrently: Finished concurrent execution") def runConcurrently(producer_consumer_list):
64
64
198
59
4
rlhatton/RossROS
rossros.py
Python
runConcurrently
runConcurrently
325
345
325
328
38f10d3a6b67bc947fc07d2bc516cea218c97f53
bigcode/the-stack
train
2a1ddeb45d51d751cd017b82
train
class
class Consumer(ConsumerProducer): """ Special case of the consumer-producer class, that reads values from buses but does not send to them """ @log_on_start(DEBUG, "{name:s}: Starting to create consumer") @log_on_error(DEBUG, "{name:s}: Encountered an error while creating consumer") @log_on_...
class Consumer(ConsumerProducer):
""" Special case of the consumer-producer class, that reads values from buses but does not send to them """ @log_on_start(DEBUG, "{name:s}: Starting to create consumer") @log_on_error(DEBUG, "{name:s}: Encountered an error while creating consumer") @log_on_end(DEBUG, "{name:s}: Finished cre...
input values def consumer_producer_function(_input_value): return producer_function() # Call the parent class init function super().__init__( consumer_producer_function, input_buses, output_buses, delay, termination_buses, ...
64
64
213
6
58
rlhatton/RossROS
rossros.py
Python
Consumer
Consumer
208
237
208
208
2bd2c694c72bb4706c9a95c19994506da1ce9b80
bigcode/the-stack
train
84db598ce7b17051cfe4fb23
train
class
class Bus: """ Class for passing broadcast messages between processes. """ def __init__(self, initial_message=0, name="Unnamed Bus"): self.message = initial_message self.name = name # Set up the class so that functions can get a lock while wor...
class Bus:
""" Class for passing broadcast messages between processes. """ def __init__(self, initial_message=0, name="Unnamed Bus"): self.message = initial_message self.name = name # Set up the class so that functions can get a lock while working ...
concurrent.futures import time import logging from readerwriterlock import rwlock from logdecorator import log_on_start, log_on_end, log_on_error DEBUG = logging.DEBUG logging_format = "%(asctime)s: %(message)s" logging.basicConfig(format=logging_format, level=logging.INFO, datefmt="%H:%M:%S") cla...
77
77
257
3
74
rlhatton/RossROS
rossros.py
Python
Bus
Bus
14
45
14
14
31dde777df9f11d4bbcd48b6614150decb619429
bigcode/the-stack
train
e401a09d8287a34b0185427b
train
class
class Producer(ConsumerProducer): """ Special case of the consumer-producer class, that sends values to buses but does not read them """ @log_on_start(DEBUG, "{name:s}: Starting to create producer") @log_on_error(DEBUG, "{name:s}: Encountered an error while creating producer") @log_on_end(D...
class Producer(ConsumerProducer):
""" Special case of the consumer-producer class, that sends values to buses but does not read them """ @log_on_start(DEBUG, "{name:s}: Starting to create producer") @log_on_error(DEBUG, "{name:s}: Encountered an error while creating producer") @log_on_end(DEBUG, "{name:s}: Finished creating...
termination_bus_values = self.collectbusesToValues(self.termination_buses) # If any of the termination buses have triggered (gone true or non-negative), signal the loop to end for tbv in termination_bus_values: if tbv and tbv >= 0: return True class Producer(Consumer...
70
70
236
6
63
rlhatton/RossROS
rossros.py
Python
Producer
Producer
174
205
174
174
ccf024e2d78f91aaaf7df16c2072756cfbd70b8a
bigcode/the-stack
train
1fdba2f08f6c3350a52506ab
train
class
class Timer(Producer): """ Timer is a producer that keeps track of time since it was instantiated Time is instantiated with a duration value, and writes a "countdown" value (time before or after the specified duration) to its output bus. The output bus can be used as the termination bus for other co...
class Timer(Producer):
""" Timer is a producer that keeps track of time since it was instantiated Time is instantiated with a duration value, and writes a "countdown" value (time before or after the specified duration) to its output bus. The output bus can be used as the termination bus for other consumer-producers (and f...
_buses, delay=0, termination_buses=Bus(False, "Default consumer termination bus"), name="Unnamed consumer"): # Match naming convention for this class with its parent class consumer_producer_function = consumer_function # Consumers don't use an...
121
121
404
5
116
rlhatton/RossROS
rossros.py
Python
Timer
Timer
240
279
240
240
25efba5d6c3355ef812d80837bbf5d538faa2be3
bigcode/the-stack
train
8a8846288e0e9da61d35170f
train
function
def ensureTuple(value): """ Function that wraps an input value in a tuple if it is not already a tuple """ if isinstance(value, tuple): value_tuple = value else: value_tuple = (value,) # comma creates the tuple return value_tuple
def ensureTuple(value):
""" Function that wraps an input value in a tuple if it is not already a tuple """ if isinstance(value, tuple): value_tuple = value else: value_tuple = (value,) # comma creates the tuple return value_tuple
:s}: Error on write by {_name:s}") @log_on_end(DEBUG, "{self.name:s}: Finished write by {_name:s}") def set_message(self, message, _name='Unspecified function'): with self.lock.gen_wlock(): self.message = message def ensureTuple(value):
64
64
63
5
58
rlhatton/RossROS
rossros.py
Python
ensureTuple
ensureTuple
48
58
48
48
40c43df9a60c99020eae4eba2759e373afcd2a20
bigcode/the-stack
train
196d013e782af1cabfc20572
train
class
class ConsumerProducer: """ Class that turns a provided function into a service that reads from the input buses, stores the resulting data into the output buses, and watches a set of termination buses for a "True" or non-negative signal, at which point the service shuts down """ @log_on_sta...
class ConsumerProducer:
""" Class that turns a provided function into a service that reads from the input buses, stores the resulting data into the output buses, and watches a set of termination buses for a "True" or non-negative signal, at which point the service shuts down """ @log_on_start(DEBUG, "{name:s}: Sta...
= rwlock.RWLockFairD() @log_on_start(DEBUG, "{self.name:s}: Initiating read by {_name:s}") @log_on_error(DEBUG, "{self.name:s}: Error on read by {_name:s}") @log_on_end(DEBUG, "{self.name:s}: Finished read by {_name:s}") def get_message(self, _name='Unspecified function'): with self.lock.gen_...
256
256
1,026
4
251
rlhatton/RossROS
rossros.py
Python
ConsumerProducer
ConsumerProducer
61
171
61
61
0f38584caf0924a6356c4dab78458d512b52be8c
bigcode/the-stack
train
83ad133b121890000f9ece21
train
class
class Printer(Consumer): """ Printer is a consumer that reads a value stored in a bus and prints it out at specified intervals """ @log_on_start(DEBUG, "{name:s}: Starting to create printer") @log_on_error(DEBUG, "{name:s}: Encountered an error while creating printer") @log_on_end(DEBUG, "{name...
class Printer(Consumer):
""" Printer is a consumer that reads a value stored in a bus and prints it out at specified intervals """ @log_on_start(DEBUG, "{name:s}: Starting to create printer") @log_on_error(DEBUG, "{name:s}: Encountered an error while creating printer") @log_on_end(DEBUG, "{name:s}: Finished creating pr...
.name:s}: Checking current time against starting time") @log_on_error(DEBUG, "{self.name:s}: Encountered an error while checking current time against starting time") @log_on_end(DEBUG, "{self.name:s}: Finished checking current time against starting time") def timer(self): # Trigger the timer if the...
129
129
433
5
123
rlhatton/RossROS
rossros.py
Python
Printer
Printer
282
322
282
282
9c2c80a4cca7e0900b6b3e2fc6457119feb36fd2
bigcode/the-stack
train
beaf7499fc008f5a4b74697c
train
function
def run_gphh_with_settings(): domain: RCPSP = load_domain(get_complete_path("j301_1.sm")) training_domains = [load_domain(get_complete_path("j301_2.sm")), load_domain(get_complete_path("j301_3.sm")), load_domain(get_complete_path("j301_4.sm")), ...
def run_gphh_with_settings():
domain: RCPSP = load_domain(get_complete_path("j301_1.sm")) training_domains = [load_domain(get_complete_path("j301_2.sm")), load_domain(get_complete_path("j301_3.sm")), load_domain(get_complete_path("j301_4.sm")), load_domain(get_complete_...
=func_heuristics, features=list(solver.params_gphh.set_feature), params_gphh=solver.params_gphh, pool_aggregation_method=PoolAggregationMethod.MEAN, ...
165
165
552
8
157
POPOGO/scikit-decide
examples/scheduling/gphh_example.py
Python
run_gphh_with_settings
run_gphh_with_settings
265
325
265
266
1fad01d487bf87add575b870f28c16f1c4126686
bigcode/the-stack
train
82976988e1d92e3677ab6874
train
function
def fitness_makespan_correlation(): # domain: RCPSP = load_domain("j301_1.sm") domain: RCPSP = load_domain(file_path=get_complete_path("j1201_9.sm")) training_domains_names = ["j301_"+str(i)+".sm" for i in range(1, 11)] # training_domains_names =["j1201_9.sm"] # evaluation=EvaluationGPHH.PERMUTATI...
def fitness_makespan_correlation(): # domain: RCPSP = load_domain("j301_1.sm")
domain: RCPSP = load_domain(file_path=get_complete_path("j1201_9.sm")) training_domains_names = ["j301_"+str(i)+".sm" for i in range(1, 11)] # training_domains_names =["j1201_9.sm"] # evaluation=EvaluationGPHH.PERMUTATION_DISTANCE # evaluation = EvaluationGPHH.SGS evaluation = EvaluationGPHH.S...
from skdecide import rollout_episode from skdecide.hub.domain.rcpsp.rcpsp_sk_parser import load_domain from skdecide.hub.domain.rcpsp.rcpsp_sk import RCPSP from skdecide.hub.solver.do_solver.do_solver_scheduling import DOSolver, SolvingMethod from skdecide.hub.solver.sgs_policies.sgs_policies import PolicyMethodParams,...
251
256
961
25
225
POPOGO/scikit-decide
examples/scheduling/gphh_example.py
Python
fitness_makespan_correlation
fitness_makespan_correlation
18
123
18
19
5dba5a00f3a3e24c4c3d6ccaee8eb4d9a6b00cac
bigcode/the-stack
train
3f8ef0abf1e5e56da713c2c4
train
function
def compare_settings(): test_domain_names = ["j1201_1.sm"] training_domains_names = ["j301_" + str(i) + ".sm" for i in range(2, 11)] domains_loaded = [] for td in training_domains_names: domains_loaded.append(load_domain(get_complete_path(td))) n_walks = 5 all_settings = [] param...
def compare_settings():
test_domain_names = ["j1201_1.sm"] training_domains_names = ["j301_" + str(i) + ".sm" for i in range(2, 11)] domains_loaded = [] for td in training_domains_names: domains_loaded.append(load_domain(get_complete_path(td))) n_walks = 5 all_settings = [] params1 = ParametersGPHH.defa...
=0.25, pop_size=20, n_gen=20, min_tree_depth=1, max_tree_depth=5, crossover_rate=0.7, mutation_rate=0.1, base_...
201
202
674
4
197
POPOGO/scikit-decide
examples/scheduling/gphh_example.py
Python
compare_settings
compare_settings
328
405
328
328
9b98f6d8ed65af1e83d263687d252474c68979d8
bigcode/the-stack
train
6da098a05c432c65ea48655e
train
function
def run_features(): domain: RCPSP = load_domain(get_complete_path("j301_1.sm")) task_id = 2 total_nres = feature_total_n_res(domain, task_id) print('total_nres: ', total_nres) duration = feature_task_duration(domain, task_id) print('duration: ', duration) n_successors = feature_n_successors(...
def run_features():
domain: RCPSP = load_domain(get_complete_path("j301_1.sm")) task_id = 2 total_nres = feature_total_n_res(domain, task_id) print('total_nres: ', total_nres) duration = feature_task_duration(domain, task_id) print('duration: ', duration) n_successors = feature_n_successors(domain, task_id) ...
') for param_key in all_results[test_domain_str].keys(): print('\t', param_key, ': ') print('\t\t all runs:', all_results[test_domain_str][param_key]) print('\t\t mean:', np.mean(all_results[test_domain_str][param_key])) def run_features():
63
64
161
4
59
POPOGO/scikit-decide
examples/scheduling/gphh_example.py
Python
run_features
run_features
408
420
408
408
488ecb66954e22dd4af7fbdc2ef772720efe8112
bigcode/the-stack
train
cacfdd2e355915bd91cb3c18
train
function
def run_gphh(): import time n_runs = 1 makespans = [] domain: RCPSP = load_domain(file_path=get_complete_path("j601_1.sm")) training_domains_names = ["j601_"+str(i)+".sm" for i in range(1, 11)] training_domains = [] for td in training_domains_names: training_domains.append(load_d...
def run_gphh():
import time n_runs = 1 makespans = [] domain: RCPSP = load_domain(file_path=get_complete_path("j601_1.sm")) training_domains_names = ["j601_"+str(i)+".sm" for i in range(1, 11)] training_domains = [] for td in training_domains_names: training_domains.append(load_domain(file_path=g...
_inplace_environment(False) state = domain.get_initial_state() states, actions, values = rollout_episode(domain=domain, max_steps=1000, solver=gphh_policy, ...
155
155
518
6
149
POPOGO/scikit-decide
examples/scheduling/gphh_example.py
Python
run_gphh
run_gphh
126
187
126
127
8c7ba86ae4edc1bbce1729c3d5f50746708cd1fa
bigcode/the-stack
train
ca286807e0dabc281bb78369
train
function
def run_pooled_gphh(): n_runs = 1 pool_size = 5 remove_extreme_values = 1 makespans = [] domain: RCPSP = load_domain(file_path=get_complete_path("j1201_9.sm")) # domain: RCPSP = load_domain("j1201_9.sm") training_domains_names = ["j301_"+str(i)+".sm" for i in range(1, 11)] training_...
def run_pooled_gphh():
n_runs = 1 pool_size = 5 remove_extreme_values = 1 makespans = [] domain: RCPSP = load_domain(file_path=get_complete_path("j1201_9.sm")) # domain: RCPSP = load_domain("j1201_9.sm") training_domains_names = ["j301_"+str(i)+".sm" for i in range(1, 11)] training_domains = [] for td ...
(folder) file = open(os.path.join(folder, 'test_gphh_'+str(i)+'.pkl'), 'wb') pickle.dump(dict(hof=heuristic), file) file.close() solver.set_domain(domain) states, actions, values = rollout_episode(domain=domain, max_steps=1000, ...
180
180
601
8
172
POPOGO/scikit-decide
examples/scheduling/gphh_example.py
Python
run_pooled_gphh
run_pooled_gphh
190
262
190
191
642236cf4bcb32dbce0e44adedf5bc11e314f60b
bigcode/the-stack
train
b1e431299eb532b8a1c840b0
train
function
def run_comparaison(): from examples.discrete_optimization.rcpsp_parser_example import \ get_data_available import os files = get_data_available() all_single_mode = [os.path.basename(f) for f in files if "sm" in f] # training_cphh = ["j1201_"+str(i)+".sm" for i in ran...
def run_comparaison():
from examples.discrete_optimization.rcpsp_parser_example import \ get_data_available import os files = get_data_available() all_single_mode = [os.path.basename(f) for f in files if "sm" in f] # training_cphh = ["j1201_"+str(i)+".sm" for i in range(2, 11)] training...
) ) solver.solve(domain_factory=lambda: domain) domain: RCPSP = test_domain domain.set_inplace_environment(False) state = domain.get_initial_state() solver.set_domain(domain) states, actions, values = rollout_episode(doma...
255
256
2,041
6
249
POPOGO/scikit-decide
examples/scheduling/gphh_example.py
Python
run_comparaison
run_comparaison
625
840
625
625
03a55a1e7b5cf5bb4ccccee57a88b60840259bbc
bigcode/the-stack
train
b0388f0af4ad75fb57ed0fe3
train
function
def compute_ref_permutations(): import os files = get_data_available() all_single_mode = [os.path.basename(f) for f in files if "sm" in f] all_permutations = {} all_makespans = {} for td_name in all_single_mode: td = load_domain(get_complete_path(td_name)) ...
def compute_ref_permutations():
import os files = get_data_available() all_single_mode = [os.path.basename(f) for f in files if "sm" in f] all_permutations = {} all_makespans = {} for td_name in all_single_mode: td = load_domain(get_complete_path(td_name)) td.set_inplace_environment(Fals...
_costs)) # print('CP: ', cp_cost) # print('GPHH: ', gphh_costs) # print('GPHH (mean): ', np.mean(gphh_costs)) # import json # import time # from datetime import datetime # all_results["params"] = {"features": [str(k.value) for k in set_feature]} # json.dump(all_results, open("training_on...
124
124
414
7
117
POPOGO/scikit-decide
examples/scheduling/gphh_example.py
Python
compute_ref_permutations
compute_ref_permutations
854
894
854
854
565a3708e881514dd14c9335c2b7f4cf5930019c
bigcode/the-stack
train
4bedc3281cac8a8740261bbf
train
function
def run_comparaison_stochastic(): import random from skdecide.hub.domain.rcpsp.rcpsp_sk import RCPSP, build_stochastic_from_deterministic, build_n_determinist_from_stochastic repeat_runs = 5 test_domain_names = ["j301_1.sm", "j301_2.sm", "j301_3.sm", "j601_1.sm", "j601_2.sm", ...
def run_comparaison_stochastic():
import random from skdecide.hub.domain.rcpsp.rcpsp_sk import RCPSP, build_stochastic_from_deterministic, build_n_determinist_from_stochastic repeat_runs = 5 test_domain_names = ["j301_1.sm", "j301_2.sm", "j301_3.sm", "j601_1.sm", "j601_2.sm", "j601_3.sm"] all_results = {}...
])) print('##### ALL RESULTS #####') for test_domain_str in test_domain_names: print(test_domain_str, ' :') for param_key in all_results[test_domain_str].keys(): print('\t', param_key, ': ') print('\t\t all runs:', all_results[test_domain_str][param_key]) pr...
256
256
1,843
8
248
POPOGO/scikit-decide
examples/scheduling/gphh_example.py
Python
run_comparaison_stochastic
run_comparaison_stochastic
423
622
423
423
42c4ded46ce7b81bb57725c79a918ac14b1c0171
bigcode/the-stack
train
e557b2729c2592014e130ad2
train
class
class CategoricalLogisticRegressionTest(unittest.TestCase): """ Unit test class for testing logistic regression with a categorical feature. """ @classmethod def setUpClass(self): """ Set up (run once). """ ## Create fake data with a categorical variable np.r...
class CategoricalLogisticRegressionTest(unittest.TestCase):
""" Unit test class for testing logistic regression with a categorical feature. """ @classmethod def setUpClass(self): """ Set up (run once). """ ## Create fake data with a categorical variable np.random.seed(15) n, d = 100, 3 self.sf = tc.SF...
"value values are incorrect. {} vs {}".format(self.coef, coef_list)) def _test_create(self, sf, target, features, solver, kwargs, rescaling): """ Test logistic regression create function for a particular set of inputs. """ test_label = "solver: {}\tkwargs: {}".format(solver, kwarg...
256
256
1,163
11
245
karthikdash/turicreate
src/unity/python/turicreate/test/test_logistic_classifier.py
Python
CategoricalLogisticRegressionTest
CategoricalLogisticRegressionTest
763
906
763
763
2fcd7fb375a6f102d36fb0ea3fba23ed67d1b7b2
bigcode/the-stack
train
62c5d941ed005f78e21a86a2
train
function
def binary_classification_integer_target(cls): """ The setup class method for a binary classification problem with the target being binary. """ ## Simulate test data np.random.seed(8) n, d = 100, 10 cls.sf = tc.SFrame() for i in range(d): cls.sf.add_column(tc.SArray(np.rando...
def binary_classification_integer_target(cls):
""" The setup class method for a binary classification problem with the target being binary. """ ## Simulate test data np.random.seed(8) n, d = 100, 10 cls.sf = tc.SFrame() for i in range(d): cls.sf.add_column(tc.SArray(np.random.rand(n)), inplace=True) target = np.rando...
# -*- coding: utf-8 -*- # Copyright © 2017 Apple Inc. All rights reserved. # # Use of this source code is governed by a BSD-3-clause license that can # be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause from __future__ import print_function as _ from __future__ import division as _ from...
205
256
1,362
8
197
karthikdash/turicreate
src/unity/python/turicreate/test/test_logistic_classifier.py
Python
binary_classification_integer_target
binary_classification_integer_target
29
149
29
29
3ed98327ba7892aa34469e419dd0cba2d2e0141b
bigcode/the-stack
train
84f99c884dd703da342bb3c3
train
function
def multiclass_integer_target(cls): """ The setup class method for multi-class classification problem with the target being integer. """ binary_classification_integer_target(cls) np.random.seed(8) n, d = 100, 10 cls.sf = tc.SFrame() for i in range(d): cls.sf.add_column(tc.SA...
def multiclass_integer_target(cls):
""" The setup class method for multi-class classification problem with the target being integer. """ binary_classification_integer_target(cls) np.random.seed(8) n, d = 100, 10 cls.sf = tc.SFrame() for i in range(d): cls.sf.add_column(tc.SArray(np.random.rand(n)), inplace=Tru...
x: x == 11, 'num_examples': lambda x: x == 100, 'class_weights': lambda x: x == {0:1, 1:1}, 'num_examples_per_class': \ lambda x: {0: cls.sf.num_rows() - cls.sf['target'].sum(), 1: cls.sf['target'].sum()}, 'num_unpacked_features': lambda x: x =...
256
256
1,105
7
249
karthikdash/turicreate
src/unity/python/turicreate/test/test_logistic_classifier.py
Python
multiclass_integer_target
multiclass_integer_target
151
256
151
151
3e2c7450418857363002135517ca8c0d532eeb0a
bigcode/the-stack
train
032b4bc6c678578a33a44e2f
train
class
class VectorLogisticRegressionTest(unittest.TestCase): """ Unit test class for testing a Logistic Regression create function. """ @classmethod def setUpClass(self): """ Set up (Run only once) """ np.random.seed(15) n, d = 100, 3 self.sf = tc.SFrame() for i in range(d): ...
class VectorLogisticRegressionTest(unittest.TestCase):
""" Unit test class for testing a Logistic Regression create function. """ @classmethod def setUpClass(self): """ Set up (Run only once) """ np.random.seed(15) n, d = 100, 3 self.sf = tc.SFrame() for i in range(d): self.sf.add_column(tc.SArray(np.random.rand(n)), inp...
.sf[:] sf['error-column'] = '1' model = tc.logistic_classifier.create(sf, self.target) sf['error-column'] = [[1] for i in sf] model = tc.logistic_classifier.create(sf, self.target) sf['error-column'] = [{1:1} for i in sf] model = tc.logistic_classifier.create(sf, self.t...
237
237
791
10
226
karthikdash/turicreate
src/unity/python/turicreate/test/test_logistic_classifier.py
Python
VectorLogisticRegressionTest
VectorLogisticRegressionTest
908
992
908
908
109f808f6f45c958d095e01367edee07f0d5e05e
bigcode/the-stack
train
31d30e1416cab1a0f2ef26dd
train
class
class ListCategoricalLogisticRegressionTest(unittest.TestCase): """ Unit test class for testing logistic regression with a categorical feature. """ @classmethod def setUpClass(self): """ Set up (run once). """ ## Create fake data with a categorical variable ...
class ListCategoricalLogisticRegressionTest(unittest.TestCase):
""" Unit test class for testing logistic regression with a categorical feature. """ @classmethod def setUpClass(self): """ Set up (run once). """ ## Create fake data with a categorical variable np.random.seed(15) n, d = 100, 3 self.sf = tc.SF...
model = tc.logistic_classifier.create(self.sf, self.target, self.features, class_weights = 1.0) except ToolkitError: pass try: model = tc.logistic_classifier.create(self.sf, self.target, self.features, ...
229
229
766
12
217
karthikdash/turicreate
src/unity/python/turicreate/test/test_logistic_classifier.py
Python
ListCategoricalLogisticRegressionTest
ListCategoricalLogisticRegressionTest
671
760
671
671
9b160e6aa720eb84a25087b749e8c24b76527fd9
bigcode/the-stack
train
9853caadabb8735d53460ac1
train
class
class LogisticRegressionCreateTest(unittest.TestCase): """ Unit test class for testing a Logistic Regression model that is not trained. """ @classmethod def setUpClass(self): """ Setup required for all tests that don't require an trained model. """ np.random.seed(8)...
class LogisticRegressionCreateTest(unittest.TestCase):
""" Unit test class for testing a Logistic Regression model that is not trained. """ @classmethod def setUpClass(self): """ Setup required for all tests that don't require an trained model. """ np.random.seed(8) n, d = 100, 10 self.sf = tc.SFrame() ...
s = (%s,%s)" % \ (metric, ans[metric], self.sm_metrics[metric])) # Default ans = model.evaluate(self.sf) self.assertEqual(sorted(ans.keys()), sorted(self.metrics)) for m in self.metrics: check_metric(ans, m) # Individual for m in...
256
256
1,046
9
247
karthikdash/turicreate
src/unity/python/turicreate/test/test_logistic_classifier.py
Python
LogisticRegressionCreateTest
LogisticRegressionCreateTest
542
669
542
542
27d24a126dd057d119e11e4e5bd846c13f53d83b
bigcode/the-stack
train
d9e8bbc98b4e14fbbf6eaaef
train
class
class DictLogisticRegressionTest(unittest.TestCase): """ Unit test class for testing a Logistic Regression create function. """ @classmethod def setUpClass(self): """ Set up (Run only once) """ np.random.seed(15) n, d = 100, 3 self.sf = tc.SFrame() # float columns for ...
class DictLogisticRegressionTest(unittest.TestCase):
""" Unit test class for testing a Logistic Regression create function. """ @classmethod def setUpClass(self): """ Set up (Run only once) """ np.random.seed(15) n, d = 100, 3 self.sf = tc.SFrame() # float columns for i in range(d): self.sf.add_column(tc.SArray(n...
kwargs) test_case = 'solver = {solver}, kwargs = {kwargs}'.format(solver = solver, kwargs = kwargs) self.assertTrue(model is not None) self.assertTrue(abs(model.training_loss - self.loss) < \ 0.01 * abs(self.loss),\ 'Loss fai...
256
256
1,057
10
246
karthikdash/turicreate
src/unity/python/turicreate/test/test_logistic_classifier.py
Python
DictLogisticRegressionTest
DictLogisticRegressionTest
995
1,100
995
995
7242a931d5633b94ac9cc79170e04fdbcca1c3cc
bigcode/the-stack
train
3e479eda3d516e9c09305804
train
class
class ValidationSetLogisticClassifierTest(unittest.TestCase): @classmethod def setUpClass(self): ## Simulate test data np.random.seed(10) n, d = 100, 10 self.sf = tc.SFrame() for i in range(d): self.sf.add_column(tc.SArray(np.random.randn(n)), inplace=True) ...
class ValidationSetLogisticClassifierTest(unittest.TestCase): @classmethod
def setUpClass(self): ## Simulate test data np.random.seed(10) n, d = 100, 10 self.sf = tc.SFrame() for i in range(d): self.sf.add_column(tc.SArray(np.random.randn(n)), inplace=True) target = np.random.randint(2, size=n) target[0] = 0 target[...
.SArray([[1,2],[3,4],[5,6]], array.array) self.sf['str'] = tc.SArray(['1','2','3'], str) print(self.sf) """ Test predict missing value """ def test_single_label_error(self): sf = self.sf.__copy__() sf['y'] = tc.SArray.from_const(0, 3) with self.assertRaises(ToolkitError): m = tc....
123
123
410
15
108
karthikdash/turicreate
src/unity/python/turicreate/test/test_logistic_classifier.py
Python
ValidationSetLogisticClassifierTest
ValidationSetLogisticClassifierTest
1,340
1,388
1,340
1,341
6dce13f3e6d9e4c926d4e21bce41b1ed310590ad
bigcode/the-stack
train
739725d30d7202363e2ef2e1
train
class
class TestStringTarget(unittest.TestCase): def test_cat(self): import numpy as np # Arrange np.random.seed(8) n, d = 1000, 100 sf = tc.SFrame() for i in range(d): sf.add_column(tc.SArray(np.random.rand(n)), inplace=True) target = np.ra...
class TestStringTarget(unittest.TestCase):
def test_cat(self): import numpy as np # Arrange np.random.seed(8) n, d = 1000, 100 sf = tc.SFrame() for i in range(d): sf.add_column(tc.SArray(np.random.rand(n)), inplace=True) target = np.random.randint(2, size=n) sf['...
with self.assertRaises(RuntimeError): validation_set = self.sf.__copy__() validation_set['X1'] = validation_set['X1'].astype(str) model = tc.logistic_classifier.create(self.sf, target='target', validation_set = validation_set) class TestStringTarget(unittest.T...
64
64
176
8
56
karthikdash/turicreate
src/unity/python/turicreate/test/test_logistic_classifier.py
Python
TestStringTarget
TestStringTarget
1,390
1,412
1,390
1,391
fff4fb23432777ba7ff116a27dde7189f6bdb0d2
bigcode/the-stack
train
c70f67c125d0b67018cf8af2
train
function
def binary_classification_string_target(cls): """ The setup class method for a binary classification problem with the target being binary. """ binary_classification_integer_target(cls) cls.sf['target'] = cls.sf['target'].astype(str) cls.model = tc.logistic_classifier.create(cls.sf, target=...
def binary_classification_string_target(cls):
""" The setup class method for a binary classification problem with the target being binary. """ binary_classification_integer_target(cls) cls.sf['target'] = cls.sf['target'].astype(str) cls.model = tc.logistic_classifier.create(cls.sf, target='target', ...
: (cls.sf['target'] == 0).sum(), 1: (cls.sf['target'] == 1).sum(), 2: (cls.sf['target'] == 2).sum()} cls.fields_ans = cls.get_ans.keys() def binary_classification_string_target(cls):
64
64
198
8
56
karthikdash/turicreate
src/unity/python/turicreate/test/test_logistic_classifier.py
Python
binary_classification_string_target
binary_classification_string_target
258
279
258
258
4a54a833d266647169721d7214ddb2d5ab772064
bigcode/the-stack
train
30a45407f108c25bbb58c2c0
train
function
def test_suite(): """ Create a test suite for each test case in LogisticRegressionClassifierModelTest """ testCases = [binary_classification_integer_target, binary_classification_string_target, multiclass_integer_target] #multiclass_string_target] ...
def test_suite():
""" Create a test suite for each test case in LogisticRegressionClassifierModelTest """ testCases = [binary_classification_integer_target, binary_classification_string_target, multiclass_integer_target] #multiclass_string_target] for t in testCases...
: x == { "0": (cls.sf["target"] == "0").sum(), "1": (cls.sf["target"] == "1").sum(), "2": (cls.sf["target"] == "2").sum(), } cls.type = str def test_suite():
64
64
210
4
59
karthikdash/turicreate
src/unity/python/turicreate/test/test_logistic_classifier.py
Python
test_suite
test_suite
307
333
307
307
df4c96b43fcff0b7e563d67d5995d527439a5a80
bigcode/the-stack
train
11f4058f2015fe245c8a175f
train
function
def multiclass_string_target(cls): """ The setup class method for a binary classification problem with the target being binary. """ multiclass_integer_target(cls) cls.sf['target'] = cls.sf['target'].astype(str) cls.model = tc.logistic_classifier.create(cls.sf, target='target', ...
def multiclass_string_target(cls):
""" The setup class method for a binary classification problem with the target being binary. """ multiclass_integer_target(cls) cls.sf['target'] = cls.sf['target'].astype(str) cls.model = tc.logistic_classifier.create(cls.sf, target='target', ...
":1} cls.get_ans["num_examples_per_class"] = lambda x: x == { "0": (cls.sf["target"] == "0").sum(), "1": (cls.sf["target"] == "1").sum()} cls.type = str def multiclass_string_target(cls):
66
66
221
7
58
karthikdash/turicreate
src/unity/python/turicreate/test/test_logistic_classifier.py
Python
multiclass_string_target
multiclass_string_target
282
305
282
282
104e927df9f8f8bef3b81382e8c60ecaa9d26256
bigcode/the-stack
train
99a26b95375ea0f5ce91a4b6
train
class
class ImproperProblemsTest(unittest.TestCase): """ Unit test class for problems with the setup, e.g. dataset. """ @classmethod def setUpClass(self): """ Set up (Run only once) """ self.target = 'y' self.sf = tc.SFrame() self.sf['y'] = tc.SArray([0,1,0], int) self.sf['int']...
class ImproperProblemsTest(unittest.TestCase):
""" Unit test class for problems with the setup, e.g. dataset. """ @classmethod def setUpClass(self): """ Set up (Run only once) """ self.target = 'y' self.sf = tc.SFrame() self.sf['y'] = tc.SArray([0,1,0], int) self.sf['int'] = tc.SArray([1,2,3], int) self.sf['float']...
s', 'fista']: self._test_l2_create(self.sf, self.target, self.features, solver, self.def_kwargs, self.l2_penalty) for solver in ['fista']: self._test_l1_create(self.sf, self.target, self.features, solver, self.def_kwargs, self.l...
81
81
270
9
72
karthikdash/turicreate
src/unity/python/turicreate/test/test_logistic_classifier.py
Python
ImproperProblemsTest
ImproperProblemsTest
1,309
1,337
1,309
1,309
21d1d9c8008fa7bd921c3851beba798221fda286
bigcode/the-stack
train
5a5672a8600ba37aa6d81358
train
class
class LogisticRegressionClassifierModelTest(unittest.TestCase): __test__ = False """ Unit test class for a LogisticRegressionModel that has already been created. """ def test__list_fields(self): """ Check the list fields function. """ model = self.model field...
class LogisticRegressionClassifierModelTest(unittest.TestCase):
__test__ = False """ Unit test class for a LogisticRegressionModel that has already been created. """ def test__list_fields(self): """ Check the list fields function. """ model = self.model fields = model._list_fields() self.assertEqual(set(fields), s...
(cls.sf["target"] == "1").sum(), "2": (cls.sf["target"] == "2").sum(), } cls.type = str def test_suite(): """ Create a test suite for each test case in LogisticRegressionClassifierModelTest """ testCases = [binary_classification_integer_target, binary_class...
256
256
1,652
10
246
karthikdash/turicreate
src/unity/python/turicreate/test/test_logistic_classifier.py
Python
LogisticRegressionClassifierModelTest
LogisticRegressionClassifierModelTest
335
539
335
335
e5ba6b2e74856c09393fe120bb5582567d61d5ac
bigcode/the-stack
train
4ad880be163d1ddaa8626258
train
class
class RegularizedLogisticRegressionTest(unittest.TestCase): """ Unit test class for testing l2 regularization with logistic regression. """ @classmethod def tearDownClass(self): os.remove(self.dataset) @classmethod def setUpClass(self): """ Set up (run only once). ...
class RegularizedLogisticRegressionTest(unittest.TestCase):
""" Unit test class for testing l2 regularization with logistic regression. """ @classmethod def tearDownClass(self): os.remove(self.dataset) @classmethod def setUpClass(self): """ Set up (run only once). """ ## Fake data, generated in R fea...
apply(lambda x: dict(list(x.items()) + list({'extra_col': 0, 'extra_col_2': 1}.items()))) pred2 = model.predict(self.sf) self.assertEqual(sum(pred - pred2), 0) self.sf['dict'] = self.sf['dict'].apply(lambda x: {k:v for k,v in x.items() \ if k not in ['extra_col', 'extra...
256
256
4,609
11
245
karthikdash/turicreate
src/unity/python/turicreate/test/test_logistic_classifier.py
Python
RegularizedLogisticRegressionTest
RegularizedLogisticRegressionTest
1,102
1,307
1,102
1,102
50ebe1157165a483b5e0ff28d0f9774d0ec2077b
bigcode/the-stack
train
bb758c9f3f570793aa6f2278
train
function
def ScalarShape(): return ops.convert_to_tensor([], dtype=dtypes.int32)
def ScalarShape():
return ops.convert_to_tensor([], dtype=dtypes.int32)
def F(): x, y = importer.import_graph_def( graph_def, return_elements=["Const:0", "while:2"]) grad_out, = gradients_impl.gradients(y, x) return grad_out self.assertAllEqual(F(), 8.0) def ScalarShape():
64
64
17
4
60
Mycaster/tensorflow
tensorflow/python/kernel_tests/while_v2_test.py
Python
ScalarShape
ScalarShape
1,834
1,835
1,834
1,834
8cf92d6b44009fa7f1fec553cd9a8cffe107b0ee
bigcode/the-stack
train
7089271015c86ad3e1d4213e
train
function
def random_gamma(shape): # pylint: disable=invalid-name return random_ops.random_gamma(shape, 1.0)
def random_gamma(shape): # pylint: disable=invalid-name
return random_ops.random_gamma(shape, 1.0)
_ops from tensorflow.python.ops import random_ops from tensorflow.python.ops import variables from tensorflow.python.ops import while_v2 from tensorflow.python.ops.while_v2 import while_loop as while_loop_v2 from tensorflow.python.platform import test def random_gamma(shape): # pylint: disable=invalid-name
64
64
27
14
49
Mycaster/tensorflow
tensorflow/python/kernel_tests/while_v2_test.py
Python
random_gamma
random_gamma
56
57
56
56
5ad4dfe21d67c89ef2482480c1ec5524c4e12e63
bigcode/the-stack
train
8406771dd49a3207e9ae4e85
train
class
class WhileV2Test(test.TestCase, parameterized.TestCase): @test_util.run_deprecated_v1 def testSingleLoopVar(self): x = constant_op.constant(2.) ret = while_loop_v2( lambda v: v < 8., lambda v: v * v, [x], return_same_structure=False) grad = gradients_impl.gradients(ret, [x]) with self.cach...
class WhileV2Test(test.TestCase, parameterized.TestCase): @test_util.run_deprecated_v1
def testSingleLoopVar(self): x = constant_op.constant(2.) ret = while_loop_v2( lambda v: v < 8., lambda v: v * v, [x], return_same_structure=False) grad = gradients_impl.gradients(ret, [x]) with self.cached_session(): self.assertEqual(self.evaluate(ret), 16.) self.assertSequenceEqu...
.ops import math_ops from tensorflow.python.ops import random_ops from tensorflow.python.ops import variables from tensorflow.python.ops import while_v2 from tensorflow.python.ops.while_v2 import while_loop as while_loop_v2 from tensorflow.python.platform import test def random_gamma(shape): # pylint: disable=invali...
256
256
13,658
24
232
Mycaster/tensorflow
tensorflow/python/kernel_tests/while_v2_test.py
Python
WhileV2Test
WhileV2Test
77
1,831
77
79
b471835774d599e035ea9d441fcf981f75b317bd
bigcode/the-stack
train
6c193e0739a16b32da89b16a
train
function
def random_poisson_v2(shape): # pylint: disable=invalid-name return random_ops.random_poisson_v2(shape, 1.0)
def random_poisson_v2(shape): # pylint: disable=invalid-name
return random_ops.random_poisson_v2(shape, 1.0)
(shape): # pylint: disable=invalid-name return random_ops.random_gamma( shape, alpha=[[1.], [3.], [5.], [6.]], beta=[[3., 4.]]) def random_poisson_v2(shape): # pylint: disable=invalid-name
63
64
33
17
46
Mycaster/tensorflow
tensorflow/python/kernel_tests/while_v2_test.py
Python
random_poisson_v2
random_poisson_v2
65
66
65
65
c6ef0fc4ec28451b5c74a1dbe97b5a2378a42900
bigcode/the-stack
train
64e67080b9737a8b519a736b
train
function
def fill(shape): # pylint: disable=invalid-name return array_ops.fill(shape, 1.0)
def fill(shape): # pylint: disable=invalid-name
return array_ops.fill(shape, 1.0)
isson_v2(shape, 1.0) def random_poisson_v2_with_lam(shape): # pylint: disable=invalid-name return random_ops.random_poisson_v2(shape, [12.2, 3.3]) def fill(shape): # pylint: disable=invalid-name
64
64
25
13
51
Mycaster/tensorflow
tensorflow/python/kernel_tests/while_v2_test.py
Python
fill
fill
73
74
73
73
affe593cf2c24240579c09dfc2dbc26b98c37ea8
bigcode/the-stack
train
26fe227a9c4f469d2c93b815
train
function
def random_gamma_with_alpha_beta(shape): # pylint: disable=invalid-name return random_ops.random_gamma( shape, alpha=[[1.], [3.], [5.], [6.]], beta=[[3., 4.]])
def random_gamma_with_alpha_beta(shape): # pylint: disable=invalid-name
return random_ops.random_gamma( shape, alpha=[[1.], [3.], [5.], [6.]], beta=[[3., 4.]])
.while_v2 import while_loop as while_loop_v2 from tensorflow.python.platform import test def random_gamma(shape): # pylint: disable=invalid-name return random_ops.random_gamma(shape, 1.0) def random_gamma_with_alpha_beta(shape): # pylint: disable=invalid-name
64
64
52
17
47
Mycaster/tensorflow
tensorflow/python/kernel_tests/while_v2_test.py
Python
random_gamma_with_alpha_beta
random_gamma_with_alpha_beta
60
62
60
60
418baf99711be06b098b2bab5e2b5d71882ac181
bigcode/the-stack
train
dbf20b610670d77c6d626726
train
function
def random_poisson_v2_with_lam(shape): # pylint: disable=invalid-name return random_ops.random_poisson_v2(shape, [12.2, 3.3])
def random_poisson_v2_with_lam(shape): # pylint: disable=invalid-name
return random_ops.random_poisson_v2(shape, [12.2, 3.3])
.]], beta=[[3., 4.]]) def random_poisson_v2(shape): # pylint: disable=invalid-name return random_ops.random_poisson_v2(shape, 1.0) def random_poisson_v2_with_lam(shape): # pylint: disable=invalid-name
64
64
41
20
44
Mycaster/tensorflow
tensorflow/python/kernel_tests/while_v2_test.py
Python
random_poisson_v2_with_lam
random_poisson_v2_with_lam
69
70
69
69
cd20b3abb32ada3a2b317dbf12c3d7d20efab8fa
bigcode/the-stack
train
52bd3b9a343b6009cd744be6
train
function
def GetOptimizedGraph(): mg = meta_graph.create_meta_graph_def(graph=ops.get_default_graph()) config = config_pb2.ConfigProto() config.graph_options.rewrite_options.CopyFrom( rewriter_config_pb2.RewriterConfig( constant_folding=rewriter_config_pb2.RewriterConfig.OFF, memory_optimization=...
def GetOptimizedGraph():
mg = meta_graph.create_meta_graph_def(graph=ops.get_default_graph()) config = config_pb2.ConfigProto() config.graph_options.rewrite_options.CopyFrom( rewriter_config_pb2.RewriterConfig( constant_folding=rewriter_config_pb2.RewriterConfig.OFF, memory_optimization=rewriter_config_pb2.Rewri...
_elements=["Const:0", "while:2"]) grad_out, = gradients_impl.gradients(y, x) return grad_out self.assertAllEqual(F(), 8.0) def ScalarShape(): return ops.convert_to_tensor([], dtype=dtypes.int32) def GetOptimizedGraph():
64
64
95
6
58
Mycaster/tensorflow
tensorflow/python/kernel_tests/while_v2_test.py
Python
GetOptimizedGraph
GetOptimizedGraph
1,838
1,845
1,838
1,838
1b5786e1d3ccd1d9175b24ca87600d67aed0942c
bigcode/the-stack
train
d91b9a7a528d6fa617b0f507
train
function
def insert_markers(text, inserts): sections = [] lastpos = 0 for pos, marker in inserts: if pos > lastpos: sections.append(html.escape(text[lastpos:pos])) elif pos < lastpos: print ("INVALID MARKER", pos, marker, inserts) assert 0 sections.appen...
def insert_markers(text, inserts):
sections = [] lastpos = 0 for pos, marker in inserts: if pos > lastpos: sections.append(html.escape(text[lastpos:pos])) elif pos < lastpos: print ("INVALID MARKER", pos, marker, inserts) assert 0 sections.append(marker) lastpos = pos ...
, nodelist): inserts = [] idmap = {} segmentmap = {} flatten_nodes(nodelist, inserts, idmap, segmentmap) #print len(segmentmap.keys()) return insert_markers(doc, inserts), segmentmap def insert_markers(text, inserts):
64
64
108
8
55
canute24/egazette
ocr/annotations.py
Python
insert_markers
insert_markers
46
61
46
46
2a4fe63377b1f80cf67ae085d5b020a24e80ccc9
bigcode/the-stack
train
e0f8da27fdd80f8c8495699c
train
function
def annotate_doc(doc, nodelist): inserts = [] idmap = {} segmentmap = {} flatten_nodes(nodelist, inserts, idmap, segmentmap) #print len(segmentmap.keys()) return insert_markers(doc, inserts), segmentmap
def annotate_doc(doc, nodelist):
inserts = [] idmap = {} segmentmap = {} flatten_nodes(nodelist, inserts, idmap, segmentmap) #print len(segmentmap.keys()) return insert_markers(doc, inserts), segmentmap
and child.end <= self.end self.children.append(child) def get_id(tag, idmap): if tag in idmap: idmap[tag] += 1 else: idmap[tag] = 1 return idmap[tag] def annotate_doc(doc, nodelist):
64
64
60
9
55
canute24/egazette
ocr/annotations.py
Python
annotate_doc
annotate_doc
38
44
38
38
fbed2850faaae3bdf2f904a06aa2c6be41887c8b
bigcode/the-stack
train
1ceeb7d4e3a801d846ae2b01
train
function
def get_id(tag, idmap): if tag in idmap: idmap[tag] += 1 else: idmap[tag] = 1 return idmap[tag]
def get_id(tag, idmap):
if tag in idmap: idmap[tag] += 1 else: idmap[tag] = 1 return idmap[tag]
% len(self.children) return '{%s}' % s def __repr__(self): return self.__str__() def add_child(self, child): #assert child.start >= self.start and child.end <= self.end self.children.append(child) def get_id(tag, idmap):
64
64
42
8
56
canute24/egazette
ocr/annotations.py
Python
get_id
get_id
31
36
31
31
6f8aa07aadcccd52646d91102422de692ca02ba6
bigcode/the-stack
train
74f7c38469a733a939e3f3f9
train
class
class Node: def __init__(self, start, end, tag, parent, attrs): self.start = start self.end = end self.tag = tag self.parent = parent self.children = [] if attrs: self.attrs = attrs else: self.attrs = [] def __str__(self): ...
class Node:
def __init__(self, start, end, tag, parent, attrs): self.start = start self.end = end self.tag = tag self.parent = parent self.children = [] if attrs: self.attrs = attrs else: self.attrs = [] def __str__(self): s = ...
import html class Node:
6
64
191
3
2
canute24/egazette
ocr/annotations.py
Python
Node
Node
3
29
3
3
0f4ea8f63bd02248b24f261f24437d2f98a0597c
bigcode/the-stack
train
9bef92bc25fc251813ec83e0
train
function
def flatten_nodes(nodelist, inserts, idmap, segmentmap): for node in nodelist: attrlist = node.attrs[:] #id1 = '%s_%d' % (node.tag, get_id(node.tag, idmap)) #attrlist.append(('id', id1)) if attrlist: attrs = ' '.join('%s="%s"' % (attr[0], attr[1]) for attr in attrlist) ...
def flatten_nodes(nodelist, inserts, idmap, segmentmap):
for node in nodelist: attrlist = node.attrs[:] #id1 = '%s_%d' % (node.tag, get_id(node.tag, idmap)) #attrlist.append(('id', id1)) if attrlist: attrs = ' '.join('%s="%s"' % (attr[0], attr[1]) for attr in attrlist) start_tag = '<%s %s>' % (node.tag, attrs) ...
", pos, marker, inserts) assert 0 sections.append(marker) lastpos = pos if lastpos < len(text): sections.append(html.escape(text[lastpos:])) return u''.join(sections) def flatten_nodes(nodelist, inserts, idmap, segmentmap):
64
64
197
15
49
canute24/egazette
ocr/annotations.py
Python
flatten_nodes
flatten_nodes
63
82
63
63
2f267cc5e036a62589b5ddc09f7a0b4447ff3f3d
bigcode/the-stack
train
95cb17c1a8d0ae13619666a4
train
function
def find_url(url): r = requests.head(url, headers={'User-Agent': 'fetch_pmc_pdf/0.1'}) if r.status_code == 200: return url elif r.status_code == 303: # redirect return find_url(r.headers['Location']) else: return None
def find_url(url):
r = requests.head(url, headers={'User-Agent': 'fetch_pmc_pdf/0.1'}) if r.status_code == 200: return url elif r.status_code == 303: # redirect return find_url(r.headers['Location']) else: return None
/?tool={toolname}&email={email}&ids={pmid}&versions=no&format=json" PMC_URL = "https://www.ncbi.nlm.nih.gov/pmc/articles/{pmcid}/pdf/" logging.basicConfig() logger = logging.getLogger('pubmed_pdf') def find_url(url):
64
64
69
5
59
mstimberg/pubmed_pdf
pubmed_pdf.py
Python
find_url
find_url
15
22
15
15
13d2fb2e8bbe7e57d916b9ba311013d01412687d
bigcode/the-stack
train
959f5f6bd29df9ed7a13de02
train
function
def find_pmc_pdf(pmid): pmcid = pubmed_to_pmc(pmid) if pmcid is not None: logger.debug('PMCID: %s', pmcid) # Check whether PMC has a pdf url = PMC_URL.format(pmcid=pmcid[3:], toolname=TOOLNAME, email=EMAIL) url = find_url(url) return url r...
def find_pmc_pdf(pmid):
pmcid = pubmed_to_pmc(pmid) if pmcid is not None: logger.debug('PMCID: %s', pmcid) # Check whether PMC has a pdf url = PMC_URL.format(pmcid=pmcid[3:], toolname=TOOLNAME, email=EMAIL) url = find_url(url) return url return None
={'User-Agent': 'fetch_pmc_pdf/0.1'}) if r.status_code == 200: return url elif r.status_code == 303: # redirect return find_url(r.headers['Location']) else: return None def find_pmc_pdf(pmid):
64
64
92
8
55
mstimberg/pubmed_pdf
pubmed_pdf.py
Python
find_pmc_pdf
find_pmc_pdf
25
34
25
25
367c9cf9fd78d66b402ae329e801665a8db25d7a
bigcode/the-stack
train
19c9a8911e80dbbff7f074d8
train
function
def pubmed_to_pmc(pmid): url = API_URL.format(pmid=pmid, toolname=TOOLNAME, email=EMAIL) reply = requests.get(url).json() records = reply['records'][0] return records.get('pmcid', None)
def pubmed_to_pmc(pmid):
url = API_URL.format(pmid=pmid, toolname=TOOLNAME, email=EMAIL) reply = requests.get(url).json() records = reply['records'][0] return records.get('pmcid', None)
', pmcid) # Check whether PMC has a pdf url = PMC_URL.format(pmcid=pmcid[3:], toolname=TOOLNAME, email=EMAIL) url = find_url(url) return url return None def pubmed_to_pmc(pmid):
64
64
60
9
54
mstimberg/pubmed_pdf
pubmed_pdf.py
Python
pubmed_to_pmc
pubmed_to_pmc
37
41
37
37
dd4caa2d3a18ba27f6f8257a60b81b645717fd1c
bigcode/the-stack
train
8627da580a606c4360e257ad
train
function
def replace_pubmed_pmc(filename, new_filename=None, remove_links=False): if new_filename is None: new_filename = filename with open(filename) as f: bibtex = bibtexparser.load(f) counter = 0 for entry in bibtex.entries: logger.info('Processing entry with title: ' + entry.get('titl...
def replace_pubmed_pmc(filename, new_filename=None, remove_links=False):
if new_filename is None: new_filename = filename with open(filename) as f: bibtex = bibtexparser.load(f) counter = 0 for entry in bibtex.entries: logger.info('Processing entry with title: ' + entry.get('title', '<Unknown>')) if entry.get('link', '').startswith('http://www...
email=EMAIL) url = find_url(url) return url return None def pubmed_to_pmc(pmid): url = API_URL.format(pmid=pmid, toolname=TOOLNAME, email=EMAIL) reply = requests.get(url).json() records = reply['records'][0] return records.get('pmcid', None) def replace...
96
96
322
16
80
mstimberg/pubmed_pdf
pubmed_pdf.py
Python
replace_pubmed_pmc
replace_pubmed_pmc
44
72
44
44
648d8c4fe993c3637aac6b1396a6086ebcee8230
bigcode/the-stack
train
b2c8c0ff497b4b7c06ae2a5b
train
function
def craete_location(host): return { 'host': host, 'username': os.environ['USER'], 'key': '~/.ssh/id_rsa.pub', 'command': 'hostname' }
def craete_location(host):
return { 'host': host, 'username': os.environ['USER'], 'key': '~/.ssh/id_rsa.pub', 'command': 'hostname' }
'127.0.0.1', 'localhost', '127.0.0.1', 'localhost', '127.0.0.1', 'localhost', '127.0.0.1', 'localhost' ] def craete_location(host):
63
64
45
6
57
iumsds/cloudmesh-cloud
tests/2_local/test_ssh.py
Python
craete_location
craete_location
40
47
40
40
7945ee90d6b8355c532d6848d03a7d4d473b5dbf
bigcode/the-stack
train
70362a237460d2f5d35566fa
train
class
@pytest.mark.incremental class TestSsh: def ssh(self, processors=1): StopWatch.start(f"total p={processors} c=1") r = Host.ssh(hosts, command="hostname", processors=processors) StopWatch.stop(f"total p={processors} c=1") return r def t...
@pytest.mark.incremental class TestSsh:
def ssh(self, processors=1): StopWatch.start(f"total p={processors} c=1") r = Host.ssh(hosts, command="hostname", processors=processors) StopWatch.stop(f"total p={processors} c=1") return r def test_internal_ssh(self): print() ...
.0.1', 'localhost', '127.0.0.1', 'localhost', '127.0.0.1', 'localhost' ] def craete_location(host): return { 'host': host, 'username': os.environ['USER'], 'key': '~/.ssh/id_rsa.pub', 'command': 'hostname' } @pytest.mark.inc...
95
95
319
10
85
iumsds/cloudmesh-cloud
tests/2_local/test_ssh.py
Python
TestSsh
TestSsh
50
101
50
52
10a14c2e42282f884c03b35bc4887cb8c66fcd44
bigcode/the-stack
train
5b9a3a2835bd0b1200e143b0
train
function
def decompress_gzip(filepath, remove_original=True): ''' Decompresses a *.gz file located at ``filepath`` and saves a new copy with the same filename (except the *.gz is removed) in the source directory, optionally removing the old file if desired. Parameters ---------- filepath: str. Shou...
def decompress_gzip(filepath, remove_original=True):
''' Decompresses a *.gz file located at ``filepath`` and saves a new copy with the same filename (except the *.gz is removed) in the source directory, optionally removing the old file if desired. Parameters ---------- filepath: str. Should be of the form 'path/to/*.gz' remove_original...
to extract. Returns ------- A pandas Series with only the values of ``key`` as lists. ''' output = expand_dict_lists(l, drop_duplicates=False, keep_index=True) return output.groupby(output.index)[key].agg(list) def decompress_gzip(filepath, remove_original=True):
64
64
179
10
54
QS-2/VESPID
vespid/data/__init__.py
Python
decompress_gzip
decompress_gzip
196
223
196
196
05a0b09cc6748d72b0ee73919d5d2bc0589f660c
bigcode/the-stack
train
48571a434c926a07f444ca2a
train
function
def expand_dict_lists(lists, unique_ids=None, drop_duplicates=True, keep_index=False): ''' Given an iterable (e.g. pandas Series) containing lists of dicts that define unique entities and their metadata, return the unique entities + metadata as a DataFrame, with duplicates dropped. Parameters...
def expand_dict_lists(lists, unique_ids=None, drop_duplicates=True, keep_index=False):
''' Given an iterable (e.g. pandas Series) containing lists of dicts that define unique entities and their metadata, return the unique entities + metadata as a DataFrame, with duplicates dropped. Parameters ---------- lists: list-like iterable. Should contain data about each entity as ...
) elif isinstance(data, pd.core.frame.DataFrame) and columns is not None: for column in columns: output[column] = _replace_characters(output[column], special_characters_dict) elif isinstance(data, pd.core.frame.DataFrame) and columns is None: for column in data.col...
136
136
454
20
115
QS-2/VESPID
vespid/data/__init__.py
Python
expand_dict_lists
expand_dict_lists
110
168
110
111
36b221650fa8090d0729ebfb148f7a263e2e9023
bigcode/the-stack
train
5527fbea2df1e1712143b829
train
function
def find_columns_by_class(df, classes_to_find): ''' Given a pandas DataFrame, find the columns that have at least one object of the the same type as any of the `classes_to_find` provided. Parameters ---------- df : pandas DataFrame The DataFrame with all your data class_to...
def find_columns_by_class(df, classes_to_find):
''' Given a pandas DataFrame, find the columns that have at least one object of the the same type as any of the `classes_to_find` provided. Parameters ---------- df : pandas DataFrame The DataFrame with all your data class_to_find : list of object classes The type ...
with gzip.open(filepath, 'rb') as f_in: with open(filepath[:-3], 'wb') as f_out: shutil.copyfileobj(f_in, f_out) if remove_original: os.remove(filepath) return filepath[:-3] def find_columns_by_class(df, classes_to_find):
64
64
158
11
53
QS-2/VESPID
vespid/data/__init__.py
Python
find_columns_by_class
find_columns_by_class
225
250
225
225
219cae65f2d3e0e4b3ea58bfdeb896e1ddba29f3
bigcode/the-stack
train
253b069e98f4c5449e1cbcef
train
function
def extract_named_value_from_lists_of_dicts(l, key='name'): ''' Using a known key, extracts every value found for that key in lists of dicts (e.g. a pandas Series of lists of dicts) and returns the input iterable but with lists of only the values found for that key. Parameters ---------- ...
def extract_named_value_from_lists_of_dicts(l, key='name'):
''' Using a known key, extracts every value found for that key in lists of dicts (e.g. a pandas Series of lists of dicts) and returns the input iterable but with lists of only the values found for that key. Parameters ---------- l: iterable of lists of dicts. The data you want to extract ...
=unique_ids) else: output = pd.DataFrame( single_list_of_dicts, index=single_list_index) if keep_index: return output else: return output.reset_index(drop=True) def extract_named_value_from_lists_of_dicts(l, key='name'):
64
64
169
15
49
QS-2/VESPID
vespid/data/__init__.py
Python
extract_named_value_from_lists_of_dicts
extract_named_value_from_lists_of_dicts
171
193
171
171
921b6e9692e3f999123db33b980e8e8902135be8
bigcode/the-stack
train
407309888c5a3abf21501b34
train
function
def replace_special_solr_characters(data, columns=None): ''' Apache Solr interprets certain characters as special if it sees them anywhere in a query. In order to avoid accidentally querying for something you don't intend to, you need to escape these characters properly. Parameters ---------- ...
def replace_special_solr_characters(data, columns=None):
''' Apache Solr interprets certain characters as special if it sees them anywhere in a query. In order to avoid accidentally querying for something you don't intend to, you need to escape these characters properly. Parameters ---------- data: either a pandas Series or DataFrame with the st...
# -*- coding: utf-8 -*- import pandas as pd import re from urllib.parse import quote_plus from vespid import setup_logger import gzip import os import shutil from vespid import setup_logger, set_global_log_level logger = setup_logger(module_name=__name__) def replace_special_solr_characters(data, columns=None):
75
183
610
12
63
QS-2/VESPID
vespid/data/__init__.py
Python
replace_special_solr_characters
replace_special_solr_characters
14
108
14
14
b1e655b6cbf5d9f3d7ad4adc2974e0ef9c823ed4
bigcode/the-stack
train
d157ffb303f84b42c6ffda42
train
function
@register.tag def breadcrumb_url(parser, token): """ Same as breadcrumb but instead of url context variable takes in all the arguments URL tag takes. {% breadcrumb "Title of breadcrumb" person_detail person.id %} {% breadcrumb person.name person_detail person.id %} """ bits = to...
@register.tag def breadcrumb_url(parser, token):
""" Same as breadcrumb but instead of url context variable takes in all the arguments URL tag takes. {% breadcrumb "Title of breadcrumb" person_detail person.id %} {% breadcrumb person.name person_detail person.id %} """ bits = token.split_contents() if len(bits)==2: ...
url tag, i.e.: {% url person_detail object.id as person_url %} then: {% breadcrumb person.name person_url %} @author Andriy Drozdyuk """ return BreadcrumbNode(token.split_contents()[1:]) @register.tag def breadcrumb_url(parser, token):
63
64
126
11
53
sekar-srinivasan/sac
donor/templatetags/breadcrumbs.py
Python
breadcrumb_url
breadcrumb_url
31
51
31
32
b5aeb52ead18e6dadca8e66679f53aa86b89709b
bigcode/the-stack
train
68f3e1e5cc02c6c631eec87e
train
class
class UrlBreadcrumbNode(Node): def __init__(self, title, url_node): self.title = Variable(title) self.url_node = url_node def render(self, context): title = self.title.var if title.find("'")==-1 and title.find('"')==-1: try: val = self.title ...
class UrlBreadcrumbNode(Node):
def __init__(self, title, url_node): self.title = Variable(title) self.url_node = url_node def render(self, context): title = self.title.var if title.find("'")==-1 and title.find('"')==-1: try: val = self.title title = val.resolve(con...
if len(self.vars)>1: val = self.vars[1] try: url = val.resolve(context) except VariableDoesNotExist: print ('URL does not exist', val) url = None return create_crumb(title, url) class UrlBreadcrumbNode(Node):
64
64
124
6
58
sekar-srinivasan/sac
donor/templatetags/breadcrumbs.py
Python
UrlBreadcrumbNode
UrlBreadcrumbNode
88
107
88
88
208df06290c6a3ba2191c10bc6e1d2894fa88b30
bigcode/the-stack
train
2594159cde1acf16e1a22dd9
train
function
def create_crumb(title, url=None): """ Helper function """ crumb = """<span class="breadcrumbs-arrow">""" \ """<img src="/media/images/arrow.gif" alt="Arrow">""" \ """</span>""" if url: crumb = "%s<a href='%s'>%s</a>" % (crumb, url, title) else: crumb = "%...
def create_crumb(title, url=None):
""" Helper function """ crumb = """<span class="breadcrumbs-arrow">""" \ """<img src="/media/images/arrow.gif" alt="Arrow">""" \ """</span>""" if url: crumb = "%s<a href='%s'>%s</a>" % (crumb, url, title) else: crumb = "%s&nbsp;&nbsp;%s" % (crumb, title) ...
self.title title = val.resolve(context) except: title = '' else: title=title.strip("'").strip('"') title=smart_text(title) url = self.url_node.render(context) return create_crumb(title, url) def create_crumb(title, url=None):
64
64
105
9
55
sekar-srinivasan/sac
donor/templatetags/breadcrumbs.py
Python
create_crumb
create_crumb
110
122
110
110
340d4233646f75d4fb1a61defe36d9b6b2005814
bigcode/the-stack
train
d86921fd14cf0b9344658aaa
train
function
@register.tag def breadcrumb(parser, token): """ Renders the breadcrumb. Examples: {% breadcrumb "Title of breadcrumb" url_var %} {% breadcrumb context_var url_var %} {% breadcrumb "Just the title" %} {% breadcrumb just_context_var %} Parameters: -First parameter is...
@register.tag def breadcrumb(parser, token):
""" Renders the breadcrumb. Examples: {% breadcrumb "Title of breadcrumb" url_var %} {% breadcrumb context_var url_var %} {% breadcrumb "Just the title" %} {% breadcrumb just_context_var %} Parameters: -First parameter is the title of the crumb, -Second (optiona...
from django import template from django.template import loader, Node, Variable from django.utils.encoding import smart_str, smart_text from django.template.defaulttags import url from django.template import VariableDoesNotExist register = template.Library() @register.tag def breadcrumb(parser, token):
58
64
141
10
48
sekar-srinivasan/sac
donor/templatetags/breadcrumbs.py
Python
breadcrumb
breadcrumb
9
28
9
10
073990674b545bdda218f8dbec32e4b3a2788490
bigcode/the-stack
train
dae0fa817797136d1c7f5590
train
class
class BreadcrumbNode(Node): def __init__(self, vars): """ First var is title, second var is url context variable """ self.vars = map(Variable,vars) def render(self, context): title = self.vars[0].var if title.find("'")==-1 and title.find('"')==-1: tr...
class BreadcrumbNode(Node):
def __init__(self, vars): """ First var is title, second var is url context variable """ self.vars = map(Variable,vars) def render(self, context): title = self.vars[0].var if title.find("'")==-1 and title.find('"')==-1: try: val = sel...
() if len(bits)==2: return breadcrumb(parser, token) # Extract our extra title parameter title = bits.pop(1) token.contents = ' '.join(bits) url_node = url(parser, token) return UrlBreadcrumbNode(title, url_node) class BreadcrumbNode(Node):
64
64
181
5
59
sekar-srinivasan/sac
donor/templatetags/breadcrumbs.py
Python
BreadcrumbNode
BreadcrumbNode
54
85
54
54
dfc50662cd2326a950e0d7bc7f42c3fb4343b316
bigcode/the-stack
train
8cef65ec3b25a1b16390a484
train
class
class HistoryManager(Callback): def __init__(self): self.records = [] def __iter__(self): yield from self.records def __getitem__(self, idx): return self.records[idx] def __len__(self): return len(self.records) def append(self, epoch, step, metrics): self....
class HistoryManager(Callback):
def __init__(self): self.records = [] def __iter__(self): yield from self.records def __getitem__(self, idx): return self.records[idx] def __len__(self): return len(self.records) def append(self, epoch, step, metrics): self.records.append({'epoch' : epoch,...
import os from collections import defaultdict from operator import itemgetter from .base import Callback class History(Callback): """ Callback that record history of all training/validation metrics """ def __init__(self): super(History, self).__init__() self.registry = HistoryManager() ...
101
119
398
6
95
nirvguy/torchtrainer
torchtrainer/callbacks/history.py
Python
HistoryManager
HistoryManager
18
86
18
18
94f4aef3e32ddfc86aeb558f4eb1228fb2a908af
bigcode/the-stack
train
ae6230db46601145a0f37e0a
train
class
class History(Callback): """ Callback that record history of all training/validation metrics """ def __init__(self): super(History, self).__init__() self.registry = HistoryManager() def on_log(self): self.registry.append(self.trainer.epochs_trained, s...
class History(Callback):
""" Callback that record history of all training/validation metrics """ def __init__(self): super(History, self).__init__() self.registry = HistoryManager() def on_log(self): self.registry.append(self.trainer.epochs_trained, self.trainer.steps_trained...
import os from collections import defaultdict from operator import itemgetter from .base import Callback class History(Callback):
25
64
75
5
19
nirvguy/torchtrainer
torchtrainer/callbacks/history.py
Python
History
History
6
16
6
6
b72855564cda07cfab72eadce3b2812bc7818b40
bigcode/the-stack
train
0ad48560148872ae091bb109
train
function
async def handler(ctx, data=None, loop=None): """This function just reflects back the json that is supplied. This is useful for debugging clients that are calling this server """ result = {} try: data = json.loads(data) privkey = get_service_private_key() encryp...
async def handler(ctx, data=None, loop=None):
"""This function just reflects back the json that is supplied. This is useful for debugging clients that are calling this server """ result = {} try: data = json.loads(data) privkey = get_service_private_key() encrypted = string_to_bytes(data["data"]) d...
, get_service_private_key from Acquire.Service import create_return_value, pack_return_value, \ start_profile, end_profile from Acquire.ObjectStore import string_to_bytes from Acquire.Crypto import PrivateKey, PublicKey from cryptography import fernet async def handler(ctx, data=None, loo...
64
64
209
11
52
michellab/BioSimSpaceCloud
identity/test/test.py
Python
handler
handler
16
51
16
16
1d17a95af996b8be253f9debd6fce127d05c5cd5
bigcode/the-stack
train
7077e0783b6ec717e55aff9f
train
function
def tree(graph): def recurse(node, padding, last=False): if last: print(u"{}└── {}".format(padding[:-4], node)) else: print(u"{}├── {}".format(padding[:-4], node)) children = graph.successors(node) if children: for child in children[:-1]: ...
def tree(graph):
def recurse(node, padding, last=False): if last: print(u"{}└── {}".format(padding[:-4], node)) else: print(u"{}├── {}".format(padding[:-4], node)) children = graph.successors(node) if children: for child in children[:-1]: recurse(c...
#!/usr/bin/python # -*- coding: utf-8 -*- import networkx as nx graph = nx.DiGraph(["ac", "cd", "ce", "ab", 'ef','dg', 'dh']) def tree(graph):
49
64
117
4
45
jdowner/tree
tree.py
Python
tree
tree
8
22
8
8
e3d2674dd063748ed6633796341a88c372161601
bigcode/the-stack
train
bbdb248cc106cd4c41a41ae2
train
class
class ApacheHttp01(common.ChallengePerformer): """Class that performs HTTP-01 challenges within the Apache configurator.""" CONFIG_TEMPLATE22_PRE = """\ RewriteEngine on RewriteRule ^/\\.well-known/acme-challenge/([A-Za-z0-9-_=]+)$ {0}/$1 [L] """ CONFIG_TEMPLATE22_POST = """\ <...
class ApacheHttp01(common.ChallengePerformer):
"""Class that performs HTTP-01 challenges within the Apache configurator.""" CONFIG_TEMPLATE22_PRE = """\ RewriteEngine on RewriteRule ^/\\.well-known/acme-challenge/([A-Za-z0-9-_=]+)$ {0}/$1 [L] """ CONFIG_TEMPLATE22_POST = """\ <Directory {0}> Order Allow,Deny ...
"""A class that performs HTTP-01 challenges for Apache""" import logging from acme.magic_typing import List, Set # pylint: disable=unused-import, no-name-in-module from certbot import errors from certbot.compat import os from certbot.compat import filesystem from certbot.plugins import common from certbot_apache.ob...
113
256
1,599
10
103
calllevels/certbot
certbot-apache/certbot_apache/http_01.py
Python
ApacheHttp01
ApacheHttp01
17
210
17
17
a5b292d5547a3543265271d32af6294687baa515
bigcode/the-stack
train
9807b991e4b4b5a118e57cc0
train
function
def parse(tokens): global cur, nxt, e assert symap, "No operators registered." \ "Please define at least one operator decorated with infix()/prefix()/etc" cur = nxt = None e = chain(tokens, [END]) cur, nxt = shift() result = expr() # sanity check try: next(e) raise Exception("not all tokens ...
def parse(tokens):
global cur, nxt, e assert symap, "No operators registered." \ "Please define at least one operator decorated with infix()/prefix()/etc" cur = nxt = None e = chain(tokens, [END]) cur, nxt = shift() result = expr() # sanity check try: next(e) raise Exception("not all tokens was parsed: either ...
r" % sym) def expr(rbp=0): global cur, nxt cur, nxt = shift() left = cur.nud() while rbp < nxt.lbp: cur, nxt = shift() left = cur.led(left) return left def parse(tokens):
64
64
117
4
59
falseadmin/truthon
pratt.py
Python
parse
parse
178
193
178
178
f873bc86ad0c2a95a9ab54b688a86afc6b7116fe
bigcode/the-stack
train
f68bdf99679157b0b292ebef
train
class
class brackets: def __init__(self, open, close): self.open = open self.close = close def __call__(self, cls): open = self.open close = self.close def nud(self): e = expr() advance(close) return cls(e) symbol(open).nud = nud symbol(close) return cls
class brackets:
def __init__(self, open, close): self.open = open self.close = close def __call__(self, cls): open = self.open close = self.close def nud(self): e = expr() advance(close) return cls(e) symbol(open).nud = nud symbol(close) return cls
: """a zero-arg operator (== keyword)""" def __init__(self, sym): self.sym = sym def __call__(self, cls): def nud(self): return cls(self.sym) symbol(self.sym).nud = nud return cls class brackets:
64
64
82
3
60
falseadmin/truthon
pratt.py
Python
brackets
brackets
88
102
88
88
1b09b2948fad38dec8ade211c77d17dab7dbe8b0
bigcode/the-stack
train
cb4978eaa6f4eeb96cb7eaa0
train
class
class postfix: def __init__(self, sym, lbp): self.sym = sym self.lbp = lbp def __call__(self, cls): def led(self, left): return cls(left) symbol(self.sym, self.lbp).led = led return cls
class postfix:
def __init__(self, sym, lbp): self.sym = sym self.lbp = lbp def __call__(self, cls): def led(self, left): return cls(left) symbol(self.sym, self.lbp).led = led return cls
p): self.sym = sym self.lbp = lbp def __call__(self, cls): def led(self, left): return cls(left, expr(self.lbp-1)) symbol(self.sym, self.lbp).led = led return cls class postfix:
64
64
67
3
60
falseadmin/truthon
pratt.py
Python
postfix
postfix
64
73
64
64
5354de0147147c7a066a3a6b3e449c3f491c3cd9
bigcode/the-stack
train
a4e29adf5cb648e9170a2e27
train
function
def symbol(sym, lbp=0): try: Sym = symap[sym] except KeyError: class Sym: pass Sym.__name__ = Sym.__qualname__ = "Sym('%s')" % sym Sym.__repr__ = lambda _: "Sym('%s')" % sym Sym.sym = sym Sym.lbp = lbp symap[sym] = Sym else: Sym.lbp = max(lbp, Sym.lbp) return Sym
def symbol(sym, lbp=0):
try: Sym = symap[sym] except KeyError: class Sym: pass Sym.__name__ = Sym.__qualname__ = "Sym('%s')" % sym Sym.__repr__ = lambda _: "Sym('%s')" % sym Sym.sym = sym Sym.lbp = lbp symap[sym] = Sym else: Sym.lbp = max(lbp, Sym.lbp) return Sym
#!/usr/bin/env python3 """ Pratt-like parser. Inspired by http://effbot.org/zone/simple-top-down-parsing.htm """ from itertools import chain symap = {} def symbol(sym, lbp=0):
48
64
110
9
39
falseadmin/truthon
pratt.py
Python
symbol
symbol
12
24
12
12
5b352834fa6f95931543fc6d1000bb21f14e70e3
bigcode/the-stack
train
a1367535595246db4a60f5e8
train
function
def expr(rbp=0): global cur, nxt cur, nxt = shift() left = cur.nud() while rbp < nxt.lbp: cur, nxt = shift() left = cur.led(left) return left
def expr(rbp=0):
global cur, nxt cur, nxt = shift() left = cur.nud() while rbp < nxt.lbp: cur, nxt = shift() left = cur.led(left) return left
################### def shift(): global nxt, e return nxt, next(e) def advance(sym=None): global cur, nxt cur, nxt = shift() if sym and cur.sym != sym: raise SyntaxError("Expected %r" % sym) def expr(rbp=0):
64
64
55
7
57
falseadmin/truthon
pratt.py
Python
expr
expr
168
175
168
168
c3f39f342c2e90a81c1bf28b55d81d9bf02111a3
bigcode/the-stack
train
403a5bbade1ac150e2beba42
train
function
def advance(sym=None): global cur, nxt cur, nxt = shift() if sym and cur.sym != sym: raise SyntaxError("Expected %r" % sym)
def advance(sym=None):
global cur, nxt cur, nxt = shift() if sym and cur.sym != sym: raise SyntaxError("Expected %r" % sym)
END: """ A guard at the end of expression. """ lbp = 0 def __repr__(self): return "END" ################### # PRATT MACHINERY # ################### def shift(): global nxt, e return nxt, next(e) def advance(sym=None):
64
64
39
5
59
falseadmin/truthon
pratt.py
Python
advance
advance
161
165
161
161
2738ab59a566a5639ac1a01e58e68f2f9f398b04
bigcode/the-stack
train
945e7ebb6f7ed4e9d578d0fd
train
class
class infix_r: def __init__(self, sym, lbp): self.sym = sym self.lbp = lbp def __call__(self, cls): def led(self, left): return cls(left, expr(self.lbp-1)) symbol(self.sym, self.lbp).led = led return cls
class infix_r:
def __init__(self, sym, lbp): self.sym = sym self.lbp = lbp def __call__(self, cls): def led(self, left): return cls(left, expr(self.lbp-1)) symbol(self.sym, self.lbp).led = led return cls
p): self.sym = sym self.lbp = lbp def __call__(self, cls): def led(self, left): return cls(left, expr(self.lbp)) symbol(self.sym, self.lbp).led = led return cls class infix_r:
64
64
76
5
58
falseadmin/truthon
pratt.py
Python
infix_r
infix_r
52
61
52
52
42def939e50ea8fad0e365865501a7cf825116ab
bigcode/the-stack
train
1b4d65f2ca906d9fc455cbad
train
class
class ifelse: """ Ternary operator with a slightly strange syntax VALUE if COND else VALUE""" def __init__(self, lbp): self.lbp = lbp def __call__(self, cls): def led(self, left): then = left iff = expr() advance("else") otherwise = expr() return cls(iff, then, otherwise) ...
class ifelse:
""" Ternary operator with a slightly strange syntax VALUE if COND else VALUE""" def __init__(self, lbp): self.lbp = lbp def __call__(self, cls): def led(self, left): then = left iff = expr() advance("else") otherwise = expr() return cls(iff, then, otherwise) symbol("if",...
.close lbp = self.lbp def led(self, left): right = expr() if close: advance(close) return cls(left, right) symbol(open, lbp=1000).led = led symbol(close) return cls class ifelse:
64
64
110
4
59
falseadmin/truthon
pratt.py
Python
ifelse
ifelse
128
142
128
128
b242b3b6fecc0e91627eb15f24b0354fa224003a
bigcode/the-stack
train
60f669702cb6ea7a9ceb83a0
train
class
class subscript: """ Postfix subscriptions, e.g., array[1]. """ def __init__(self, *args): if len(args) == 2: # no close tag defined self.open, self.lbp = args self.close = None elif len(args) == 3: # there is a close tag self.open, self.close, self.lbp = args def __call__(self, cls):...
class subscript:
""" Postfix subscriptions, e.g., array[1]. """ def __init__(self, *args): if len(args) == 2: # no close tag defined self.open, self.lbp = args self.close = None elif len(args) == 3: # there is a close tag self.open, self.close, self.lbp = args def __call__(self, cls): open = self...
.close = close def __call__(self, cls): open = self.open close = self.close def nud(self): e = expr() advance(close) return cls(e) symbol(open).nud = nud symbol(close) return cls class subscript:
64
64
169
4
59
falseadmin/truthon
pratt.py
Python
subscript
subscript
105
125
105
105
1340a9e26aa20b4cf9f8a6e5c0e8ae572857f6e9
bigcode/the-stack
train
1d89de50a8e3d8c9b7076b59
train
class
class infix: def __init__(self, sym, lbp): self.sym = sym self.lbp = lbp def __call__(self, cls): def led(self, left): return cls(left, expr(self.lbp)) symbol(self.sym, self.lbp).led = led return cls
class infix:
def __init__(self, sym, lbp): self.sym = sym self.lbp = lbp def __call__(self, cls): def led(self, left): return cls(left, expr(self.lbp)) symbol(self.sym, self.lbp).led = led return cls
, rbp): self.sym = sym self.rbp = rbp def __call__(self, cls): rbp = self.rbp def nud(self): return cls(expr(rbp)) symbol(self.sym).nud = nud return cls class infix:
64
64
73
4
59
falseadmin/truthon
pratt.py
Python
infix
infix
40
49
40
40
103b44f482cb759a872fdadf2cb2a5c802b28b14
bigcode/the-stack
train
1550c554f8e8772d002f00ff
train
function
def shift(): global nxt, e return nxt, next(e)
def shift():
global nxt, e return nxt, next(e)
=self.lbp).led = led symbol("else") return cls class END: """ A guard at the end of expression. """ lbp = 0 def __repr__(self): return "END" ################### # PRATT MACHINERY # ################### def shift():
64
64
16
3
61
falseadmin/truthon
pratt.py
Python
shift
shift
156
158
156
156
cd22008ac78a49b0628c139229a0fe4f49969874
bigcode/the-stack
train
bb38cdcb7459be9d19330296
train
class
class END: """ A guard at the end of expression. """ lbp = 0 def __repr__(self): return "END"
class END:
""" A guard at the end of expression. """ lbp = 0 def __repr__(self): return "END"
def led(self, left): then = left iff = expr() advance("else") otherwise = expr() return cls(iff, then, otherwise) symbol("if", lbp=self.lbp).led = led symbol("else") return cls class END:
64
64
33
3
60
falseadmin/truthon
pratt.py
Python
END
END
145
149
145
145
e4ad0136c12c043700e5e581738cd2c61e5264c2
bigcode/the-stack
train
b910b72638ce4d55a189daf0
train
class
class prefix: def __init__(self, sym, rbp): self.sym = sym self.rbp = rbp def __call__(self, cls): rbp = self.rbp def nud(self): return cls(expr(rbp)) symbol(self.sym).nud = nud return cls
class prefix:
def __init__(self, sym, rbp): self.sym = sym self.rbp = rbp def __call__(self, cls): rbp = self.rbp def nud(self): return cls(expr(rbp)) symbol(self.sym).nud = nud return cls
sym Sym.__repr__ = lambda _: "Sym('%s')" % sym Sym.sym = sym Sym.lbp = lbp symap[sym] = Sym else: Sym.lbp = max(lbp, Sym.lbp) return Sym class prefix:
64
64
71
3
60
falseadmin/truthon
pratt.py
Python
prefix
prefix
27
37
27
27
ad9ada5e12a64a8c2cdff25a10839816f4ab9061
bigcode/the-stack
train
d2ec749b91ca77b0b5cb6ea7
train
class
class nullary: """a zero-arg operator (== keyword)""" def __init__(self, sym): self.sym = sym def __call__(self, cls): def nud(self): return cls(self.sym) symbol(self.sym).nud = nud return cls
class nullary:
"""a zero-arg operator (== keyword)""" def __init__(self, sym): self.sym = sym def __call__(self, cls): def nud(self): return cls(self.sym) symbol(self.sym).nud = nud return cls
__(self, sym, lbp): self.sym = sym self.lbp = lbp def __call__(self, cls): def led(self, left): return cls(left) symbol(self.sym, self.lbp).led = led return cls class nullary:
64
64
64
4
59
falseadmin/truthon
pratt.py
Python
nullary
nullary
76
85
76
76
e580847eb349d0cbc3eb5ad63df61545122bf319
bigcode/the-stack
train
d5af8664a38107f6f315c78f
train
function
@pytest.fixture def single_company(art_project_factory, research_project_factory, company_factory): company = company_factory(future_projects=(research_project_factory(), art_project_factory())) return company
@pytest.fixture def single_company(art_project_factory, research_project_factory, company_factory):
company = company_factory(future_projects=(research_project_factory(), art_project_factory())) return company
entries @pytest.fixture def single_comment(blog, author, entry_factory, comment_factory): entry = entry_factory(blog=blog, authors=(author,)) comment_factory(entry=entry) return comment_factory(entry=entry) @pytest.fixture def single_company(art_project_factory, research_project_factory, company_factory)...
64
64
39
18
46
luismorenolopera/django-rest-framework-json-api
example/tests/conftest.py
Python
single_company
single_company
60
63
60
61
205a88ae9d4bc374ff64650638cbb43ac71ffcd4
bigcode/the-stack
train
b4861d300f5e58cb069424ca
train
function
@pytest.fixture def single_art_project(art_project_factory): return art_project_factory()
@pytest.fixture def single_art_project(art_project_factory):
return art_project_factory()
_factory(entry=entry) return comment_factory(entry=entry) @pytest.fixture def single_company(art_project_factory, research_project_factory, company_factory): company = company_factory(future_projects=(research_project_factory(), art_project_factory())) return company @pytest.fixture def single_art_project...
64
64
18
12
51
luismorenolopera/django-rest-framework-json-api
example/tests/conftest.py
Python
single_art_project
single_art_project
66
68
66
67
a927d1bf0d9032e58a5ad26e2ad5e6bb09c25229
bigcode/the-stack
train
4ffe92b4fe81503fab0dac7a
train
function
@pytest.fixture def single_comment(blog, author, entry_factory, comment_factory): entry = entry_factory(blog=blog, authors=(author,)) comment_factory(entry=entry) return comment_factory(entry=entry)
@pytest.fixture def single_comment(blog, author, entry_factory, comment_factory):
entry = entry_factory(blog=blog, authors=(author,)) comment_factory(entry=entry) return comment_factory(entry=entry)
=blog_factory(), authors=(author_factory(),)), entry_factory(blog=blog_factory(), authors=(author_factory(),)), ] comment_factory(entry=entries[0]) comment_factory(entry=entries[1]) return entries @pytest.fixture def single_comment(blog, author, entry_factory, comment_factory):
64
64
44
16
47
luismorenolopera/django-rest-framework-json-api
example/tests/conftest.py
Python
single_comment
single_comment
53
57
53
54
e632cae4b4981a27725a8751ed8a31280fe3c93c
bigcode/the-stack
train
b86111465e199deb611b68cc
train
function
@pytest.fixture def single_entry(blog, author, entry_factory, comment_factory, tagged_item_factory): entry = entry_factory(blog=blog, authors=(author,)) comment_factory(entry=entry) tagged_item_factory(content_object=entry) return entry
@pytest.fixture def single_entry(blog, author, entry_factory, comment_factory, tagged_item_factory):
entry = entry_factory(blog=blog, authors=(author,)) comment_factory(entry=entry) tagged_item_factory(content_object=entry) return entry
(AuthorBioMetadataFactory) register(AuthorTypeFactory) register(EntryFactory) register(CommentFactory) register(TaggedItemFactory) register(ArtProjectFactory) register(ResearchProjectFactory) register(CompanyFactory) @pytest.fixture def single_entry(blog, author, entry_factory, comment_factory, tagged_item_factory):
64
64
53
20
44
luismorenolopera/django-rest-framework-json-api
example/tests/conftest.py
Python
single_entry
single_entry
32
38
32
34
64addf65f53ec9dfd2f5f854b165416276810872
bigcode/the-stack
train
a8e037f9a648c8db19fac2a7
train
function
@pytest.fixture def multiple_entries(blog_factory, author_factory, entry_factory, comment_factory): entries = [ entry_factory(blog=blog_factory(), authors=(author_factory(),)), entry_factory(blog=blog_factory(), authors=(author_factory(),)), ] comment_factory(entry=entries[0]) comment_f...
@pytest.fixture def multiple_entries(blog_factory, author_factory, entry_factory, comment_factory):
entries = [ entry_factory(blog=blog_factory(), authors=(author_factory(),)), entry_factory(blog=blog_factory(), authors=(author_factory(),)), ] comment_factory(entry=entries[0]) comment_factory(entry=entries[1]) return entries
, author, entry_factory, comment_factory, tagged_item_factory): entry = entry_factory(blog=blog, authors=(author,)) comment_factory(entry=entry) tagged_item_factory(content_object=entry) return entry @pytest.fixture def multiple_entries(blog_factory, author_factory, entry_factory, comment_factory):
64
64
74
18
45
luismorenolopera/django-rest-framework-json-api
example/tests/conftest.py
Python
multiple_entries
multiple_entries
41
50
41
43
3f569ef083bc02d52a6daad0a94aad5a51c175c6
bigcode/the-stack
train
2450ef4fd9c87b34ee7b71d3
train
function
@pytest.fixture def client(): return APIClient()
@pytest.fixture def client():
return APIClient()
) @pytest.fixture def single_company(art_project_factory, research_project_factory, company_factory): company = company_factory(future_projects=(research_project_factory(), art_project_factory())) return company @pytest.fixture def single_art_project(art_project_factory): return art_project_factory() @p...
64
64
11
6
58
luismorenolopera/django-rest-framework-json-api
example/tests/conftest.py
Python
client
client
71
73
71
72
b9ec0524781ef3accd16bb270a3e6b9673460bf8
bigcode/the-stack
train
376bdc3926d6107a94cc003e
train
class
class AbstractGame: """Abstract class for running a card game""" def __init__(self, players=[], deck=None): self.players = list(players) self.deck = deck def play_game(self): """Override this function for custom game logic""" pass
class AbstractGame:
"""Abstract class for running a card game""" def __init__(self, players=[], deck=None): self.players = list(players) self.deck = deck def play_game(self): """Override this function for custom game logic""" pass
class AbstractGame:
4
64
58
4
0
mleyfman/abstract-card-game
AbstractGame.py
Python
AbstractGame
AbstractGame
1
10
1
1
c242246ddd1214caf596ffd07b106754452120d1
bigcode/the-stack
train
aa6f1103e32f3f24d375dcac
train
class
class Search(Base): name = 'Browser' manifest_url = "app://search.gaiamobile.org/manifest.webapp" _url_bar_locator = (By.CSS_SELECTOR, 'div.search-app .urlbar .title') _history_item_locator = (By.CSS_SELECTOR, '#history .result') _private_window_locator = (By.ID, 'private-window') def go_to_u...
class Search(Base):
name = 'Browser' manifest_url = "app://search.gaiamobile.org/manifest.webapp" _url_bar_locator = (By.CSS_SELECTOR, 'div.search-app .urlbar .title') _history_item_locator = (By.CSS_SELECTOR, '#history .result') _private_window_locator = (By.ID, 'private-window') def go_to_url(self, url): ...
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from gaiatest.apps.base import Base from marionette_driver import expected, By, Wait class Search(Base):
79
109
366
4
74
jaoo/gaia
tests/python/gaia-ui-tests/gaiatest/apps/search/app.py
Python
Search
Search
9
46
9
10
610af4d4712cb5e047cbd91135d30fa8c3e2bead
bigcode/the-stack
train
416392ae87de914b70bf4860
train
function
def test_polylog_expansion(): from sympy import log assert polylog(s, 0) == 0 assert polylog(s, 1) == zeta(s) assert polylog(s, -1) == dirichlet_eta(s) assert myexpand(polylog(1, z), -log(1 + exp_polar(-I*pi)*z)) assert myexpand(polylog(0, z), z/(1 - z)) assert myexpand(polylog(-1, z), z**2...
def test_polylog_expansion():
from sympy import log assert polylog(s, 0) == 0 assert polylog(s, 1) == zeta(s) assert polylog(s, -1) == dirichlet_eta(s) assert myexpand(polylog(1, z), -log(1 + exp_polar(-I*pi)*z)) assert myexpand(polylog(0, z), z/(1 - z)) assert myexpand(polylog(-1, z), z**2/(1 - z)**2 + z/(1 - z)) a...
subs = {} for a in func.free_symbols: subs[a] = randcplx() return abs(func.subs(subs).n() - expanded.replace(exp_polar, exp).subs(subs).n()) < 1e-10 def test_polylog_expansion():
64
64
139
7
56
ovolve/sympy
sympy/functions/special/tests/test_zeta_functions.py
Python
test_polylog_expansion
test_polylog_expansion
123
132
123
123
b82a28b02b2cf9c98c4f01575a58a5184ac77bc0
bigcode/the-stack
train
5666df3d5135b58422d7d2dd
train
function
def test_lerchphi_expansion(): assert myexpand(lerchphi(1, s, a), zeta(s, a)) assert myexpand(lerchphi(z, s, 1), polylog(s, z)/z) # direct summation assert myexpand(lerchphi(z, -1, a), a/(1 - z) + z/(1 - z)**2) assert myexpand(lerchphi(z, -3, a), None) # polylog reduction assert myexpand(le...
def test_lerchphi_expansion():
assert myexpand(lerchphi(1, s, a), zeta(s, a)) assert myexpand(lerchphi(z, s, 1), polylog(s, z)/z) # direct summation assert myexpand(lerchphi(z, -1, a), a/(1 - z) + z/(1 - z)**2) assert myexpand(lerchphi(z, -3, a), None) # polylog reduction assert myexpand(lerchphi(z, s, S(1)/2), ...
(s, 1) == zeta(s) assert polylog(s, -1) == dirichlet_eta(s) assert myexpand(polylog(1, z), -log(1 + exp_polar(-I*pi)*z)) assert myexpand(polylog(0, z), z/(1 - z)) assert myexpand(polylog(-1, z), z**2/(1 - z)**2 + z/(1 - z)) assert myexpand(polylog(-5, z), None) def test_lerchphi_expansion():
117
117
392
9
108
ovolve/sympy
sympy/functions/special/tests/test_zeta_functions.py
Python
test_lerchphi_expansion
test_lerchphi_expansion
135
157
135
135
a5557ec7a9c646d067b318d46b85f235a5cd3804
bigcode/the-stack
train