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
2ea8eb47da2e0238f1db3738
train
function
def get_update_func(nodelist,surveys): cmp = matplotlib.cm.ScalarMappable(norm=None, cmap='cool').get_cmap() def update(val): dist = sdist.val clusters = cluster_surveys.clusters_at_distance(nodelist,dist) colour_intensity = np.array([len(cluster) for cluster in clusters]) cols =...
def get_update_func(nodelist,surveys):
cmp = matplotlib.cm.ScalarMappable(norm=None, cmap='cool').get_cmap() def update(val): dist = sdist.val clusters = cluster_surveys.clusters_at_distance(nodelist,dist) colour_intensity = np.array([len(cluster) for cluster in clusters]) cols = cmp(colour_intensity/N_surveyors) ...
import numpy as np import matplotlib.pyplot as plt from matplotlib.widgets import Slider, Button, RadioButtons from matplotlib.collections import EllipseCollection import matplotlib.cm import matplotlib.artist import cluster_surveys from utils import convert, distance def get_update_func(nodelist,surveys):
61
116
387
11
49
aliFrancis/mars-crater-catalogue
src/cluster_slider.py
Python
get_update_func
get_update_func
12
43
12
12
ab99634837cb28cc52a8256fce1a74343df390ef
bigcode/the-stack
train
095dc47241317e919481afb1
train
function
def send_message(message, jwt): body = { 'action': 'send_message', 'args': { 'message': message, } } return http_client(service_name, body=body, jwt=jwt)
def send_message(message, jwt):
body = { 'action': 'send_message', 'args': { 'message': message, } } return http_client(service_name, body=body, jwt=jwt)
from app.service.http_client import http_client service_name = 'uaa' def send_message(message, jwt):
22
64
49
7
15
corner4world/cubeai
umd-python/app/service/uaa_client.py
Python
send_message
send_message
7
14
7
7
3c1206339e7a637d76553dde57b3b2832a130039
bigcode/the-stack
train
bb707133d7ddb419acfc5557
train
class
@ddt.ddt class PortSecTest(base_security.BaseSecGroupTest, base.BaseNetworkTest): @test.idempotent_id('7c338ddf-e64e-4118-bd33-e49a1f2f1495') @test.requires_ext(extension='port-security', service='network') def test_port_sec_default_value(self): # Default port-sec value is True, a...
@ddt.ddt class PortSecTest(base_security.BaseSecGroupTest, base.BaseNetworkTest): @test.idempotent_id('7c338ddf-e64e-4118-bd33-e49a1f2f1495') @test.requires_ext(extension='port-security', service='network')
def test_port_sec_default_value(self): # Default port-sec value is True, and the attr of the port will inherit # from the port-sec of the network when it not be specified in API network = self.create_network() self.assertTrue(network['port_security_enabled']) self.create_subn...
"License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS...
256
256
1,252
69
187
ISCAS-VDI/neutron-base
neutron/tests/tempest/api/test_extension_driver_port_security.py
Python
PortSecTest
PortSecTest
27
149
27
32
96f55bd9c439032f4d6c75f2bf40d22e0d6324f9
bigcode/the-stack
train
98069ad330e4a796d920f9db
train
class
class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) #first_name #last_name total_likes = models.IntegerField(default=0) image = models.ImageField(default='default.jpg', upload_to='profile_pics') follows = models.ManyToManyField('self', related_name='followers...
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE) #first_name #last_name total_likes = models.IntegerField(default=0) image = models.ImageField(default='default.jpg', upload_to='profile_pics') follows = models.ManyToManyField('self', related_name='followers', blank=True, symmetrical=Fa...
from django.db import models from django.contrib.auth.models import User from main.models import Post from PIL import Image class Profile(models.Model):
30
64
184
5
24
DanHunt27/Music-Website
mysite/users/models.py
Python
Profile
Profile
7
27
7
7
e95195ca498e955549c0e57134d6a90200a1e4d3
bigcode/the-stack
train
921f187de815c828427f1b58
train
class
class ARN(BaseARN): def __init__(self, resource='', region='', account=''): sup = super(ARN, self) sup.__init__(service=prefix, resource=resource, region=region, account=account)
class ARN(BaseARN):
def __init__(self, resource='', region='', account=''): sup = super(ARN, self) sup.__init__(service=prefix, resource=resource, region=region, account=account)
aws import Action as BaseAction from aws import BaseARN service_name = 'AWS X-Ray' prefix = 'xray' class Action(BaseAction): def __init__(self, action=None): sup = super(Action, self) sup.__init__(prefix, action) class ARN(BaseARN):
64
64
50
5
59
mtrspringer/awacs
awacs/xray.py
Python
ARN
ARN
19
23
19
19
3decc5b71a0a3c89c8e0e3bcb1a15fcb594714a0
bigcode/the-stack
train
2c38206c9f77fad3040cb8a0
train
class
class Action(BaseAction): def __init__(self, action=None): sup = super(Action, self) sup.__init__(prefix, action)
class Action(BaseAction):
def __init__(self, action=None): sup = super(Action, self) sup.__init__(prefix, action)
c) 2012-2013, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. from aws import Action as BaseAction from aws import BaseARN service_name = 'AWS X-Ray' prefix = 'xray' class Action(BaseAction):
64
64
32
5
59
mtrspringer/awacs
awacs/xray.py
Python
Action
Action
13
16
13
13
d7d032e10dbe02e94d06a7bfde9139fffa993d29
bigcode/the-stack
train
25bcf76f8bc14da084658b0b
train
function
def consultar(message,bot): cmd = (message.text).replace('/cep ','').replace('/CEP ','') print('Consulta por CEP requisitada por {} {}'.format(message.chat.first_name,message.chat.last_name)) if len(cmd) != 8: msg="QUANTIDADE DE DIGITOS INVALIDA" else: api = requests.get('https://viacep.com.br/ws/{}/json/'.form...
def consultar(message,bot):
cmd = (message.text).replace('/cep ','').replace('/CEP ','') print('Consulta por CEP requisitada por {} {}'.format(message.chat.first_name,message.chat.last_name)) if len(cmd) != 8: msg="QUANTIDADE DE DIGITOS INVALIDA" else: api = requests.get('https://viacep.com.br/ws/{}/json/'.format(cmd)).json() if 'erro' ...
import requests def consultar(message,bot):
9
64
207
6
2
hackersoares/hsconsulta_bot
data/cep.py
Python
consultar
consultar
2
23
2
2
13795b2150accf7696ffeef0c69969c4d36d57d4
bigcode/the-stack
train
73e9ba840e3bf711b3f3f6e9
train
function
def ensure_path_exists(save_path): # https://stackoverflow.com/questions/273192/how-can-i-safely-create-a-nested-directory-in-python dir_name = os.path.dirname(save_path) from pathlib import Path Path(dir_name).mkdir(parents=True, exist_ok=True)
def ensure_path_exists(save_path): # https://stackoverflow.com/questions/273192/how-can-i-safely-create-a-nested-directory-in-python
dir_name = os.path.dirname(save_path) from pathlib import Path Path(dir_name).mkdir(parents=True, exist_ok=True)
(save_path)) return { "accuracies": accuracy_results_df, "stel_tasks": stel_instances, "single_predictions": prediction_df } def ensure_path_exists(save_path): # https://stackoverflow.com/questions/273192/how-can-i-safely-create-a-nested-directory-in-python
64
64
62
31
33
nlpsoc/STEL
src/eval_style_models.py
Python
ensure_path_exists
ensure_path_exists
180
185
180
181
c1ca88fa5ef9327d05a1491e1c7369e0ce5bf77c
bigcode/the-stack
train
5125bcdfc39cacbac07928dc
train
function
def predict_alternatives(sims, triple): """ :param sims: similarity values for considered tasks (4 per question if triple=False, 2 per question if triple=True) following order: sim(A1,S1), sim(A1, S2), [sim(A2, S1), sim(A2, S2)] :param triple: whether models are evaluated on the quadruple or th...
def predict_alternatives(sims, triple):
""" :param sims: similarity values for considered tasks (4 per question if triple=False, 2 per question if triple=True) following order: sim(A1,S1), sim(A1, S2), [sim(A2, S1), sim(A2, S2)] :param triple: whether models are evaluated on the quadruple or the triple setup :return: pred...
1 with sentence 1 anchors.append(anchor_1) sentences.append(sentence_1) # compare anchor 1 with sentence 2 anchors.append(anchor_1) sentences.append(sentence_2) if not triple: # compare anchor 2 with sentence 1 anchors.append(anchor_2) ...
180
180
603
10
170
nlpsoc/STEL
src/eval_style_models.py
Python
predict_alternatives
predict_alternatives
343
394
343
343
3f2c87a9088c9c4af966640e28d8525b78ac952c
bigcode/the-stack
train
6118d1dbad4fd6b69abba2a9
train
function
def calculate_accuracies(stel_instances, predictions_dict, stel_types, f_name): """ given the stel task instances and the predictions for the style similarity function of name f_name, calculate the total accuracy and the accuracies per dimension/characteristic :param stel_instances: dataframe wi...
def calculate_accuracies(stel_instances, predictions_dict, stel_types, f_name):
""" given the stel task instances and the predictions for the style similarity function of name f_name, calculate the total accuracy and the accuracies per dimension/characteristic :param stel_instances: dataframe with task instances :param predictions_dict: dictionary including 'is_random',...
if stel_dim_tsv and stel_char_tsv: stel_instances = pd.concat([dim_instances_df, char_instances_df], ignore_index=True) stel_types = list(stel_instances[STYLE_TYPE_COL].unique()) logging.info('Evaluating on {} style dim and {} style char tasks ... ' .format(len(dim_instance...
185
185
619
18
166
nlpsoc/STEL
src/eval_style_models.py
Python
calculate_accuracies
calculate_accuracies
231
273
231
231
efc37ff18c0f15a2fdeb16971639a5378a64c4ca
bigcode/the-stack
train
4f236eec697cde49d2f6f813
train
function
def read_tsv_list_to_pd(csv_file_list: List[str]): """ :param csv_file_list: list of file paths to csv files separated with tabs :return: dataframe of concatenated dataframe, beginning with the first element in the string list """ csv_df = read_tsv_to_pd(csv_file_list[0]) # , index_col=0 for fi...
def read_tsv_list_to_pd(csv_file_list: List[str]):
""" :param csv_file_list: list of file paths to csv files separated with tabs :return: dataframe of concatenated dataframe, beginning with the first element in the string list """ csv_df = read_tsv_to_pd(csv_file_list[0]) # , index_col=0 for file_tsv in csv_file_list[1:]: cur_df = read_...
== np.linalg.norm(a1s2) random_answer = random.choice([1, 2]) predictions.append(random_answer) nbr_random += 1 is_random.append(True) return is_random, nbr_random, predictions def read_tsv_list_to_pd(csv_file_list: List[str]):
64
64
123
14
49
nlpsoc/STEL
src/eval_style_models.py
Python
read_tsv_list_to_pd
read_tsv_list_to_pd
397
406
397
397
6f6f323d5a946ef3453169bd10f5c27ece83cfc8
bigcode/the-stack
train
867d54d1ab85048e5aa41014
train
function
def get_rnd_adapted_accuracy(cur_ground_truth: List[int], cur_predictions: List[int], nbr_random: int) -> float: """ calculate the 'random' adapted accuracy, i.e., for the number of random guesses accuracy is 0.5 :param cur_ground_truth: list of ground truth values (ints) :param cur_predictions: list of...
def get_rnd_adapted_accuracy(cur_ground_truth: List[int], cur_predictions: List[int], nbr_random: int) -> float:
""" calculate the 'random' adapted accuracy, i.e., for the number of random guesses accuracy is 0.5 :param cur_ground_truth: list of ground truth values (ints) :param cur_predictions: list of predictions (ints) :param nbr_random: nbr of random guesses :return: """ assert len(cur_ground_t...
_tasks - cur_nbr_random)) cur_result_dict['Accuracy ' + cur_stel_type] = cur_style_acc return cur_result_dict, prediction_per_instance def get_rnd_adapted_accuracy(cur_ground_truth: List[int], cur_predictions: List[int], nbr_random: int) -> float:
64
64
184
29
34
nlpsoc/STEL
src/eval_style_models.py
Python
get_rnd_adapted_accuracy
get_rnd_adapted_accuracy
276
291
276
276
67e4d4390b703a7b0d0f4878e1ce3eb29e62b097
bigcode/the-stack
train
97366e73070b96d5daba4d0d
train
function
def get_predictions(sim_function_callable: Callable, df_questions: pd.DataFrame, triple: bool = True): """ :param sim_function_callable: similarity function that takes two arrays of the same length as input and returns an array of similairties between the respective elements at the same position in the...
def get_predictions(sim_function_callable: Callable, df_questions: pd.DataFrame, triple: bool = True):
""" :param sim_function_callable: similarity function that takes two arrays of the same length as input and returns an array of similairties between the respective elements at the same position in the input arrays :param df_questions: dataframe of the STEL questions to look at with the TSV columns ...
list of predictions (ints) :param nbr_random: nbr of random guesses :return: """ assert len(cur_ground_truth) == len(cur_predictions) if nbr_random < len(cur_predictions): accuracy = len(cur_predictions) / (nbr_random + len(cur_predictions)) * \ accuracy_score(cur_ground_...
129
129
432
22
106
nlpsoc/STEL
src/eval_style_models.py
Python
get_predictions
get_predictions
294
340
294
294
34da9aa722aa45c217297861d8fea49f2f36ec57
bigcode/the-stack
train
d8f5d9a208a788adba397f14
train
function
def read_in_stel_instances(stel_dim_tsv: List[str], stel_char_tsv: List[str], filter_majority_votes: bool): """ read in task instances to evalaute from list of paths to tsv files for stel dimensions and characteristics respectively :param filter_majority_votes: :param stel_char_tsv: ...
def read_in_stel_instances(stel_dim_tsv: List[str], stel_char_tsv: List[str], filter_majority_votes: bool):
""" read in task instances to evalaute from list of paths to tsv files for stel dimensions and characteristics respectively :param filter_majority_votes: :param stel_char_tsv: :param stel_dim_tsv: :return: """ # read in style dimension task instances to dataframe if s...
') logging.info('Saved single predictions to {}'.format(save_path)) return { "accuracies": accuracy_results_df, "stel_tasks": stel_instances, "single_predictions": prediction_df } def ensure_path_exists(save_path): # https://stackoverflow.com/questions/273192/how-can-i-safely-...
136
136
456
30
106
nlpsoc/STEL
src/eval_style_models.py
Python
read_in_stel_instances
read_in_stel_instances
188
228
188
188
f7b57d76bb9b3ed2daf3b37688d1759555842c7d
bigcode/the-stack
train
db097bb925c8b61b219854a7
train
function
def eval_sim(stel_char_tsv: List[str] = LOCAL_STEL_CHAR_QUAD, stel_dim_tsv: List[str] = LOCAL_STEL_DIM_QUAD, style_objects=STYLE_OBJECTS, output_folder='output/', eval_on_triple=False, filter_majority_votes: bool = True, stel_instances: pd.DataFrame = None, single_predictions_save...
def eval_sim(stel_char_tsv: List[str] = LOCAL_STEL_CHAR_QUAD, stel_dim_tsv: List[str] = LOCAL_STEL_DIM_QUAD, style_objects=STYLE_OBJECTS, output_folder='output/', eval_on_triple=False, filter_majority_votes: bool = True, stel_instances: pd.DataFrame = None, single_predictions_save...
""" running the evaluation of (language) models/methods on the similarity-based STyle EvaLuation Framework (STEL) :param stel_char_tsv: list of paths to pandas dataframes in the expected format :param stel_dim_tsv: list of paths to pandas dataframe in the expected format and majority vote column ...
necessary USESimilarity(), BERTCasedNextSentenceSimilarity(), BERTUncasedNextSentenceSimilarity(), MpnetSentenceBertSimilarity(), ParaMpnetSentenceBertSimilarity(), CasedBertSimilarity(), RobertaSimil...
255
256
1,192
82
173
nlpsoc/STEL
src/eval_style_models.py
Python
eval_sim
eval_sim
61
177
61
64
963418300fa31eaecc8161e2d69c431627c0e342
bigcode/the-stack
train
2a0adfeda37fa580cd572fdc
train
function
@needs_singularity def test_iwdr_permutations_singularity(tmp_path_factory: Any) -> None: misc = tmp_path_factory.mktemp("misc") fifth = str(tmp_path_factory.mktemp("fifth")) sixth = str(tmp_path_factory.mktemp("sixth")) seventh = str(tmp_path_factory.mktemp("seventh")) eighth = str(tmp_path_factory...
@needs_singularity def test_iwdr_permutations_singularity(tmp_path_factory: Any) -> None:
misc = tmp_path_factory.mktemp("misc") fifth = str(tmp_path_factory.mktemp("fifth")) sixth = str(tmp_path_factory.mktemp("sixth")) seventh = str(tmp_path_factory.mktemp("seventh")) eighth = str(tmp_path_factory.mktemp("eighth")) first = misc / "first" first.touch() second = misc / "secon...
ird), "--fourth", str(fourth), "--fifth", fifth, "--sixth", sixth, "--seventh", seventh, "--eighth", eighth, ] ) == 0 ) @needs_s...
82
82
274
26
56
lijiayong/cwltool
tests/test_iwdr.py
Python
test_iwdr_permutations_singularity
test_iwdr_permutations_singularity
179
222
179
180
ddf99d36d61607db0e34b98b7bf3a2f363c4ab74
bigcode/the-stack
train
4dad0c65413e779d257ee262
train
function
def test_iwdr_permutations_readonly(tmp_path_factory: Any) -> None: """Confirm that readonly input files are properly made writable.""" misc = tmp_path_factory.mktemp("misc") fifth = tmp_path_factory.mktemp("fifth") fifth_file = fifth / "bar" fifth_dir = fifth / "foo" fifth_file.touch() fift...
def test_iwdr_permutations_readonly(tmp_path_factory: Any) -> None:
"""Confirm that readonly input files are properly made writable.""" misc = tmp_path_factory.mktemp("misc") fifth = tmp_path_factory.mktemp("fifth") fifth_file = fifth / "bar" fifth_dir = fifth / "foo" fifth_file.touch() fifth_dir.mkdir() sixth = tmp_path_factory.mktemp("sixth") first...
ations.cwl"), "--first", str(first), "--second", str(second), "--third", str(third), "--fourth", str(fourth), "--fifth", fifth, "--sixth", ...
102
102
343
19
83
lijiayong/cwltool
tests/test_iwdr.py
Python
test_iwdr_permutations_readonly
test_iwdr_permutations_readonly
84
128
84
84
683745c709e2656efbf391a834f4dd384201ee8c
bigcode/the-stack
train
abad759666307bf0e2e0544b
train
function
def test_newline_in_entry() -> None: """Files in a InitialWorkingDirectory are created with a newline character.""" factory = Factory() echo = factory.make(get_data("tests/wf/iwdr-entry.cwl")) assert echo(message="hello") == {"out": "CONFIGVAR=hello\n"}
def test_newline_in_entry() -> None:
"""Files in a InitialWorkingDirectory are created with a newline character.""" factory = Factory() echo = factory.make(get_data("tests/wf/iwdr-entry.cwl")) assert echo(message="hello") == {"out": "CONFIGVAR=hello\n"}
WRITE, S_IWGRP, S_IWOTH from typing import Any from cwltool.factory import Factory from cwltool.main import main from .util import get_data, get_main_output, needs_docker, needs_singularity def test_newline_in_entry() -> None:
64
64
66
10
53
lijiayong/cwltool
tests/test_iwdr.py
Python
test_newline_in_entry
test_newline_in_entry
11
15
11
11
4fa7f73d7d591c126db9b2b0a27c7c51ec024205
bigcode/the-stack
train
5e18ff058c244fd328640e42
train
function
@needs_docker def test_iwdr_permutations_inplace(tmp_path_factory: Any) -> None: misc = tmp_path_factory.mktemp("misc") fifth = str(tmp_path_factory.mktemp("fifth")) sixth = str(tmp_path_factory.mktemp("sixth")) seventh = str(tmp_path_factory.mktemp("seventh")) eighth = str(tmp_path_factory.mktemp("...
@needs_docker def test_iwdr_permutations_inplace(tmp_path_factory: Any) -> None:
misc = tmp_path_factory.mktemp("misc") fifth = str(tmp_path_factory.mktemp("fifth")) sixth = str(tmp_path_factory.mktemp("sixth")) seventh = str(tmp_path_factory.mktemp("seventh")) eighth = str(tmp_path_factory.mktemp("eighth")) first = misc / "first" first.touch() second = misc / "secon...
(sixth), ] ) == 0 ) for entry in [first, second, fifth, sixth, fifth_file, fifth_dir]: try: mode = entry.stat().st_mode entry.chmod(mode | S_IWRITE) except PermissionError: pass @needs_docker def test_iwdr_permutations_inplace(tmp_p...
88
88
294
24
63
lijiayong/cwltool
tests/test_iwdr.py
Python
test_iwdr_permutations_inplace
test_iwdr_permutations_inplace
131
176
131
132
f7dfd74aa651588791064dba5853b4576d5f991e
bigcode/the-stack
train
4e4b23868354b3047954ffa9
train
function
@needs_docker def test_directory_literal_with_real_inputs_inside(tmp_path: Path) -> None: """Cope with unmoveable files in the output directory created by Docker+IWDR.""" err_code, _, _ = get_main_output( [ "--out", str(tmp_path), get_data("tests/iwdr_dir_literal_real...
@needs_docker def test_directory_literal_with_real_inputs_inside(tmp_path: Path) -> None:
"""Cope with unmoveable files in the output directory created by Docker+IWDR.""" err_code, _, _ = get_main_output( [ "--out", str(tmp_path), get_data("tests/iwdr_dir_literal_real_file.cwl"), "--example={}".format(get_data("tests/__init__.py")), ] ...
empty file can be created in InitialWorkingDirectory.""" err_code, _, _ = get_main_output([get_data("tests/wf/iwdr-empty.cwl")]) assert err_code == 0 @needs_docker def test_directory_literal_with_real_inputs_inside(tmp_path: Path) -> None:
64
64
105
21
42
lijiayong/cwltool
tests/test_iwdr.py
Python
test_directory_literal_with_real_inputs_inside
test_directory_literal_with_real_inputs_inside
25
36
25
26
f76e2637f60683a5b7cc9a8afdb2728542b0f6a7
bigcode/the-stack
train
dfe7b0df0745b2c4c0fbb326
train
function
@needs_docker def test_empty_file_creation() -> None: """An empty file can be created in InitialWorkingDirectory.""" err_code, _, _ = get_main_output([get_data("tests/wf/iwdr-empty.cwl")]) assert err_code == 0
@needs_docker def test_empty_file_creation() -> None:
"""An empty file can be created in InitialWorkingDirectory.""" err_code, _, _ = get_main_output([get_data("tests/wf/iwdr-empty.cwl")]) assert err_code == 0
Directory are created with a newline character.""" factory = Factory() echo = factory.make(get_data("tests/wf/iwdr-entry.cwl")) assert echo(message="hello") == {"out": "CONFIGVAR=hello\n"} @needs_docker def test_empty_file_creation() -> None:
63
64
60
14
49
lijiayong/cwltool
tests/test_iwdr.py
Python
test_empty_file_creation
test_empty_file_creation
18
22
18
19
d473c510ee8e1fc3572f81625d8d8688858cbc79
bigcode/the-stack
train
0b7965b12d5aaec6f5fa279e
train
function
@needs_singularity def test_iwdr_permutations_singularity_inplace(tmp_path_factory: Any) -> None: misc = tmp_path_factory.mktemp("misc") fifth = str(tmp_path_factory.mktemp("fifth")) sixth = str(tmp_path_factory.mktemp("sixth")) seventh = str(tmp_path_factory.mktemp("seventh")) eighth = str(tmp_path...
@needs_singularity def test_iwdr_permutations_singularity_inplace(tmp_path_factory: Any) -> None:
misc = tmp_path_factory.mktemp("misc") fifth = str(tmp_path_factory.mktemp("fifth")) sixth = str(tmp_path_factory.mktemp("sixth")) seventh = str(tmp_path_factory.mktemp("seventh")) eighth = str(tmp_path_factory.mktemp("eighth")) first = misc / "first" first.touch() second = misc / "secon...
"--third", str(third), "--fourth", str(fourth), "--fifth", fifth, "--sixth", sixth, "--seventh", seventh, "--eighth", eighth, ] ...
90
90
303
28
62
lijiayong/cwltool
tests/test_iwdr.py
Python
test_iwdr_permutations_singularity_inplace
test_iwdr_permutations_singularity_inplace
225
271
225
226
3a873d2af7dc82e617c8ef9600cf29b493389a10
bigcode/the-stack
train
80acc3dc781f537b4bb33806
train
function
@needs_docker def test_iwdr_permutations(tmp_path_factory: Any) -> None: misc = tmp_path_factory.mktemp("misc") fifth = str(tmp_path_factory.mktemp("fifth")) sixth = str(tmp_path_factory.mktemp("sixth")) seventh = str(tmp_path_factory.mktemp("seventh")) eighth = str(tmp_path_factory.mktemp("eighth")...
@needs_docker def test_iwdr_permutations(tmp_path_factory: Any) -> None:
misc = tmp_path_factory.mktemp("misc") fifth = str(tmp_path_factory.mktemp("fifth")) sixth = str(tmp_path_factory.mktemp("sixth")) seventh = str(tmp_path_factory.mktemp("seventh")) eighth = str(tmp_path_factory.mktemp("eighth")) first = misc / "first" first.touch() second = misc / "secon...
get_main_output( [ "--out", str(tmp_path), get_data("tests/iwdr_dir_literal_real_file.cwl"), "--example={}".format(get_data("tests/__init__.py")), ] ) assert err_code == 0 @needs_docker def test_iwdr_permutations(tmp_path_factory: Any) -> None:
79
79
265
22
56
lijiayong/cwltool
tests/test_iwdr.py
Python
test_iwdr_permutations
test_iwdr_permutations
39
81
39
40
7f63b9b4c6502ea349d02b2a06caa215a1644c1e
bigcode/the-stack
train
d74bdbbd0d5b8848defc0fb0
train
class
class RomanNumerals: dic = {"I":"1", "IV":"4", "V":"5", "X":"10", "L":"50", "C":"100", "D":"500", "M":"1000"} print(dic) def to_roman(val): out = "" DicVal = list(RomanNumerals.dic.values()) DicKey = list(RomanNumerals.dic.keys()) while val > 0: if val >= 1000: ...
class RomanNumerals:
dic = {"I":"1", "IV":"4", "V":"5", "X":"10", "L":"50", "C":"100", "D":"500", "M":"1000"} print(dic) def to_roman(val): out = "" DicVal = list(RomanNumerals.dic.values()) DicKey = list(RomanNumerals.dic.keys()) while val > 0: if val >= 1000: tho = ...
class RomanNumerals:
5
142
474
5
0
joanzhu728/Codewar
16_ RomanNumerals.py
Python
RomanNumerals
RomanNumerals
1
52
1
1
d9a0ce07f733d5bd896e8fdfcc7f3746a9531436
bigcode/the-stack
train
0c8c382de34fb37c11c55929
train
class
class ServerStartStopPolicyEnforcementV21(test.TestCase): start_policy = "os_compute_api:servers:start" stop_policy = "os_compute_api:servers:stop" def setUp(self): super(ServerStartStopPolicyEnforcementV21, self).setUp() self.controller = server_v21.ServersController() self.req = f...
class ServerStartStopPolicyEnforcementV21(test.TestCase):
start_policy = "os_compute_api:servers:start" stop_policy = "os_compute_api:servers:stop" def setUp(self): super(ServerStartStopPolicyEnforcementV21, self).setUp() self.controller = server_v21.ServersController() self.req = fakes.HTTPRequest.blank('') self.useFixture(nova_fi...
, body) self.assertIn('is locked', six.text_type(ex)) @mock.patch.object(compute_api.API, 'stop', side_effect=exception.InstanceIsLocked( instance_uuid=uuids.instance)) def test_stop_invalid_state(self, stop_mock): body = dict(start="") ...
256
256
868
13
243
lixiaoy1/nova
nova/tests/unit/api/openstack/compute/test_server_start_stop.py
Python
ServerStartStopPolicyEnforcementV21
ServerStartStopPolicyEnforcementV21
124
218
124
124
ab31a06f20b3ee9452dd29b2233315004d65fee9
bigcode/the-stack
train
cb1af64e533c176689704ec1
train
class
class ServerStartStopTestV21(test.TestCase): def setUp(self): super(ServerStartStopTestV21, self).setUp() self._setup_controller() self.req = fakes.HTTPRequest.blank('') self.useFixture(nova_fixtures.SingleCellSimple()) self.stub_out('nova.db.api.instance_get_by_uuid', ...
class ServerStartStopTestV21(test.TestCase):
def setUp(self): super(ServerStartStopTestV21, self).setUp() self._setup_controller() self.req = fakes.HTTPRequest.blank('') self.useFixture(nova_fixtures.SingleCellSimple()) self.stub_out('nova.db.api.instance_get_by_uuid', fakes.fake_instance_get()) ...
Midokura Japan K.K. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in w...
250
250
836
11
238
lixiaoy1/nova
nova/tests/unit/api/openstack/compute/test_server_start_stop.py
Python
ServerStartStopTestV21
ServerStartStopTestV21
32
121
32
33
3cb826497b9fb903a810a1c06f76120350bdecf4
bigcode/the-stack
train
10cf0f9ff23f445c12ed73ae
train
function
def get_recall(type_list, gold_ne_list): systematic_list, family_list, trivial_list, formura_list,\ abbreviation_list, identifier_list, multiple_list, no_class_list = type_list systematic_correct = 0 systematic_all = 0 family_correct = 0 family_all = 0 trivial_correct = 0 trivial_all = ...
def get_recall(type_list, gold_ne_list):
systematic_list, family_list, trivial_list, formura_list,\ abbreviation_list, identifier_list, multiple_list, no_class_list = type_list systematic_correct = 0 systematic_all = 0 family_correct = 0 family_all = 0 trivial_correct = 0 trivial_all = 0 formura_correct = 0 formura_all...
set(multiple_list), set(no_class_list)] return type_list def extract_gold_ne(ner_output): with open(ner_output, 'r') as r: line_list = [l for l in r] ne_list = [] for line in line_list: splited_list = line.strip().split(' ') if len(splited_list) > 2: name = splite...
255
255
850
11
243
shuu-tatsu/ds_ner
dic_learning/src/type_recall.py
Python
get_recall
get_recall
73
169
73
73
aa5ee9904a7d1449f65afb255414979b356b1066
bigcode/the-stack
train
f95e7fdec1604bd0d10373a2
train
function
def creat_type_dict(chemd_test): systematic_list = [] family_list = [] trivial_list = [] formura_list = [] abbreviation_list = [] identifier_list = [] multiple_list = [] no_class_list = [] with open(chemd_test, 'r') as r: line_list = [l for l in r] for line in line_list:...
def creat_type_dict(chemd_test):
systematic_list = [] family_list = [] trivial_list = [] formura_list = [] abbreviation_list = [] identifier_list = [] multiple_list = [] no_class_list = [] with open(chemd_test, 'r') as r: line_list = [l for l in r] for line in line_list: splited_list = line.stri...
''' dic learningのtype別Recallを算出 ''' def creat_type_dict(chemd_test):
21
88
294
9
12
shuu-tatsu/ds_ner
dic_learning/src/type_recall.py
Python
creat_type_dict
creat_type_dict
6
41
6
6
8d064c4ddbfeae6951fb6a7894d188d2d9290109
bigcode/the-stack
train
db59e58044d2da12390decea
train
function
def main(chemd_test, ner_output): type_list = creat_type_dict(chemd_test) type_name_list = ['SYSTEMATIC', 'FAMILY', 'TRIVIAL', 'FORMULA', 'ABBREVIATION', 'IDENTIFIER', 'MULTIPLE', 'NO CLASS'] for i, type_ne in enumerate(type_list): print('type:{} size:{} sample:{}'.format(type_name_list[i], len(type...
def main(chemd_test, ner_output):
type_list = creat_type_dict(chemd_test) type_name_list = ['SYSTEMATIC', 'FAMILY', 'TRIVIAL', 'FORMULA', 'ABBREVIATION', 'IDENTIFIER', 'MULTIPLE', 'NO CLASS'] for i, type_ne in enumerate(type_list): print('type:{} size:{} sample:{}'.format(type_name_list[i], len(type_ne), list(type_ne)[:10])) ...
}/{} REC:{}'.format(multiple_correct, multiple_all, mul_rec)) noc_rec = no_class_correct / no_class_all print('NO_CLASS :{}/{} REC:{}'.format(no_class_correct, no_class_all, noc_rec)) def main(chemd_test, ner_output):
64
64
155
10
54
shuu-tatsu/ds_ner
dic_learning/src/type_recall.py
Python
main
main
172
185
172
172
cbfaeb47a22a6406db6851993481e59f02e83930
bigcode/the-stack
train
81670adfc92b4b52848c94c5
train
function
def extract_gold_ne(ner_output): with open(ner_output, 'r') as r: line_list = [l for l in r] ne_list = [] for line in line_list: splited_list = line.strip().split(' ') if len(splited_list) > 2: name = splited_list[0] gold = splited_list[1] pred = ...
def extract_gold_ne(ner_output):
with open(ner_output, 'r') as r: line_list = [l for l in r] ne_list = [] for line in line_list: splited_list = line.strip().split(' ') if len(splited_list) > 2: name = splited_list[0] gold = splited_list[1] pred = splited_list[2] if le...
CLASS': no_class_list.append(name) type_list = [set(systematic_list), set(family_list), set(trivial_list), set(formura_list),\ set(abbreviation_list), set(identifier_list), set(multiple_list), set(no_class_list)] return type_list def extract_gold_ne(ner_output):
68
68
229
8
59
shuu-tatsu/ds_ner
dic_learning/src/type_recall.py
Python
extract_gold_ne
extract_gold_ne
44
70
44
44
6b6b22352f4de06bb334df8faf9ec082dcc5eb21
bigcode/the-stack
train
93c57c8fcd845a8e6e9cc652
train
function
def solve_pddl(): plan, cost = solve_from_pddl(DOMAIN_PDDL, PROBLEM_PDDL) print('Plan:', plan) print('Cost:', cost)
def solve_pddl():
plan, cost = solve_from_pddl(DOMAIN_PDDL, PROBLEM_PDDL) print('Plan:', plan) print('Cost:', cost)
BLEM_PDDL = """ (define (problem pb2) (:domain blocksworld) (:objects a b) (:init (on b a) (on-table a) (arm-empty)) (:goal (and (on a b)))) """ ################################################## def solve_pddl():
64
64
39
5
59
suddhu/pddlstream
examples/blocksworld/run_derived.py
Python
solve_pddl
solve_pddl
58
61
58
58
52833e69db47434987f919a77b19fc826fc9dcc9
bigcode/the-stack
train
d30cf55efbca36e6c2edafa7
train
function
def get_problem(): constant_map = {} stream_pddl = None stream_map = {} init = [ ('on-table', 'a'), ('on', 'b', 'a'), ('arm-empty',), ] goal = ('on', 'a', 'b') return DOMAIN_PDDL, constant_map, stream_pddl, stream_map, init, goal
def get_problem():
constant_map = {} stream_pddl = None stream_map = {} init = [ ('on-table', 'a'), ('on', 'b', 'a'), ('arm-empty',), ] goal = ('on', 'a', 'b') return DOMAIN_PDDL, constant_map, stream_pddl, stream_map, init, goal
) (arm-empty)) (:goal (and (on a b)))) """ ################################################## def solve_pddl(): plan, cost = solve_from_pddl(DOMAIN_PDDL, PROBLEM_PDDL) print('Plan:', plan) print('Cost:', cost) ################################################## def get_problem():
64
64
84
4
60
suddhu/pddlstream
examples/blocksworld/run_derived.py
Python
get_problem
get_problem
65
77
65
65
cf8cedbae969cdd6275e273dc09f78ae46ff4085
bigcode/the-stack
train
4506ec7925b3ccfde2f7c5d0
train
function
def solve_pddlstream(focused=True): pddlstream_problem = get_problem() if focused: solution = solve_focused(pddlstream_problem, unit_costs=True) else: #solution = solve_exhaustive(pddlstream_problem, unit_costs=True) solution = solve_incremental(pddlstream_problem, unit_costs=True) ...
def solve_pddlstream(focused=True):
pddlstream_problem = get_problem() if focused: solution = solve_focused(pddlstream_problem, unit_costs=True) else: #solution = solve_exhaustive(pddlstream_problem, unit_costs=True) solution = solve_incremental(pddlstream_problem, unit_costs=True) print_solution(solution)
', 'a'), ('on', 'b', 'a'), ('arm-empty',), ] goal = ('on', 'a', 'b') return DOMAIN_PDDL, constant_map, stream_pddl, stream_map, init, goal def solve_pddlstream(focused=True):
64
64
80
9
54
suddhu/pddlstream
examples/blocksworld/run_derived.py
Python
solve_pddlstream
solve_pddlstream
79
86
79
79
9afb4c19ebf64017fdf7a1b47cfdadb7afb25359
bigcode/the-stack
train
45f9c7cfd38abe7cde8ec69c
train
function
def main(): #solve_pddl() solve_pddlstream()
def main(): #solve_pddl()
solve_pddlstream()
ocused(pddlstream_problem, unit_costs=True) else: #solution = solve_exhaustive(pddlstream_problem, unit_costs=True) solution = solve_incremental(pddlstream_problem, unit_costs=True) print_solution(solution) ################################################## def main(): #solve_pddl()
64
64
15
9
55
suddhu/pddlstream
examples/blocksworld/run_derived.py
Python
main
main
90
92
90
91
e16c67e3fe1460978c5644d492257d66a9107377
bigcode/the-stack
train
acaa7f2d9efd14f6e358630b
train
class
@rfm.simple_test class StreamWithRefTest(rfm.RegressionTest): valid_systems = ['*'] valid_prog_environs = ['gnu'] prebuild_cmds = [ 'wget https://raw.githubusercontent.com/jeffhammond/STREAM/master/stream.c' # noqa: E501 ] build_system = 'SingleSource' sourcepath = 'stream.c' variab...
@rfm.simple_test class StreamWithRefTest(rfm.RegressionTest):
valid_systems = ['*'] valid_prog_environs = ['gnu'] prebuild_cmds = [ 'wget https://raw.githubusercontent.com/jeffhammond/STREAM/master/stream.c' # noqa: E501 ] build_system = 'SingleSource' sourcepath = 'stream.c' variables = { 'OMP_NUM_THREADS': '4', 'OMP_PLACES': ...
# Copyright 2016-2021 Swiss National Supercomputing Centre (CSCS/ETH Zurich) # ReFrame Project Developers. See the top-level LICENSE file for details. # # SPDX-License-Identifier: BSD-3-Clause # rfmdocstart: streamtest3 import reframe as rfm import reframe.utility.sanity as sn @rfm.simple_test class StreamWithRefTest(...
90
139
465
17
72
CLIP-HPC/reframe
tutorials/basics/stream/stream3.py
Python
StreamWithRefTest
StreamWithRefTest
11
61
11
12
8e80768049f8f20886905b05062833b184f47eab
bigcode/the-stack
train
0a960f2fa49becb7d2a76d2a
train
class
class Migration(migrations.Migration): dependencies = [ ('auth', '0001_initial'), ('pages', '__first__'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('contenttypes', '0001_initial'), ('hs_core', '0002_genericresource_resource_type'), ] operations = [...
class Migration(migrations.Migration):
dependencies = [ ('auth', '0001_initial'), ('pages', '__first__'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('contenttypes', '0001_initial'), ('hs_core', '0002_genericresource_resource_type'), ] operations = [ migrations.RenameModel("Generic...
# -*- coding: utf-8 -*- from django.db import models, migrations from django.conf import settings import hs_core.models class Migration(migrations.Migration):
35
64
82
7
27
hydroshare/hydroshare
hs_core/migrations/0003_auto_20150721_1122.py
Python
Migration
Migration
9
21
9
10
0f5eb3c3de81d3664d4490e50a4a70b375bf597b
bigcode/the-stack
train
fa0f13758eb1c9e5800f4929
train
class
class TestTimestampProperty(unittest.TestCase): def setUp(self): pass def tearDown(self): for t in TestModel.all(): t.delete() def test_property(self): start_at = datetime.datetime.now().timestamp() john = TestModel.create() john.name = "john" jo...
class TestTimestampProperty(unittest.TestCase):
def setUp(self): pass def tearDown(self): for t in TestModel.all(): t.delete() def test_property(self): start_at = datetime.datetime.now().timestamp() john = TestModel.create() john.name = "john" john.born_at = start_at self.assertEqual(j...
import unittest import fsglue from tests import setup_env # noqa import datetime class TestModel(fsglue.BaseModel): COLLECTION_PATH = "test" COLLECTION_PATH_PARAMS = [] name = fsglue.StringProperty(required=True) born_at = fsglue.TimestampProperty() created_at = fsglue.TimestampProperty(auto_now...
104
122
409
8
96
g0e/fsglue
tests/property/test_timestamp_property.py
Python
TestTimestampProperty
TestTimestampProperty
17
59
17
17
71f0e5d7ce01a8a48f0731980783e80185728e9f
bigcode/the-stack
train
55e2fbc09c10d86002be5e4c
train
class
class TestModel(fsglue.BaseModel): COLLECTION_PATH = "test" COLLECTION_PATH_PARAMS = [] name = fsglue.StringProperty(required=True) born_at = fsglue.TimestampProperty() created_at = fsglue.TimestampProperty(auto_now_add=True) updated_at = fsglue.TimestampProperty(auto_now=True)
class TestModel(fsglue.BaseModel):
COLLECTION_PATH = "test" COLLECTION_PATH_PARAMS = [] name = fsglue.StringProperty(required=True) born_at = fsglue.TimestampProperty() created_at = fsglue.TimestampProperty(auto_now_add=True) updated_at = fsglue.TimestampProperty(auto_now=True)
import unittest import fsglue from tests import setup_env # noqa import datetime class TestModel(fsglue.BaseModel):
31
64
75
10
20
g0e/fsglue
tests/property/test_timestamp_property.py
Python
TestModel
TestModel
7
14
7
7
41ace7e879d3d4d8b76bf29a2d173903b57e4404
bigcode/the-stack
train
d92f4c9fbe6ad6b6c212c48c
train
function
@app.route("/") def suggestions(): n_suggestions = request.args.get("n_suggestions", 10, int) n = request.args.get("n", 5, int) dict_file = "wordle_answers.txt" if n == 5 else "words.txt" game_str = request.args.get("game", "", str) game = [move.split(":") for move in game_str.split(",")] if game_st...
@app.route("/") def suggestions():
n_suggestions = request.args.get("n_suggestions", 10, int) n = request.args.get("n", 5, int) dict_file = "wordle_answers.txt" if n == 5 else "words.txt" game_str = request.args.get("game", "", str) game = [move.split(":") for move in game_str.split(",")] if game_str else [] if any(len(x) != 2 f...
import string from flask import Flask, request from flask_cors import CORS from solver import WordleSolver app = Flask(__name__) CORS(app) @app.route("/") def suggestions():
41
84
283
6
35
hannesveit/wordle-solver
backend/app.py
Python
suggestions
suggestions
13
41
13
14
1931bb02c617ddd20d8e162dc716c4ae066385aa
bigcode/the-stack
train
7f12ecfbc17c2296eb1e95b2
train
class
class TestKeystoneV3Driver(manager_congress.ScenarioPolicyBase): @classmethod def skip_checks(cls): super(TestKeystoneV3Driver, cls).skip_checks() if not (CONF.network.project_networks_reachable or CONF.network.public_network_id): msg = ('Either project_networks_reac...
class TestKeystoneV3Driver(manager_congress.ScenarioPolicyBase): @classmethod
def skip_checks(cls): super(TestKeystoneV3Driver, cls).skip_checks() if not (CONF.network.project_networks_reachable or CONF.network.public_network_id): msg = ('Either project_networks_reachable must be "true", or ' 'public_network_id must be defined.')...
# Copyright 2014 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requ...
214
256
1,493
19
194
mail2nsrajesh/congress
congress_tempest_tests/tests/scenario/congress_datasources/test_keystonev3.py
Python
TestKeystoneV3Driver
TestKeystoneV3Driver
27
205
27
29
caee7dd39cf071b87b2608261713862ab61d994b
bigcode/the-stack
train
ebb5ff1bc72d825eb160e081
train
class
class SafeFunction(object): """Wrapper that handles the serialization of exception tracebacks. If an exception is triggered when calling the inner function, a copy of the full traceback is captured to make it possible to serialize it so that it can be rendered in a different Python process. """ ...
class SafeFunction(object):
"""Wrapper that handles the serialization of exception tracebacks. If an exception is triggered when calling the inner function, a copy of the full traceback is captured to make it possible to serialize it so that it can be rendered in a different Python process. """ def __init__(self, func): ...
if ensure_ready: self.configure(n_jobs=self.parallel.n_jobs, parallel=self.parallel) class ImmediateResult(object): def __init__(self, batch): # Don't delay the application, to avoid keeping the input # arguments in memory self.results = batch() def get(self): ...
73
73
246
5
67
MarcoMancha/BreastCancerDetector
env/lib/python3.7/site-packages/joblib/_parallel_backends.py
Python
SafeFunction
SafeFunction
588
616
588
588
da567d946a86c7ab53c172499a1be21b9dffe805
bigcode/the-stack
train
423353d292739fff08765222
train
class
class SequentialBackend(ParallelBackendBase): """A ParallelBackend which will execute all batches sequentially. Does not use/create any threading objects, and hence has minimal overhead. Used when n_jobs == 1. """ uses_threads = True supports_sharedmem = True def effective_n_jobs(self, n_...
class SequentialBackend(ParallelBackendBase):
"""A ParallelBackend which will execute all batches sequentially. Does not use/create any threading objects, and hence has minimal overhead. Used when n_jobs == 1. """ uses_threads = True supports_sharedmem = True def effective_n_jobs(self, n_jobs): """Determine the number of jobs...
: var_value = default_n_threads else: var_value = str(explicit_n_threads) env[var] = var_value return env @staticmethod def in_main_thread(): return isinstance(threading.current_thread(), threading._MainThread) class SequentialBackend...
65
65
218
8
57
MarcoMancha/BreastCancerDetector
env/lib/python3.7/site-packages/joblib/_parallel_backends.py
Python
SequentialBackend
SequentialBackend
183
212
183
183
ece827f752f2874c0f817c9a2afe1f04b4c6865d
bigcode/the-stack
train
c89afb3bbd6d685af46e4cbc
train
class
class ThreadingBackend(PoolManagerMixin, ParallelBackendBase): """A ParallelBackend which will use a thread pool to execute batches in. This is a low-overhead backend but it suffers from the Python Global Interpreter Lock if the called function relies a lot on Python objects. Mostly useful when the exe...
class ThreadingBackend(PoolManagerMixin, ParallelBackendBase):
"""A ParallelBackend which will use a thread pool to execute batches in. This is a low-overhead backend but it suffers from the Python Global Interpreter Lock if the called function relies a lot on Python objects. Mostly useful when the execution bottleneck is a compiled extension that explicitly r...
_duration = 0.8 * old_duration + 0.2 * duration self._smoothed_batch_duration = new_duration def reset_batch_stats(self): """Reset batch statistics to default values. This avoids interferences with future jobs. """ self._effective_batch_size = self._DEFAULT_EFFECTIVE_BA...
101
101
337
13
87
MarcoMancha/BreastCancerDetector
env/lib/python3.7/site-packages/joblib/_parallel_backends.py
Python
ThreadingBackend
ThreadingBackend
363
401
363
363
bcd837abb4c7ec6d070b1e5af9efae5e2c32a77e
bigcode/the-stack
train
a89fbf5c43c0b964145afd39
train
class
class LokyBackend(AutoBatchingMixin, ParallelBackendBase): """Managing pool of workers with loky instead of multiprocessing.""" supports_timeout = True supports_inner_max_num_threads = True def configure(self, n_jobs=1, parallel=None, prefer=None, require=None, idle_worker_timeout=30...
class LokyBackend(AutoBatchingMixin, ParallelBackendBase):
"""Managing pool of workers with loky instead of multiprocessing.""" supports_timeout = True supports_inner_max_num_threads = True def configure(self, n_jobs=1, parallel=None, prefer=None, require=None, idle_worker_timeout=300, **memmappingexecutor_args): """Build a process e...
a system that does ' 'not support forking. To use parallel-computing in a ' 'script, you must protect your main loop using "if ' "__name__ == '__main__'" '". Please see the joblib documentation on Parallel ' 'for more information') ...
210
210
701
14
196
MarcoMancha/BreastCancerDetector
env/lib/python3.7/site-packages/joblib/_parallel_backends.py
Python
LokyBackend
LokyBackend
492
575
492
492
2dff2fcb2de5c874f78e1027b7e25f50613f410d
bigcode/the-stack
train
44e9f10b30d7ba4e1e3b0110
train
class
class ParallelBackendBase(with_metaclass(ABCMeta)): """Helper abc which defines all methods a ParallelBackend must implement""" supports_timeout = False supports_inner_max_num_threads = False nesting_level = None def __init__(self, nesting_level=None, inner_max_num_threads=None): self.nest...
class ParallelBackendBase(with_metaclass(ABCMeta)):
"""Helper abc which defines all methods a ParallelBackend must implement""" supports_timeout = False supports_inner_max_num_threads = False nesting_level = None def __init__(self, nesting_level=None, inner_max_num_threads=None): self.nesting_level = nesting_level self.inner_max_num...
""" Backends for embarrassingly parallel code. """ import gc import os import sys import warnings import threading import functools import contextlib from abc import ABCMeta, abstractmethod from .format_stack import format_exc from .my_exceptions import WorkerInterrupt, TransportableException from ._multiprocessing_h...
189
256
1,260
11
177
MarcoMancha/BreastCancerDetector
env/lib/python3.7/site-packages/joblib/_parallel_backends.py
Python
ParallelBackendBase
ParallelBackendBase
30
180
30
30
d2fb870c0b4bfa140c772b54d346aa0d31abf28d
bigcode/the-stack
train
7c0cb12d977ce7b002725b60
train
class
class ImmediateResult(object): def __init__(self, batch): # Don't delay the application, to avoid keeping the input # arguments in memory self.results = batch() def get(self): return self.results
class ImmediateResult(object):
def __init__(self, batch): # Don't delay the application, to avoid keeping the input # arguments in memory self.results = batch() def get(self): return self.results
workers and restart a new one with the same parameters """ self._workers.shutdown(kill_workers=True) delete_folder(self._workers._temp_folder) self._workers = None if ensure_ready: self.configure(n_jobs=self.parallel.n_jobs, parallel=self.parallel) class ImmediateRes...
64
64
49
5
59
MarcoMancha/BreastCancerDetector
env/lib/python3.7/site-packages/joblib/_parallel_backends.py
Python
ImmediateResult
ImmediateResult
578
585
578
578
17fefd1d1727666c9ca48702e03b68462eb7d6fd
bigcode/the-stack
train
6526ff453b7c84aab49cbc52
train
class
class FallbackToBackend(Exception): """Raised when configuration should fallback to another backend""" def __init__(self, backend): self.backend = backend
class FallbackToBackend(Exception):
"""Raised when configuration should fallback to another backend""" def __init__(self, backend): self.backend = backend
_info() text = format_exc(e_type, e_value, e_tb, context=10, tb_offset=1) raise TransportableException(text, e_type) else: # Rely on Python 3 built-in Remote Traceback reporting raise class FallbackToBackend(Ex...
64
64
33
7
56
MarcoMancha/BreastCancerDetector
env/lib/python3.7/site-packages/joblib/_parallel_backends.py
Python
FallbackToBackend
FallbackToBackend
619
623
619
619
d6368d1586a01071cbb89171caf80ff9839d95e1
bigcode/the-stack
train
420e661b14deb5eed6733f83
train
class
class PoolManagerMixin(object): """A helper class for managing pool of workers.""" _pool = None def effective_n_jobs(self, n_jobs): """Determine the number of jobs which are going to run in parallel""" if n_jobs == 0: raise ValueError('n_jobs == 0 in Parallel has no meaning') ...
class PoolManagerMixin(object):
"""A helper class for managing pool of workers.""" _pool = None def effective_n_jobs(self, n_jobs): """Determine the number of jobs which are going to run in parallel""" if n_jobs == 0: raise ValueError('n_jobs == 0 in Parallel has no meaning') elif mp is None or n_jobs...
to be run""" result = ImmediateResult(func) if callback: callback(result) return result def get_nested_backend(self): # import is not top level to avoid cyclic import errors. from .parallel import get_active_backend # SequentialBackend should neither ch...
93
93
311
6
87
MarcoMancha/BreastCancerDetector
env/lib/python3.7/site-packages/joblib/_parallel_backends.py
Python
PoolManagerMixin
PoolManagerMixin
215
253
215
215
f960e7e732dafa333eac2ce7419319640f4cacab
bigcode/the-stack
train
f11f69e1e52524718a3e02d8
train
class
class AutoBatchingMixin(object): """A helper class for automagically batching jobs.""" # In seconds, should be big enough to hide multiprocessing dispatching # overhead. # This settings was found by running benchmarks/bench_auto_batching.py # with various parameters on various platforms. MIN_ID...
class AutoBatchingMixin(object):
"""A helper class for automagically batching jobs.""" # In seconds, should be big enough to hide multiprocessing dispatching # overhead. # This settings was found by running benchmarks/bench_auto_batching.py # with various parameters on various platforms. MIN_IDEAL_BATCH_DURATION = .2 # Sh...
_jobs == 0 in Parallel has no meaning') elif mp is None or n_jobs is None: # multiprocessing is not available or disabled, fallback # to sequential mode return 1 elif n_jobs < 0: n_jobs = max(cpu_count() + 1 + n_jobs, 1) return n_jobs def term...
256
256
1,002
7
249
MarcoMancha/BreastCancerDetector
env/lib/python3.7/site-packages/joblib/_parallel_backends.py
Python
AutoBatchingMixin
AutoBatchingMixin
256
360
256
256
d69050017234dbfa2037114ca32bab8c86340149
bigcode/the-stack
train
a3ef7664eabb0d2b4e2de908
train
class
class MultiprocessingBackend(PoolManagerMixin, AutoBatchingMixin, ParallelBackendBase): """A ParallelBackend which will use a multiprocessing.Pool. Will introduce some communication and memory overhead when exchanging input and output data with the with the worker Python proces...
class MultiprocessingBackend(PoolManagerMixin, AutoBatchingMixin, ParallelBackendBase):
"""A ParallelBackend which will use a multiprocessing.Pool. Will introduce some communication and memory overhead when exchanging input and output data with the with the worker Python processes. However, does not suffer from the Python Global Interpreter Lock. """ # Environment variables to pr...
used as the default backend for nested calls. """ supports_timeout = True uses_threads = True supports_sharedmem = True def configure(self, n_jobs=1, parallel=None, **backend_args): """Build a process or thread pool and return the number of workers""" n_jobs = self.effective_n_job...
215
215
719
19
195
MarcoMancha/BreastCancerDetector
env/lib/python3.7/site-packages/joblib/_parallel_backends.py
Python
MultiprocessingBackend
MultiprocessingBackend
404
489
404
405
a99c7a75d83b6d3a67d4156faa30ec42b446a385
bigcode/the-stack
train
0a5af0e6e4b34e54d6f4cff1
train
function
def apply(): """Apply all MPL settings """ # print(plt.style.available) # plt.style.use('seaborn-paper') plt.style.use('seaborn-notebook') plt.rcParams['figure.max_open_warning'] = 1000 plt.rcParams['figure.figsize'] = (12, 6)
def apply():
"""Apply all MPL settings """ # print(plt.style.available) # plt.style.use('seaborn-paper') plt.style.use('seaborn-notebook') plt.rcParams['figure.max_open_warning'] = 1000 plt.rcParams['figure.figsize'] = (12, 6)
import matplotlib.pyplot as plt def apply():
10
64
73
3
6
Who8MyLunch/PiJuPyPrefs
pijupy/my_matplotlib.py
Python
apply
apply
6
15
6
6
c85bf148b48788078f6b735448768402ab925c6a
bigcode/the-stack
train
a1b6ee47ae6502e985e89c49
train
function
def _get_boolean_value( x: Union[None, bool, str], name: str, default: Optional[bool] = None, ) -> bool: if x is None: return bool(default) if isinstance(x, bool): return x possible_values = {"true": True, "false": False, "1": True, "0": False} try: return possible_va...
def _get_boolean_value( x: Union[None, bool, str], name: str, default: Optional[bool] = None, ) -> bool:
if x is None: return bool(default) if isinstance(x, bool): return x possible_values = {"true": True, "false": False, "1": True, "0": False} try: return possible_values[x.lower()] except KeyError: raise ValueError( "{} is not a valid value for {}. " ...
ured: return import django.apps if not django.apps.apps.ready: django.setup() _blocking_manager.block() def _get_boolean_value( x: Union[None, bool, str], name: str, default: Optional[bool] = None, ) -> bool:
64
64
137
36
28
IslandKnight/pytest-django
pytest_django/plugin.py
Python
_get_boolean_value
_get_boolean_value
239
255
239
243
c6530e92fcde490660cc95b7ed35aec0bdb7f495
bigcode/the-stack
train
d9884610c3601a7bd3d59586
train
function
@contextlib.contextmanager def _handle_import_error(extra_message: str) -> Generator[None, None, None]: try: yield except ImportError as e: django_msg = (e.args[0] + "\n\n") if e.args else "" msg = django_msg + extra_message raise ImportError(msg)
@contextlib.contextmanager def _handle_import_error(extra_message: str) -> Generator[None, None, None]:
try: yield except ImportError as e: django_msg = (e.args[0] + "\n\n") if e.args else "" msg = django_msg + extra_message raise ImportError(msg)
) PROJECT_SCAN_DISABLED = ( "pytest-django did not search for Django " "projects since it is disabled in the configuration " '("django_find_project = false")' ) @contextlib.contextmanager def _handle_import_error(extra_message: str) -> Generator[None, None, None]:
64
64
73
25
39
IslandKnight/pytest-django
pytest_django/plugin.py
Python
_handle_import_error
_handle_import_error
174
181
174
175
91ce0a1d2b38198706a18570ab057a87fddf9afe
bigcode/the-stack
train
1d537027819723a872014d48
train
function
@pytest.fixture(scope="function") def django_mail_dnsname() -> str: return "fake-tests.example.com"
@pytest.fixture(scope="function") def django_mail_dnsname() -> str:
return "fake-tests.example.com"
="function") def django_mail_patch_dns( monkeypatch, django_mail_dnsname: str, ) -> None: from django.core import mail monkeypatch.setattr(mail.message, "DNS_NAME", django_mail_dnsname) @pytest.fixture(scope="function") def django_mail_dnsname() -> str:
64
64
23
15
49
IslandKnight/pytest-django
pytest_django/plugin.py
Python
django_mail_dnsname
django_mail_dnsname
535
537
535
536
4dd9b27f2b81b5af5849a00f43ca5c67e9efcbd1
bigcode/the-stack
train
7e9e01ca1a07e0da63c9fe13
train
class
class _DatabaseBlockerContextManager: def __init__(self, db_blocker) -> None: self._db_blocker = db_blocker def __enter__(self) -> None: pass def __exit__(self, exc_type, exc_value, traceback) -> None: self._db_blocker.restore()
class _DatabaseBlockerContextManager:
def __init__(self, db_blocker) -> None: self._db_blocker = db_blocker def __enter__(self) -> None: pass def __exit__(self, exc_type, exc_value, traceback) -> None: self._db_blocker.restore()
_settings_is_configured(): from django.conf import settings as dj_settings if "django.contrib.sites" in dj_settings.INSTALLED_APPS: from django.contrib.sites.models import Site Site.objects.clear_cache() # ############### Helper Functions ################ class _DatabaseBlock...
64
64
72
8
55
IslandKnight/pytest-django
pytest_django/plugin.py
Python
_DatabaseBlockerContextManager
_DatabaseBlockerContextManager
675
683
675
675
1dfd3867f60bd16bccb4897fb1b6a3e3eec646ca
bigcode/the-stack
train
367025969bc62666de853e67
train
function
@pytest.hookimpl(trylast=True) def pytest_configure() -> None: # Allow Django settings to be configured in a user pytest_configure call, # but make sure we call django.setup() _setup_django()
@pytest.hookimpl(trylast=True) def pytest_configure() -> None: # Allow Django settings to be configured in a user pytest_configure call, # but make sure we call django.setup()
_setup_django()
report_header: return ["django: " + ", ".join(_report_header)] return None @pytest.hookimpl(trylast=True) def pytest_configure() -> None: # Allow Django settings to be configured in a user pytest_configure call, # but make sure we call django.setup()
64
64
49
43
20
IslandKnight/pytest-django
pytest_django/plugin.py
Python
pytest_configure
pytest_configure
358
362
358
361
47311d5635c00cfd61c0ae738a45b5a5ee865f7b
bigcode/the-stack
train
01b85d9983eecb6bbe66ed87
train
function
@pytest.hookimpl() def pytest_addoption(parser) -> None: group = parser.getgroup("django") group.addoption( "--reuse-db", action="store_true", dest="reuse_db", default=False, help="Re-use the testing database if it already exists, " "and do not remove it when the ...
@pytest.hookimpl() def pytest_addoption(parser) -> None:
group = parser.getgroup("django") group.addoption( "--reuse-db", action="store_true", dest="reuse_db", default=False, help="Re-use the testing database if it already exists, " "and do not remove it when the test finishes.", ) group.addoption( "--cr...
import async_rf # noqa from .fixtures import rf # noqa from .fixtures import settings # noqa from .fixtures import transactional_db # noqa from .lazy_django import django_settings_is_configured, skip_if_no_django TYPE_CHECKING = False if TYPE_CHECKING: from typing import ContextManager, NoReturn import ...
155
155
519
14
140
IslandKnight/pytest-django
pytest_django/plugin.py
Python
pytest_addoption
pytest_addoption
64
150
64
65
f493a747ea4e03f2063f4f588ee26c75525d405b
bigcode/the-stack
train
d782b4e62ec8a8a5f8a0f275
train
function
def _add_django_project_to_path(args) -> str: def is_django_project(path: pathlib.Path) -> bool: try: return path.is_dir() and (path / "manage.py").exists() except OSError: return False def arg_to_path(arg: str) -> pathlib.Path: # Test classes or functions can be...
def _add_django_project_to_path(args) -> str:
def is_django_project(path: pathlib.Path) -> bool: try: return path.is_dir() and (path / "manage.py").exists() except OSError: return False def arg_to_path(arg: str) -> pathlib.Path: # Test classes or functions can be appended to paths separated by :: arg...
def _handle_import_error(extra_message: str) -> Generator[None, None, None]: try: yield except ImportError as e: django_msg = (e.args[0] + "\n\n") if e.args else "" msg = django_msg + extra_message raise ImportError(msg) def _add_django_project_to_path(args) -> str:
80
80
268
13
67
IslandKnight/pytest-django
pytest_django/plugin.py
Python
_add_django_project_to_path
_add_django_project_to_path
184
218
184
184
4fa97df9f20234de30a2860d81e58a837fdaef71
bigcode/the-stack
train
20e26bab036ae5326e405c5a
train
function
@pytest.fixture(autouse=True) def _template_string_if_invalid_marker(request) -> None: """Apply the @pytest.mark.ignore_template_errors marker, internal to pytest-django.""" marker = request.keywords.get("ignore_template_errors", None) if os.environ.get(INVALID_TEMPLATE_VARS_ENV, "false") == "true": ...
@pytest.fixture(autouse=True) def _template_string_if_invalid_marker(request) -> None:
"""Apply the @pytest.mark.ignore_template_errors marker, internal to pytest-django.""" marker = request.keywords.get("ignore_template_errors", None) if os.environ.get(INVALID_TEMPLATE_VARS_ENV, "false") == "true": if marker and django_settings_is_configured(): from django.conf impor...
_settings_is_configured() ): from django.conf import settings as dj_settings if dj_settings.TEMPLATES: dj_settings.TEMPLATES[0]["OPTIONS"]["string_if_invalid"] = InvalidVarException() @pytest.fixture(autouse=True) def _template_string_if_invalid_marker(request) -> None:
64
64
118
19
45
IslandKnight/pytest-django
pytest_django/plugin.py
Python
_template_string_if_invalid_marker
_template_string_if_invalid_marker
644
654
644
645
825a1da3148ad75ab9d4c3abcd5527b3c95b41ed
bigcode/the-stack
train
157f056cc20019bf2c9d5240
train
function
@pytest.fixture(autouse=True) def _django_db_marker(request) -> None: """Implement the django_db marker, internal to pytest-django. This will dynamically request the ``db``, ``transactional_db`` or ``django_db_reset_sequences`` fixtures as required by the django_db marker. """ marker = request.node...
@pytest.fixture(autouse=True) def _django_db_marker(request) -> None:
"""Implement the django_db marker, internal to pytest-django. This will dynamically request the ``db``, ``transactional_db`` or ``django_db_reset_sequences`` fixtures as required by the django_db marker. """ marker = request.node.get_closest_marker("django_db") if marker: transaction, r...
() to temporarily enable database access. This is an advanced feature that is meant to be used to implement database fixtures. """ if not django_settings_is_configured(): return None return _blocking_manager @pytest.fixture(autouse=True) def _django_db_marker(request) -> None:
64
64
165
17
46
IslandKnight/pytest-django
pytest_django/plugin.py
Python
_django_db_marker
_django_db_marker
450
469
450
451
ef656df11afb8150e57c5aa2399570a95bbb07ef
bigcode/the-stack
train
6a78feaa8ebf75e8fc3f3338
train
function
@pytest.fixture(scope="function", autouse=True) def _dj_autoclear_mailbox() -> None: if not django_settings_is_configured(): return from django.core import mail del mail.outbox[:]
@pytest.fixture(scope="function", autouse=True) def _dj_autoclear_mailbox() -> None:
if not django_settings_is_configured(): return from django.core import mail del mail.outbox[:]
fixturevalue("django_db_setup") with django_db_blocker.unblock(): yield finally: TestCaseFunction.runtest = original_runtest # type: ignore[assignment] @pytest.fixture(scope="function", autouse=True) def _dj_autoclear_mailbox() -> None:
64
64
48
22
42
IslandKnight/pytest-django
pytest_django/plugin.py
Python
_dj_autoclear_mailbox
_dj_autoclear_mailbox
502
509
502
503
1e1124aa662ba891328f2241444c12bcb21e2283
bigcode/the-stack
train
1af3ff530052f1ad503ba27b
train
function
@pytest.fixture(autouse=True, scope="function") def _django_set_urlconf(request) -> None: """Apply the @pytest.mark.urls marker, internal to pytest-django.""" marker = request.node.get_closest_marker("urls") if marker: skip_if_no_django() import django.conf from django.urls import cl...
@pytest.fixture(autouse=True, scope="function") def _django_set_urlconf(request) -> None:
"""Apply the @pytest.mark.urls marker, internal to pytest-django.""" marker = request.node.get_closest_marker("urls") if marker: skip_if_no_django() import django.conf from django.urls import clear_url_caches, set_urlconf urls = validate_urls(marker) original_urlconf...
mail monkeypatch.setattr(mail.message, "DNS_NAME", django_mail_dnsname) @pytest.fixture(scope="function") def django_mail_dnsname() -> str: return "fake-tests.example.com" @pytest.fixture(autouse=True, scope="function") def _django_set_urlconf(request) -> None:
64
64
192
22
42
IslandKnight/pytest-django
pytest_django/plugin.py
Python
_django_set_urlconf
_django_set_urlconf
540
562
540
541
a3157ab71173663536fb41fe1d94eb076911ac56
bigcode/the-stack
train
c93c25331c90a2fa1ea8bc44
train
function
@pytest.fixture(autouse=True, scope="function") def _django_clear_site_cache() -> None: """Clears ``django.contrib.sites.models.SITE_CACHE`` to avoid unexpected behavior with cached site objects. """ if django_settings_is_configured(): from django.conf import settings as dj_settings if...
@pytest.fixture(autouse=True, scope="function") def _django_clear_site_cache() -> None:
"""Clears ``django.contrib.sites.models.SITE_CACHE`` to avoid unexpected behavior with cached site objects. """ if django_settings_is_configured(): from django.conf import settings as dj_settings if "django.contrib.sites" in dj_settings.INSTALLED_APPS: from django.contrib.s...
django_settings_is_configured(): from django.conf import settings as dj_settings if dj_settings.TEMPLATES: dj_settings.TEMPLATES[0]["OPTIONS"]["string_if_invalid"].fail = False @pytest.fixture(autouse=True, scope="function") def _django_clear_site_cache() -> None:
64
64
99
21
42
IslandKnight/pytest-django
pytest_django/plugin.py
Python
_django_clear_site_cache
_django_clear_site_cache
657
669
657
658
7fb6e2f8b86e7e6ad9dbb2ac3c3dbaf6a058da05
bigcode/the-stack
train
9e657efc3b5a441d775bc4a3
train
function
@pytest.hookimpl() def pytest_report_header() -> Optional[List[str]]: if _report_header: return ["django: " + ", ".join(_report_header)] return None
@pytest.hookimpl() def pytest_report_header() -> Optional[List[str]]:
if _report_header: return ["django: " + ", ".join(_report_header)] return None
# ImproperlyConfigured if settings cannot be loaded. from django.conf import settings as dj_settings with _handle_import_error(_django_project_scan_outcome): dj_settings.DATABASES _setup_django() @pytest.hookimpl() def pytest_report_header() -> Optional[List[str]]:
64
64
39
15
49
IslandKnight/pytest-django
pytest_django/plugin.py
Python
pytest_report_header
pytest_report_header
351
355
351
352
4687f347d4fb4fb732481ab4a85facc6873a6d0c
bigcode/the-stack
train
f9e48d56485ff3c4f931fea5
train
function
@pytest.hookimpl() def pytest_load_initial_conftests( early_config, parser, args: List[str], ) -> None: # Register the marks early_config.addinivalue_line( "markers", "django_db(transaction=False, reset_sequences=False, databases=None): " "Mark the test as using the Django te...
@pytest.hookimpl() def pytest_load_initial_conftests( early_config, parser, args: List[str], ) -> None: # Register the marks
early_config.addinivalue_line( "markers", "django_db(transaction=False, reset_sequences=False, databases=None): " "Mark the test as using the Django test database. " "The *transaction* argument allows you to use real transactions " "in the test like Django's TransactionTestC...
settings are not properly configured. if not django.conf.settings.configured: return import django.apps if not django.apps.apps.ready: django.setup() _blocking_manager.block() def _get_boolean_value( x: Union[None, bool, str], name: str, default: Optional[bool] = None, ...
214
214
715
36
178
IslandKnight/pytest-django
pytest_django/plugin.py
Python
pytest_load_initial_conftests
pytest_load_initial_conftests
258
348
258
264
083bcb5eb97adbe6df25f9665393fcf3be3e6491
bigcode/the-stack
train
535f2acb5c5696cb7e933ab4
train
class
class _DatabaseBlocker: """Manager for django.db.backends.base.base.BaseDatabaseWrapper. This is the object returned by django_db_blocker. """ def __init__(self): self._history = [] self._real_ensure_connection = None @property def _dj_db_wrapper(self) -> "django.db.backends.b...
class _DatabaseBlocker:
"""Manager for django.db.backends.base.base.BaseDatabaseWrapper. This is the object returned by django_db_blocker. """ def __init__(self): self._history = [] self._real_ensure_connection = None @property def _dj_db_wrapper(self) -> "django.db.backends.base.base.BaseDatabaseWra...
.sites" in dj_settings.INSTALLED_APPS: from django.contrib.sites.models import Site Site.objects.clear_cache() # ############### Helper Functions ################ class _DatabaseBlockerContextManager: def __init__(self, db_blocker) -> None: self._db_blocker = db_blocker def...
114
114
382
6
108
IslandKnight/pytest-django
pytest_django/plugin.py
Python
_DatabaseBlocker
_DatabaseBlocker
686
732
686
686
b0ef4ca489221a9fe8caea04c12a9391ecb51e91
bigcode/the-stack
train
88ca6a9cac3aac0a245f6147
train
function
def validate_urls(marker) -> List[str]: """Validate the urls marker. It checks the signature and creates the `urls` attribute on the marker which will have the correct value. """ def apifun(urls: List[str]) -> List[str]: return urls return apifun(*marker.args, **marker.kwargs)
def validate_urls(marker) -> List[str]:
"""Validate the urls marker. It checks the signature and creates the `urls` attribute on the marker which will have the correct value. """ def apifun(urls: List[str]) -> List[str]: return urls return apifun(*marker.args, **marker.kwargs)
bool = False, reset_sequences: bool = False, databases: "_DjangoDbDatabases" = None, ) -> "_DjangoDb": return transaction, reset_sequences, databases return apifun(*marker.args, **marker.kwargs) def validate_urls(marker) -> List[str]:
64
64
73
9
55
IslandKnight/pytest-django
pytest_django/plugin.py
Python
validate_urls
validate_urls
758
768
758
758
f4da7e014ee3c689eaf68424ea44d8d5f5e9214d
bigcode/the-stack
train
66b0962e52dfff459c15a396
train
function
@pytest.fixture(autouse=True, scope="session") def django_test_environment(request) -> None: """ Ensure that Django is loaded and has its testing environment setup. XXX It is a little dodgy that this is an autouse fixture. Perhaps an email fixture should be requested in order to be able to ...
@pytest.fixture(autouse=True, scope="session") def django_test_environment(request) -> None:
""" Ensure that Django is loaded and has its testing environment setup. XXX It is a little dodgy that this is an autouse fixture. Perhaps an email fixture should be requested in order to be able to use the Django email machinery just like you need to request a db fixture for access...
fixtures: return 1 if transaction is False: return 0 if "db" in fixtures: return 0 return 2 items.sort(key=get_order_number) @pytest.fixture(autouse=True, scope="session") def django_test_environment(request) -> None:
64
64
213
20
44
IslandKnight/pytest-django
pytest_django/plugin.py
Python
django_test_environment
django_test_environment
404
427
404
405
7b5b920e3d2e05f185a844a626c111bbef44ca30
bigcode/the-stack
train
d72c2b05d20d65ad9d2ed5dc
train
function
@pytest.fixture(scope="function") def django_mail_patch_dns( monkeypatch, django_mail_dnsname: str, ) -> None: from django.core import mail monkeypatch.setattr(mail.message, "DNS_NAME", django_mail_dnsname)
@pytest.fixture(scope="function") def django_mail_patch_dns( monkeypatch, django_mail_dnsname: str, ) -> None:
from django.core import mail monkeypatch.setattr(mail.message, "DNS_NAME", django_mail_dnsname)
Optional[List[django.core.mail.EmailMessage]]": if not django_settings_is_configured(): return None from django.core import mail return mail.outbox @pytest.fixture(scope="function") def django_mail_patch_dns( monkeypatch, django_mail_dnsname: str, ) -> None:
64
64
52
28
35
IslandKnight/pytest-django
pytest_django/plugin.py
Python
django_mail_patch_dns
django_mail_patch_dns
525
532
525
529
25515363056773c28592b58098a3b5a78994e8fb
bigcode/the-stack
train
e34134666b88933afeb46be7
train
function
@pytest.hookimpl(tryfirst=True) def pytest_collection_modifyitems(items: List[pytest.Item]) -> None: # If Django is not configured we don't need to bother if not django_settings_is_configured(): return from django.test import TestCase, TransactionTestCase def get_order_number(test: pytest.Item...
@pytest.hookimpl(tryfirst=True) def pytest_collection_modifyitems(items: List[pytest.Item]) -> None: # If Django is not configured we don't need to bother
if not django_settings_is_configured(): return from django.test import TestCase, TransactionTestCase def get_order_number(test: pytest.Item) -> int: test_cls = getattr(test, "cls", None) if test_cls: # Beware, TestCase is a subclass of TransactionTestCase if...
_configure() -> None: # Allow Django settings to be configured in a user pytest_configure call, # but make sure we call django.setup() _setup_django() @pytest.hookimpl(tryfirst=True) def pytest_collection_modifyitems(items: List[pytest.Item]) -> None: # If Django is not configured we don't need to bothe...
75
75
253
37
38
IslandKnight/pytest-django
pytest_django/plugin.py
Python
pytest_collection_modifyitems
pytest_collection_modifyitems
365
401
365
367
7d0a63eeef01d7476d09e9c1da4555cf898f8f67
bigcode/the-stack
train
73b95056c022d351d51e0bdf
train
function
@pytest.fixture(autouse=True, scope="session") def _fail_for_invalid_template_variable(): """Fixture that fails for invalid variables in templates. This fixture will fail each test that uses django template rendering should a template contain an invalid template variable. The fail message will include ...
@pytest.fixture(autouse=True, scope="session") def _fail_for_invalid_template_variable():
"""Fixture that fails for invalid variables in templates. This fixture will fail each test that uses django template rendering should a template contain an invalid template variable. The fail message will include the name of the invalid variable and in most cases the template name. It does not...
jango.""" marker = request.node.get_closest_marker("urls") if marker: skip_if_no_django() import django.conf from django.urls import clear_url_caches, set_urlconf urls = validate_urls(marker) original_urlconf = django.conf.settings.ROOT_URLCONF django.conf.settin...
175
175
585
19
156
IslandKnight/pytest-django
pytest_django/plugin.py
Python
_fail_for_invalid_template_variable
_fail_for_invalid_template_variable
565
641
565
566
a77b12d4499651672c1a57094f2d4ec8e85eb65f
bigcode/the-stack
train
ec9c7ef3d1a3df7854d424af
train
function
@pytest.fixture(scope="session") def django_db_blocker() -> "Optional[_DatabaseBlocker]": """Wrapper around Django's database access. This object can be used to re-enable database access. This fixture is used internally in pytest-django to build the other fixtures and can be used for special database ...
@pytest.fixture(scope="session") def django_db_blocker() -> "Optional[_DatabaseBlocker]":
"""Wrapper around Django's database access. This object can be used to re-enable database access. This fixture is used internally in pytest-django to build the other fixtures and can be used for special database handling. The object is a context manager and provides the methods .unblock()/.bl...
debug = None else: debug = _get_boolean_value(debug_ini, "django_debug_mode", False) setup_test_environment(debug=debug) request.addfinalizer(teardown_test_environment) @pytest.fixture(scope="session") def django_db_blocker() -> "Optional[_DatabaseBlocker]":
64
64
140
21
43
IslandKnight/pytest-django
pytest_django/plugin.py
Python
django_db_blocker
django_db_blocker
430
447
430
431
c1c1813d008b9e6683d1a3c43c7d2a90ef5d580c
bigcode/the-stack
train
6ca90e3888a22fff9a602ff8
train
function
def _setup_django() -> None: if "django" not in sys.modules: return import django.conf # Avoid force-loading Django when settings are not properly configured. if not django.conf.settings.configured: return import django.apps if not django.apps.apps.ready: django.setup...
def _setup_django() -> None:
if "django" not in sys.modules: return import django.conf # Avoid force-loading Django when settings are not properly configured. if not django.conf.settings.configured: return import django.apps if not django.apps.apps.ready: django.setup() _blocking_manager.blo...
is_django_project(parent): return parent return None project_dir = find_django_path(args) if project_dir: sys.path.insert(0, str(project_dir.absolute())) return PROJECT_FOUND % project_dir return PROJECT_NOT_FOUND def _setup_django() -> None:
64
64
75
9
54
IslandKnight/pytest-django
pytest_django/plugin.py
Python
_setup_django
_setup_django
221
236
221
221
11348f7088e155cddc40cdc838edfd80752d8ad0
bigcode/the-stack
train
53913751b7712432e4f2a463
train
function
@pytest.fixture(scope="function") def mailoutbox( django_mail_patch_dns: None, _dj_autoclear_mailbox: None, ) -> "Optional[List[django.core.mail.EmailMessage]]": if not django_settings_is_configured(): return None from django.core import mail return mail.outbox
@pytest.fixture(scope="function") def mailoutbox( django_mail_patch_dns: None, _dj_autoclear_mailbox: None, ) -> "Optional[List[django.core.mail.EmailMessage]]":
if not django_settings_is_configured(): return None from django.core import mail return mail.outbox
_is_configured(): return from django.core import mail del mail.outbox[:] @pytest.fixture(scope="function") def mailoutbox( django_mail_patch_dns: None, _dj_autoclear_mailbox: None, ) -> "Optional[List[django.core.mail.EmailMessage]]":
64
64
69
43
20
IslandKnight/pytest-django
pytest_django/plugin.py
Python
mailoutbox
mailoutbox
512
522
512
516
ccd716f3bad6f90ab4db15a39ac7ba7f2fa026f6
bigcode/the-stack
train
fafd1aa106f0fd99438e74fa
train
function
@pytest.fixture(autouse=True, scope="class") def _django_setup_unittest( request, django_db_blocker: "_DatabaseBlocker", ) -> Generator[None, None, None]: """Setup a django unittest, internal to pytest-django.""" if not django_settings_is_configured() or not is_django_unittest(request): yield ...
@pytest.fixture(autouse=True, scope="class") def _django_setup_unittest( request, django_db_blocker: "_DatabaseBlocker", ) -> Generator[None, None, None]:
"""Setup a django unittest, internal to pytest-django.""" if not django_settings_is_configured() or not is_django_unittest(request): yield return # Fix/patch pytest. # Before pytest 5.4: https://github.com/pytest-dev/pytest/issues/5991 # After pytest 5.4: https://github.com/pytest-d...
value("django_db_reset_sequences") elif transaction: request.getfixturevalue("transactional_db") else: request.getfixturevalue("db") @pytest.fixture(autouse=True, scope="class") def _django_setup_unittest( request, django_db_blocker: "_DatabaseBlocker", ) -> Generator[Non...
74
74
248
42
32
IslandKnight/pytest-django
pytest_django/plugin.py
Python
_django_setup_unittest
_django_setup_unittest
472
499
472
476
7c03a531eb1b280b73ab3645bbb4397c05efd5c3
bigcode/the-stack
train
933a5d172c969f911d7b57f2
train
function
def validate_django_db(marker) -> "_DjangoDb": """Validate the django_db marker. It checks the signature and creates the ``transaction``, ``reset_sequences`` and ``databases`` attributes on the marker which will have the correct values. A sequence reset is only allowed when combined with a transac...
def validate_django_db(marker) -> "_DjangoDb":
"""Validate the django_db marker. It checks the signature and creates the ``transaction``, ``reset_sequences`` and ``databases`` attributes on the marker which will have the correct values. A sequence reset is only allowed when combined with a transaction. """ def apifun( transact...
_db_wrapper.ensure_connection = self._blocking_wrapper return _DatabaseBlockerContextManager(self) def restore(self) -> None: self._dj_db_wrapper.ensure_connection = self._history.pop() _blocking_manager = _DatabaseBlocker() def validate_django_db(marker) -> "_DjangoDb":
64
64
134
13
51
IslandKnight/pytest-django
pytest_django/plugin.py
Python
validate_django_db
validate_django_db
738
755
738
738
1d0872568f36a452008412b0eaaa667074c20259
bigcode/the-stack
train
b689bb59911dfb946ff7a741
train
class
class UnknownTransform(Transform): def __init__(self, source_type: Type, transform: str): self.source_type = source_type self.transform = transform def apply(self, value): raise AttributeError(f"Cannot apply unsupported transform: {self.transform}") def can_transform(self, type_va...
class UnknownTransform(Transform):
def __init__(self, source_type: Type, transform: str): self.source_type = source_type self.transform = transform def apply(self, value): raise AttributeError(f"Cannot apply unsupported transform: {self.transform}") def can_transform(self, type_var) -> bool: # assume the tra...
software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from typing import Union from iceberg.api.types import String...
79
79
264
6
72
Pooja0509/iceberg
python_legacy/iceberg/api/transforms/unknown_transform.py
Python
UnknownTransform
UnknownTransform
25
61
25
26
69e064e3ad789621f40d95734a2f93c28ebead5c
bigcode/the-stack
train
8d45616ab1b421e7b68a5c9d
train
function
def main(): """Examples.""" from time import sleep # Example 1 from time import sleep from random import random def print_n(author, n): """Prints number from 0 to n - 1.""" for i in range(n): sleep(random()) print("[{}]: {}".format(author, i)) ThreadP...
def main():
"""Examples.""" from time import sleep # Example 1 from time import sleep from random import random def print_n(author, n): """Prints number from 0 to n - 1.""" for i in range(n): sleep(random()) print("[{}]: {}".format(author, i)) ThreadPool().add(1,...
key not in self._registry: raise IndexError("Specified key not present in the registry.") return self._registry[key] == TaskState.FAILED def get_result(self, key): """Returns the result of the specified thread.""" if key not in self._registry: raise IndexError("Spec...
84
84
283
3
81
pBouillon/TELECOM_TAN
utils/easy_thread.py
Python
main
main
253
289
253
253
0c0d2bb9bf962f5b8f9bbab7b9fa96a3aa409dbf
bigcode/the-stack
train
a68ea7100c88349781851445
train
class
class ThreadPool(object): """Represents a thread pool, which can accept arbitrary number of threads running at the same time.""" def __init__( self, daemon=DAEMON, debug_level=DEBUG_LEVEL, write_log=print): """Init method.""" super().__init__() self._daemon = daemon ...
class ThreadPool(object):
"""Represents a thread pool, which can accept arbitrary number of threads running at the same time.""" def __init__( self, daemon=DAEMON, debug_level=DEBUG_LEVEL, write_log=print): """Init method.""" super().__init__() self._daemon = daemon self._debug_level = debug_...
_set_result, set_set_result) def get_write_log(self): """write_log getter.""" return self._write_log def set_write_log(self, new_value): """write_log setter.""" raise ValueError("write_log cannot be changed after initialization.") write_log = pr...
256
256
894
5
251
pBouillon/TELECOM_TAN
utils/easy_thread.py
Python
ThreadPool
ThreadPool
130
251
130
130
c6bee032059de907cda73a7ddc0ac512cd00ea25
bigcode/the-stack
train
0ba04eac4c5cfed3a00a05da
train
function
def LOSE_RESULT(value): """Do nothing with the result.""" pass
def LOSE_RESULT(value):
"""Do nothing with the result.""" pass
NOT_STARTED = 0 RUNNING = 1 FAILED = -1 class DebugLevel(IntEnum): """Represents debug levels.""" ERROR = 0 WARNING = 1 INFO = 2 DEBUG_LEVEL = DebugLevel.INFO def LOSE_RESULT(value):
64
64
17
6
57
pBouillon/TELECOM_TAN
utils/easy_thread.py
Python
LOSE_RESULT
LOSE_RESULT
27
29
27
27
9ef1eb688867cbe71ecd5f4c7e968ff867982365
bigcode/the-stack
train
95ddd2df5b1a2725aa9b61f7
train
class
class EasyThread(Thread): """Easy thread instance. Run the specified function with specified args, and output result by calling the specified set_result function.""" def __init__( self, name, func, args, kwargs, debug_level=DEBUG_LEVEL, set_result=LOSE_RESULT, write_log=print): ...
class EasyThread(Thread):
"""Easy thread instance. Run the specified function with specified args, and output result by calling the specified set_result function.""" def __init__( self, name, func, args, kwargs, debug_level=DEBUG_LEVEL, set_result=LOSE_RESULT, write_log=print): """Init method.""" ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Simple way to create basic decorrelated threads with Python 3.""" from threading import Thread from enum import Enum, IntEnum DAEMON = False class TaskState(Enum): """Represents task states.""" NOT_STARTED = 0 RUNNING = 1 FAILED = -1 class DebugLev...
139
200
668
5
133
pBouillon/TELECOM_TAN
utils/easy_thread.py
Python
EasyThread
EasyThread
31
128
31
31
69a63c7c568d0d5f92f050b868ff2a3d8fbe140b
bigcode/the-stack
train
4d61e51f914577a690ff4cc3
train
class
class TaskState(Enum): """Represents task states.""" NOT_STARTED = 0 RUNNING = 1 FAILED = -1
class TaskState(Enum):
"""Represents task states.""" NOT_STARTED = 0 RUNNING = 1 FAILED = -1
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Simple way to create basic decorrelated threads with Python 3.""" from threading import Thread from enum import Enum, IntEnum DAEMON = False class TaskState(Enum):
52
64
32
5
46
pBouillon/TELECOM_TAN
utils/easy_thread.py
Python
TaskState
TaskState
11
16
11
11
59ffb2c677a3d880f781a38fb7756e283ea447f1
bigcode/the-stack
train
e64d961ce3677595b3d14e06
train
class
class DebugLevel(IntEnum): """Represents debug levels.""" ERROR = 0 WARNING = 1 INFO = 2
class DebugLevel(IntEnum):
"""Represents debug levels.""" ERROR = 0 WARNING = 1 INFO = 2
decorrelated threads with Python 3.""" from threading import Thread from enum import Enum, IntEnum DAEMON = False class TaskState(Enum): """Represents task states.""" NOT_STARTED = 0 RUNNING = 1 FAILED = -1 class DebugLevel(IntEnum):
64
64
31
6
57
pBouillon/TELECOM_TAN
utils/easy_thread.py
Python
DebugLevel
DebugLevel
18
23
18
18
c82bd59ff1543a5f29eeb646d1472e8f3864648a
bigcode/the-stack
train
d705873f074188a3449d553b
train
function
def main(): """main function""" sys.stdout.write(banner()) version = "%(prog)s {version}".format(version=udemy.__version__) description = "A cross-platform python based utility to download courses from udemy for personal offline use." parser = argparse.ArgumentParser( description=description...
def main():
"""main function""" sys.stdout.write(banner()) version = "%(prog)s {version}".format(version=udemy.__version__) description = "A cross-platform python based utility to download courses from udemy for personal offline use." parser = argparse.ArgumentParser( description=description, conflict_h...
new_line=True, ) lecture_index = 0 if lecture_number: lecture_index = lecture_number - 1 if lecture_start: lecture_index = lecture_start - 1 if lecture_index < 0: ...
255
256
1,722
3
252
Puyodead1/udemy-dl-drm
udemy-dl.py
Python
main
main
406
671
406
406
c70fadbb05ec9abf423a9d375ab02789ab77a622
bigcode/the-stack
train
8afe9fe43dffe7bc139cacc6
train
class
class Udemy(WebVtt2Srt, ProgressBar): """Udemy is class which implements downloading/lising and all""" def __init__( self, url_or_courses, username="", password="", cookies="", cache_session=False ): self.username = username self.password = password self.cookies = cookies ...
class Udemy(WebVtt2Srt, ProgressBar):
"""Udemy is class which implements downloading/lising and all""" def __init__( self, url_or_courses, username="", password="", cookies="", cache_session=False ): self.username = username self.password = password self.cookies = cookies self._cache_session = cache_sess...
merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWAR...
256
256
2,620
13
243
Puyodead1/udemy-dl-drm
udemy-dl.py
Python
Udemy
Udemy
46
403
46
46
0791570addbd81f15dfda1bdb75718db05178846
bigcode/the-stack
train
7214c4bf9509cea827dfaa19
train
function
def glInitConvolutionBorderModesSUN(): '''Return boolean indicating whether this extension is available''' from OpenGL import extensions return extensions.hasGLExtension( _EXTENSION_NAME )
def glInitConvolutionBorderModesSUN():
'''Return boolean indicating whether this extension is available''' from OpenGL import extensions return extensions.hasGLExtension( _EXTENSION_NAME )
from OpenGL import extensions, wrapper import ctypes from OpenGL.raw.GL import _types, _glgets from OpenGL.raw.GL.SUN.convolution_border_modes import * from OpenGL.raw.GL.SUN.convolution_border_modes import _EXTENSION_NAME def glInitConvolutionBorderModesSUN():
64
64
40
9
54
ShujaKhalid/deep-rl
deep-rl/lib/python2.7/site-packages/OpenGL/GL/SUN/convolution_border_modes.py
Python
glInitConvolutionBorderModesSUN
glInitConvolutionBorderModesSUN
22
25
22
22
26d95ec6ebb19a7e214d493027a44018c0d16ca0
bigcode/the-stack
train
05fe511270f1229786741f4c
train
function
def _create_mapping_tuple(name): return ('~/' + name, LaunchConfiguration(name))
def _create_mapping_tuple(name):
return ('~/' + name, LaunchConfiguration(name))
License for the specific language governing permissions and # limitations under the License. from launch import LaunchDescription from launch.actions import DeclareLaunchArgument from launch.substitutions import LaunchConfiguration from launch_ros.actions import LoadComposableNodes from launch_ros.descriptions import...
64
64
19
7
56
KevinXie86/AutowareArchitectureProposal.iv
control/external_cmd_selector/launch/external_cmd_selector.launch.py
Python
_create_mapping_tuple
_create_mapping_tuple
22
23
22
22
f74fb4d72504405c8812639fd7499d9ca156dac5
bigcode/the-stack
train
2cc5e7958d208f849912f23b
train
function
def generate_launch_description(): arguments = [ # component DeclareLaunchArgument('use_intra_process'), DeclareLaunchArgument('target_container'), # settings DeclareLaunchArgument( 'initial_selector_mode', default_value='local', choices=...
def generate_launch_description():
arguments = [ # component DeclareLaunchArgument('use_intra_process'), DeclareLaunchArgument('target_container'), # settings DeclareLaunchArgument( 'initial_selector_mode', default_value='local', choices=['local', 'remote'] ), ...
# Copyright 2021 Tier IV, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing...
196
223
745
5
191
KevinXie86/AutowareArchitectureProposal.iv
control/external_cmd_selector/launch/external_cmd_selector.launch.py
Python
generate_launch_description
generate_launch_description
26
138
26
27
73df97c7a356c49992bcf03f8d699618b06c5cc7
bigcode/the-stack
train
d3a947760357c88d29eefac2
train
function
def train_model(X_train, y_train, delta_t, optical_flows_train, motion_representations_train, baseline, lr, epochs, tune, print_every = 1): """ MODEL TRAINING PROCEDURE param X_train : the training images of shape (N, 120, 120, 1); to be loaded from memory befo...
def train_model(X_train, y_train, delta_t, optical_flows_train, motion_representations_train, baseline, lr, epochs, tune, print_every = 1):
""" MODEL TRAINING PROCEDURE param X_train : the training images of shape (N, 120, 120, 1); to be loaded from memory before passing in ; type --> numpy array param y_train : the target images of shape (N, 120, 120, 1); to be loaded from memory before passing in ;...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Dec 2 14:03:19 2018 @author: roshanprakash """ import os import numpy as np import tensorflow as tf from dataset_loader import * from encode_decode import * from baseline import * import logging logging.basicConfig(level = logging.INFO) model_logger ...
134
256
1,262
40
94
avaneesh93/frame-prediction
src/train_model.py
Python
train_model
train_model
21
126
21
23
7ca2afd84fd4fb6b19004b44474bb91d19f944d3
bigcode/the-stack
train
3896f627042d80cf6c1816c7
train
class
class ARLSTem(StemmerI): ''' ARLSTem stemmer : a light Arabic Stemming algorithm without any dictionary. Department of Telecommunication & Information Processing. USTHB University, Algiers, Algeria. ARLSTem.stem(token) returns the Arabic stem for the input token. The ARLSTem Stemmer requires tha...
class ARLSTem(StemmerI):
''' ARLSTem stemmer : a light Arabic Stemming algorithm without any dictionary. Department of Telecommunication & Information Processing. USTHB University, Algiers, Algeria. ARLSTem.stem(token) returns the Arabic stem for the input token. The ARLSTem Stemmer requires that all tokens are encoded ...
ainia@gmail.com> # Siham Ouamour # Halim Sayoud # URL: <http://nltk.org/> # For license information, see LICENSE.TXT """ ARLSTem Arabic Stemmer The details about the implementation of this algorithm are described in: K. Abainia, S. Ouamour and H. Sayoud, A Novel Robust ...
256
256
3,082
10
245
TejPatel98/voice_your_professional_email
Boilermake2018/Lib/site-packages/nltk/stem/arlstem.py
Python
ARLSTem
ARLSTem
34
369
34
34
d545b6b53a995828c1315b6774f35fc66153a030
bigcode/the-stack
train
41bb8bae03e5a18970296cd9
train
class
class GenericDFTJob(AtomisticGenericJob): def __init__(self, project, job_name): super(GenericDFTJob, self).__init__(project, job_name) self._generic_input["fix_symmetry"] = True @property def encut(self): return self.plane_wave_cutoff @encut.setter def encut(self, val): ...
class GenericDFTJob(AtomisticGenericJob):
def __init__(self, project, job_name): super(GenericDFTJob, self).__init__(project, job_name) self._generic_input["fix_symmetry"] = True @property def encut(self): return self.plane_wave_cutoff @encut.setter def encut(self, val): self.plane_wave_cutoff = val @p...
# coding: utf-8 # Copyright (c) Max-Planck-Institut für Eisenforschung GmbH - Computational Materials Design (CM) Department # Distributed under the terms of "New BSD License", see the LICENSE file. import numpy as np from pyiron.atomistics.job.atomistic import AtomisticGenericJob import warnings __author__ = "Jan Ja...
180
256
1,978
11
169
ashtonmv/pyiron
pyiron/dft/job/generic.py
Python
GenericDFTJob
GenericDFTJob
21
290
21
21
0a49b2c28982db92f46f7edb51a856d99b69f9cf
bigcode/the-stack
train
4ee62eb0fee833be71ef3eff
train
class
class SnapshotData(DataBase): """A class for openstack snapshot data""" def __init__(self, data): self.data = data['snapshot']
class SnapshotData(DataBase):
"""A class for openstack snapshot data""" def __init__(self, data): self.data = data['snapshot']
# Copyright 2020 Soil, Inc. from soil.openstack.base import DataBase from soil.openstack.base import SourceBase class SnapshotData(DataBase):
33
64
33
6
26
JackDan9/soil
soil/soil/openstack/snapshot.py
Python
SnapshotData
SnapshotData
7
11
7
7
72cf6ca8d2a20e31c09bad1a10d87df0ad11115c
bigcode/the-stack
train
f8d126b2b4e4e406e2c50430
train
class
class Snapshot(SourceBase): """A class for openstack snapshot""" def __init__(self, plugin, source_id): super(Snapshot, self).__init__(plugin, source_id) self._snapshot_obj = None @property def snapshot_obj(self): if self._snapshot_obj is not None: return self._snap...
class Snapshot(SourceBase):
"""A class for openstack snapshot""" def __init__(self, plugin, source_id): super(Snapshot, self).__init__(plugin, source_id) self._snapshot_obj = None @property def snapshot_obj(self): if self._snapshot_obj is not None: return self._snapshot_obj self._snap...
Copyright 2020 Soil, Inc. from soil.openstack.base import DataBase from soil.openstack.base import SourceBase class SnapshotData(DataBase): """A class for openstack snapshot data""" def __init__(self, data): self.data = data['snapshot'] class Snapshot(SourceBase):
64
64
182
5
59
JackDan9/soil
soil/soil/openstack/snapshot.py
Python
Snapshot
Snapshot
14
45
14
14
c6d303aa04bc185989351731a091708b621ddf6d
bigcode/the-stack
train
163361c344d42c4693874596
train
function
def replace_config_vals(rule_body: str) -> str: for k, v in CONFIG_VARS: vregex = v.replace('.', '\\.') rule_body = re.sub(f'\\b{vregex}\\b', f"{{{k}}}", rule_body, flags=re.IGNORECASE) return rule_body
def replace_config_vals(rule_body: str) -> str:
for k, v in CONFIG_VARS: vregex = v.replace('.', '\\.') rule_body = re.sub(f'\\b{vregex}\\b', f"{{{k}}}", rule_body, flags=re.IGNORECASE) return rule_body
them" indent = min(len(x) for x in re.findall('^( *)', text, flags=re.M | re.I)) return text if indent == 0 else re.sub(f'^{" " * indent}', '', text, flags=re.M) def replace_config_vals(rule_body: str) -> str:
64
64
68
12
52
mihirk11/SnowAlert
src/webui/backend/webui/api/__init__.py
Python
replace_config_vals
replace_config_vals
27
31
27
27
63c8d1a4db2bb600c1e0017e92c73168d6e5d6f3
bigcode/the-stack
train
ee1cd9ee7db7132051817881
train
function
@rules_api.route('', methods=['POST']) def create_rule(): if not hmac.compare_digest(request.cookies.get("sid", ""), SECRET): return jsonify(success=False, message="bad sid", rule={}) data = request.get_json() rule_title, rule_type, rule_target, rule_body = data['title'], data['type'], data['target...
@rules_api.route('', methods=['POST']) def create_rule():
if not hmac.compare_digest(request.cookies.get("sid", ""), SECRET): return jsonify(success=False, message="bad sid", rule={}) data = request.get_json() rule_title, rule_type, rule_target, rule_body = data['title'], data['type'], data['target'], data['body'] logger.info(f'Creating rule {rule_tit...
|suppression|definition)$', '', rule['name'], flags=re.I), "target": rule['name'].split('_')[-2].upper(), "type": rule['name'].split('_')[-1].upper(), "body": replace_config_vals(rule['text']), "results": ( list(db.fetch(ctx, f"SELECT *...
136
136
455
13
123
mihirk11/SnowAlert
src/webui/backend/webui/api/__init__.py
Python
create_rule
create_rule
68
110
68
69
d9c1bf47ce5423bfbaf5e45c30a07c63ac194cbb
bigcode/the-stack
train
29abab4f650870bc938f0012
train
function
@rules_api.route('', methods=['GET']) def get_rules(): if not hmac.compare_digest(request.cookies.get("sid", ""), SECRET): return jsonify(rules=[]) rule_type = request.args.get('type', '%').upper() rule_target = request.args.get('target', '%').upper() logger.info(f'Fetching {rule_target}_{rule...
@rules_api.route('', methods=['GET']) def get_rules():
if not hmac.compare_digest(request.cookies.get("sid", ""), SECRET): return jsonify(rules=[]) rule_type = request.args.get('type', '%').upper() rule_target = request.args.get('target', '%').upper() logger.info(f'Fetching {rule_target}_{rule_type} rules...') oauth = json.loads(request.heade...
indent}', '', text, flags=re.M) def replace_config_vals(rule_body: str) -> str: for k, v in CONFIG_VARS: vregex = v.replace('.', '\\.') rule_body = re.sub(f'\\b{vregex}\\b', f"{{{k}}}", rule_body, flags=re.IGNORECASE) return rule_body @rules_api.route('', methods=['GET']) def get_rules():
90
90
302
13
76
mihirk11/SnowAlert
src/webui/backend/webui/api/__init__.py
Python
get_rules
get_rules
34
65
34
35
05726bb4a853a0d42318e9bbdfa1e60ba5634e23
bigcode/the-stack
train
d72b55eeba58093f008ebf4a
train
function
@rules_api.route('/rename', methods=['POST']) def rename_rule(): if not hmac.compare_digest(request.cookies.get("sid", ""), SECRET): return jsonify(success=False, message="bad sid", rule={}) data = request.get_json() rule_title, rule_type, rule_target, new_title = data['title'], data['type'], data[...
@rules_api.route('/rename', methods=['POST']) def rename_rule():
if not hmac.compare_digest(request.cookies.get("sid", ""), SECRET): return jsonify(success=False, message="bad sid", rule={}) data = request.get_json() rule_title, rule_type, rule_target, new_title = data['title'], data['type'], data['target'], data['newTitle'] logger.info(f'Renaming rule {rule...
data: data['savedBody'] = rule_body except snowflake.connector.errors.ProgrammingError as e: return jsonify(success=False, message=e.msg, rule=data) return jsonify(success=True, view_name=view_name, rule=data) @rules_api.route('/rename', methods=['POST']) def rename_rule():
66
66
223
15
51
mihirk11/SnowAlert
src/webui/backend/webui/api/__init__.py
Python
rename_rule
rename_rule
138
158
138
139
c21a33bd647cbe0fa15883582e47976940964a5c
bigcode/the-stack
train
91ada5bd10cb5c39c7e56e44
train
function
def unindent(text): "if beginning and every newline followed by spaces, removes them" indent = min(len(x) for x in re.findall('^( *)', text, flags=re.M | re.I)) return text if indent == 0 else re.sub(f'^{" " * indent}', '', text, flags=re.M)
def unindent(text):
"if beginning and every newline followed by spaces, removes them" indent = min(len(x) for x in re.findall('^( *)', text, flags=re.M | re.I)) return text if indent == 0 else re.sub(f'^{" " * indent}', '', text, flags=re.M)
from runners.config import CONFIG_VARS from runners.helpers import db, dbconfig from flask import Blueprint, request, jsonify import logbook logger = logbook.Logger(__name__) rules_api = Blueprint('rules', __name__) SECRET = os.environ.get("SECRET", "") def unindent(text):
63
64
69
5
58
mihirk11/SnowAlert
src/webui/backend/webui/api/__init__.py
Python
unindent
unindent
21
24
21
21
7fc3903b764b74c6e2b208f34c6771d1cf2f3197
bigcode/the-stack
train
73e58ec70e24695009a55183
train
function
@rules_api.route('/delete', methods=['POST']) def delete_rule(): if not hmac.compare_digest(request.cookies.get("sid", ""), SECRET): return jsonify(success=False, message="bad sid", rule={}) data = request.get_json() rule_title, rule_type, rule_target, rule_body = data['title'], data['type'], data[...
@rules_api.route('/delete', methods=['POST']) def delete_rule():
if not hmac.compare_digest(request.cookies.get("sid", ""), SECRET): return jsonify(success=False, message="bad sid", rule={}) data = request.get_json() rule_title, rule_type, rule_target, rule_body = data['title'], data['type'], data['target'], data['body'] logger.info(f'Deleting rule {rule_tit...
f"SELECT * FROM {view_name};")) if view_name.endswith("_POLICY_DEFINITION") else None ) except snowflake.connector.errors.ProgrammingError as e: return jsonify(success=False, message=e.msg, rule=data) return jsonify(success=True, rule=data) @rules_api.route('/delete', ...
76
76
255
15
61
mihirk11/SnowAlert
src/webui/backend/webui/api/__init__.py
Python
delete_rule
delete_rule
113
135
113
114
7f4978733eac16a8609b9aefde491730d0eb2683
bigcode/the-stack
train
48d54f6c10b0afc64fe37ca2
train
function
@pytest.mark.parametrize("CompoundFormulae", [And, Or, Implies, Bidirectional]) def test_predicate_called(CompoundFormulae): P = Predicate("P", arity=0) with pytest.raises(ValueError): CompoundFormulae(P, P()) with pytest.raises(ValueError): CompoundFormulae(P(), P) with pytest.raises...
@pytest.mark.parametrize("CompoundFormulae", [And, Or, Implies, Bidirectional]) def test_predicate_called(CompoundFormulae):
P = Predicate("P", arity=0) with pytest.raises(ValueError): CompoundFormulae(P, P()) with pytest.raises(ValueError): CompoundFormulae(P(), P) with pytest.raises(ValueError): CompoundFormulae(P, P)
Rights Reserved. # # SPDX-License-Identifier: Apache-2.0 ## import pytest from lnn import Predicate, And, Or, Implies, Bidirectional @pytest.mark.parametrize("CompoundFormulae", [And, Or, Implies, Bidirectional]) def test_predicate_called(CompoundFormulae):
64
64
86
29
34
mikulatomas/LNN
tests/general/test_predicate.py
Python
test_predicate_called
test_predicate_called
12
23
12
13
dd6e0f92f15718d08f80e08e70676e58af25901a
bigcode/the-stack
train