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
f44b71deaf79ee38588ff79b
train
function
def update_questionnaire(questionnaire, post, manager): questionnaire.form_code = post['questionnaire-code'].lower() json_string = post['question-set'] question_set = json.loads(json_string) QuestionnaireBuilder(questionnaire, manager).update_questionnaire_with_questions(question_set) return questio...
def update_questionnaire(questionnaire, post, manager):
questionnaire.form_code = post['questionnaire-code'].lower() json_string = post['question-set'] question_set = json.loads(json_string) QuestionnaireBuilder(questionnaire, manager).update_questionnaire_with_questions(question_set) return questionnaire
QuestionnaireBuilder(questionnaire, manager)\ .update_questionnaire_with_questions(question_set)\ .update_reminder(json.loads(post.get('reminder_and_deadline', '{}')))\ .update_outgoing_sms_enabled_flag(outgoing_sms_enabled) return questionnaire def update_questionnaire(questionnaire, post...
64
64
62
11
52
ICT4H/dcs-web
datawinners/project/wizard_view.py
Python
update_questionnaire
update_questionnaire
68
73
68
68
3a09035f12eb1cbce49d4d3df10720a7144aab6a
bigcode/the-stack
train
aad033b0b55f6f8dd5a40cf3
train
function
def create_questionnaire(post, manager, name, language, reporter_id, question_set_json=None, xform=None, is_open_survey=False, created_using = "DW-DESIGNER"): questionnaire_code = post['questionnaire-code'].lower() datasenders = json.loads(post.get('datasenders', "[]")) question_se...
def create_questionnaire(post, manager, name, language, reporter_id, question_set_json=None, xform=None, is_open_survey=False, created_using = "DW-DESIGNER"):
questionnaire_code = post['questionnaire-code'].lower() datasenders = json.loads(post.get('datasenders', "[]")) question_set = question_set_json if question_set_json else json.loads(post['question-set']) questionnaire = Project(manager, name=name, fields=[], form_code=question...
is_project_exist from datawinners.project.utils import is_quota_reached from mangrove.transport.xforms.xform import create_xform_by_form_id from mangrove.utils.types import is_empty def create_questionnaire(post, manager, name, language, reporter_id, question_set_json=None, xform=None, is_open...
84
84
282
42
41
ICT4H/dcs-web
datawinners/project/wizard_view.py
Python
create_questionnaire
create_questionnaire
38
65
38
40
cb4d900cabb380ec34c3dbf8a03ee59ab3c75f0a
bigcode/the-stack
train
457cb75055a16672179d6b80
train
function
def get_preview_and_instruction_links(): links = { 'sms_preview': reverse("sms_preview"), 'web_preview': reverse("web_preview"), 'smart_phone_preview': reverse("smart_phone_preview"), } return links
def get_preview_and_instruction_links():
links = { 'sms_preview': reverse("sms_preview"), 'web_preview': reverse("web_preview"), 'smart_phone_preview': reverse("smart_phone_preview"), } return links
naire, post, manager): questionnaire.form_code = post['questionnaire-code'].lower() json_string = post['question-set'] question_set = json.loads(json_string) QuestionnaireBuilder(questionnaire, manager).update_questionnaire_with_questions(question_set) return questionnaire def get_preview_and_instru...
64
64
49
7
56
ICT4H/dcs-web
datawinners/project/wizard_view.py
Python
get_preview_and_instruction_links
get_preview_and_instruction_links
76
82
76
76
a235f0bee9e7f8c162b73cb6fe1b6f407276f1f2
bigcode/the-stack
train
17d6160e54bf857f5fc38339
train
function
@login_required @session_not_expired @csrf_exempt @is_not_expired def get_templates(request): library = QuestionnaireLibrary() return HttpResponse(json.dumps({'categories': library.get_template_groupings(request.LANGUAGE_CODE)}), content_type='application/json')
@login_required @session_not_expired @csrf_exempt @is_not_expired def get_templates(request):
library = QuestionnaireLibrary() return HttpResponse(json.dumps({'categories': library.get_template_groupings(request.LANGUAGE_CODE)}), content_type='application/json')
{ 'sms_preview': reverse("sms_preview"), 'web_preview': reverse("web_preview"), 'smart_phone_preview': reverse("smart_phone_preview"), } return links @login_required @session_not_expired @csrf_exempt @is_not_expired def get_templates(request):
64
64
58
25
38
ICT4H/dcs-web
datawinners/project/wizard_view.py
Python
get_templates
get_templates
85
92
85
89
85b911b963196ea7c832f9e3bb59e20b1faa2eae
bigcode/the-stack
train
70d4dbef147c361faa79fede
train
function
@login_required @session_not_expired @is_datasender @is_not_expired @is_project_exist @csrf_exempt def reminder_settings(request, project_id): dbm = get_database_manager(request.user) questionnaire = Project.get(dbm, project_id) dashboard_page = settings.HOME_PAGE + "?deleted=true" if questionnaire.is_v...
@login_required @session_not_expired @is_datasender @is_not_expired @is_project_exist @csrf_exempt def reminder_settings(request, project_id):
dbm = get_database_manager(request.user) questionnaire = Project.get(dbm, project_id) dashboard_page = settings.HOME_PAGE + "?deleted=true" if questionnaire.is_void(): return HttpResponseRedirect(dashboard_page) from datawinners.project.views.views import make_project_links project_lin...
ExistsException, EntityQuestionAlreadyExistsException) as ex: return HttpResponse( json.dumps({'success': False, 'error_in_project_section': False, 'error_message': _(ex.message)})) except DataObjectAlreadyExists: return HttpResponse(json.dumps({'success':...
173
174
580
38
135
ICT4H/dcs-web
datawinners/project/wizard_view.py
Python
reminder_settings
reminder_settings
175
229
175
181
0a33b38d926bd23fbf81a7a63cab8e33b586a92a
bigcode/the-stack
train
1d44f8a5a400a23c490e6b61
train
function
def remove_deleted_questions_from_submissions(manager, form_model_id, deleted_question_codes): if deleted_question_codes: survey_responses = survey_responses_by_form_model_id(manager, form_model_id) for survey_response in survey_responses: for code in deleted_question_codes: ...
def remove_deleted_questions_from_submissions(manager, form_model_id, deleted_question_codes):
if deleted_question_codes: survey_responses = survey_responses_by_form_model_id(manager, form_model_id) for survey_response in survey_responses: for code in deleted_question_codes: survey_response._doc.values.pop(code, None) survey_response.save()
_code) # documents = [] # for survey_response in survey_responses: # survey_response.form_code = new_form_code # documents.append(survey_response._doc) # manager._save_documents(documents) def remove_deleted_questions_from_submissions(manager, form_model_id, deleted_question_c...
64
64
74
17
47
ICT4H/dcs-web
datawinners/project/wizard_view.py
Python
remove_deleted_questions_from_submissions
remove_deleted_questions_from_submissions
351
357
351
351
08b5132090be9126b231c3cfc313376a0ee9c0fc
bigcode/the-stack
train
ac239653d7b3ff65fb8b12e8
train
function
def _get_activity_log_action(reminder_list, new_value): action = None if reminder_list.count() == 0 and (new_value['should_send_reminders_after_deadline'] or new_value['should_send_reminders_on_deadline'] or new_value['should_...
def _get_activity_log_action(reminder_list, new_value):
action = None if reminder_list.count() == 0 and (new_value['should_send_reminders_after_deadline'] or new_value['should_send_reminders_on_deadline'] or new_value['should_send_reminders_before_deadline']): action = ACTI...
_send_reminder_to_all_ds'] = not cleaned_data['whom_to_send_message'] == 'true' else: reminder_list = Reminder.objects.filter(project_id=project.id) reminder_list.delete() return project, set_deadline def _get_activity_log_action(reminder_list, new_value):
64
64
155
13
50
ICT4H/dcs-web
datawinners/project/wizard_view.py
Python
_get_activity_log_action
_get_activity_log_action
328
338
328
328
ff99d014adff333cc791b56e34d99f44e6483d51
bigcode/the-stack
train
c1d1a5e25cb51f4082dfd130
train
function
def _add_reminder_info_to_project(cleaned_data, project, organization, reminder_list=None): set_deadline = False if project.reminder_and_deadline.get('has_deadline'): project.reminder_and_deadline['frequency_period'] = cleaned_data['frequency_period'] if cleaned_data['frequency_period'] == 'mont...
def _add_reminder_info_to_project(cleaned_data, project, organization, reminder_list=None):
set_deadline = False if project.reminder_and_deadline.get('has_deadline'): project.reminder_and_deadline['frequency_period'] = cleaned_data['frequency_period'] if cleaned_data['frequency_period'] == 'month': if project.reminder_and_deadline.get('deadline_week'): del p...
_deadline[0].day data['reminder_text_after_deadline'] = reminder_after_deadline[0].message else: data['should_send_reminders_after_deadline'] = False data['number_of_days_after_deadline'] = 2 data['reminder_text_after_deadline'] = ugettext("Hello. We have not rece...
145
145
486
20
124
ICT4H/dcs-web
datawinners/project/wizard_view.py
Python
_add_reminder_info_to_project
_add_reminder_info_to_project
285
325
285
285
ef1b6a6027843f61eca7701f77bda962956bc115
bigcode/the-stack
train
42dd84821273ef37aa6762c4
train
function
def _get_changed_data(project, project_info): changed_dict = dict() for attr, value in project_info.iteritems(): if getattr(project, attr) != value: changed_dict.update({attr.capitalize(): value}) return changed_dict
def _get_changed_data(project, project_info):
changed_dict = dict() for attr, value in project_info.iteritems(): if getattr(project, attr) != value: changed_dict.update({attr.capitalize(): value}) return changed_dict
=field_to_json)} return HttpResponse(json.dumps(template_details), content_type='application/json') def _get_deleted_question_codes(new_codes, old_codes): diff = set(old_codes) - set(new_codes) return filter(diff.__contains__, old_codes) def _get_changed_data(project, project_info):
64
64
51
10
54
ICT4H/dcs-web
datawinners/project/wizard_view.py
Python
_get_changed_data
_get_changed_data
111
116
111
111
ea77a3ec717d4bcacf1d3867b1a07c7de045ca53
bigcode/the-stack
train
f9d3edaff5dfa7db85d4040d
train
function
def _get_deleted_question_codes(new_codes, old_codes): diff = set(old_codes) - set(new_codes) return filter(diff.__contains__, old_codes)
def _get_deleted_question_codes(new_codes, old_codes):
diff = set(old_codes) - set(new_codes) return filter(diff.__contains__, old_codes)
': template.get('language'), 'questionnaire_code': template.get('form_code'), 'existing_questions': json.dumps(template.get('json_fields'), default=field_to_json)} return HttpResponse(json.dumps(template_details), content_type='application/json') def _get_deleted_ques...
64
64
34
12
52
ICT4H/dcs-web
datawinners/project/wizard_view.py
Python
_get_deleted_question_codes
_get_deleted_question_codes
106
108
106
106
05b08e8bfa563fd4ea7b8b2c5014e6a31528aaf7
bigcode/the-stack
train
fe322defae9af9c50909d205
train
function
def _reminder_info_about_project(project): data = {} deadline_information = project.reminder_and_deadline data['has_deadline'] = deadline_information['has_deadline'] if deadline_information['has_deadline']: data['frequency_period'] = deadline_information['frequency_period'] if deadline_i...
def _reminder_info_about_project(project):
data = {} deadline_information = project.reminder_and_deadline data['has_deadline'] = deadline_information['has_deadline'] if deadline_information['has_deadline']: data['frequency_period'] = deadline_information['frequency_period'] if deadline_information['frequency_period'] == 'month': ...
add_reminder_info_to_project(post_data, questionnaire, organization, reminder_list=reminder_list) questionnaire.save() if action is not None: UserActivityLog().log(request, action=action, project=questionnaire.name) if set...
172
172
574
9
162
ICT4H/dcs-web
datawinners/project/wizard_view.py
Python
_reminder_info_about_project
_reminder_info_about_project
240
282
240
240
5270b01e81bfb090f789104553c1557a4b3aecb6
bigcode/the-stack
train
d4b2b6625c4e8ca9b7726f88
train
function
@login_required def get_template_details(request, template_id): library = QuestionnaireLibrary() template = library.get_questionnaire_template(template_id) template_details = {'template_id': template.id, 'project_name': template.get('name'), 'project_language': template.get('language...
@login_required def get_template_details(request, template_id):
library = QuestionnaireLibrary() template = library.get_questionnaire_template(template_id) template_details = {'template_id': template.id, 'project_name': template.get('name'), 'project_language': template.get('language'), 'questionnaire_code': template.get('...
_expired @csrf_exempt @is_not_expired def get_templates(request): library = QuestionnaireLibrary() return HttpResponse(json.dumps({'categories': library.get_template_groupings(request.LANGUAGE_CODE)}), content_type='application/json') @login_required def get_template_details(request, tem...
64
64
105
12
52
ICT4H/dcs-web
datawinners/project/wizard_view.py
Python
get_template_details
get_template_details
95
103
95
96
06f76cff6f0e247e5364ee3dc4e5f90902f12a53
bigcode/the-stack
train
dc4e11b00e79520c0bad7e56
train
function
def _populate_week_month_data(post_data): if post_data['frequency_period'] == 'month': post_data['deadline_month'] = post_data['select_day'] else: post_data['deadline_week'] = post_data['select_day'] return post_data
def _populate_week_month_data(post_data):
if post_data['frequency_period'] == 'month': post_data['deadline_month'] = post_data['select_day'] else: post_data['deadline_week'] = post_data['select_day'] return post_data
if set_deadline: UserActivityLog().log(request, action=SET_DEADLINE, project=questionnaire.name) response = {'success_message': ugettext("Reminder settings saved successfully."), 'success': True} return HttpResponse(json.dumps(response)) def _populate_week_month_data(post_data):
64
64
57
9
55
ICT4H/dcs-web
datawinners/project/wizard_view.py
Python
_populate_week_month_data
_populate_week_month_data
232
237
232
232
2fc0c4d09273aa1ee6ae56ac9d2408f00acf97ce
bigcode/the-stack
train
ccfaee149b2511503735eba4
train
class
class PolicyClientConfiguration(AzureConfiguration): """Configuration for PolicyClient Note that all parameters used to create this instance are saved as instance attributes. :param credentials: Credentials needed for the client to connect to Azure. :type credentials: :mod:`A msrestazure Credential...
class PolicyClientConfiguration(AzureConfiguration):
"""Configuration for PolicyClient Note that all parameters used to create this instance are saved as instance attributes. :param credentials: Credentials needed for the client to connect to Azure. :type credentials: :mod:`A msrestazure Credentials object<msrestazure.azure_active_directory>` ...
# regenerated. # -------------------------------------------------------------------------- from msrest.service_client import ServiceClient from msrest import Serializer, Deserializer from msrestazure import AzureConfiguration from azure.profiles import KnownProfiles, ProfileDefinition from azure.profiles.multiapicli...
71
71
237
8
62
AlexanderYukhanov/azure-sdk-for-python
azure-mgmt-resource/azure/mgmt/resource/policy/policy_client.py
Python
PolicyClientConfiguration
PolicyClientConfiguration
21
50
21
21
b719ffd531db9a05269f3d03618493f157621147
bigcode/the-stack
train
6fc1477b1838f602ee4ad18f
train
class
class PolicyClient(MultiApiClientMixin): """To manage and control access to your resources, you can define customized policies and assign them at a scope. :ivar config: Configuration for client. :vartype config: PolicyClientConfiguration :param credentials: Credentials needed for the client to connect...
class PolicyClient(MultiApiClientMixin):
"""To manage and control access to your resources, you can define customized policies and assign them at a scope. :ivar config: Configuration for client. :vartype config: PolicyClientConfiguration :param credentials: Credentials needed for the client to connect to Azure. :type credentials: :mod:`A...
ApiClientMixin from ..version import VERSION class PolicyClientConfiguration(AzureConfiguration): """Configuration for PolicyClient Note that all parameters used to create this instance are saved as instance attributes. :param credentials: Credentials needed for the client to connect to Azure. :t...
256
256
1,839
9
246
AlexanderYukhanov/azure-sdk-for-python
azure-mgmt-resource/azure/mgmt/resource/policy/policy_client.py
Python
PolicyClient
PolicyClient
53
189
53
53
800a69d88c4df1096305a14b51755c9d0bdd1be6
bigcode/the-stack
train
fed8b427afcf21e038ecf8ef
train
class
class BandListWidget(entity_list_widget.EntityListWidget): def __init__(self, items: list, clicked): super().__init__(items, clicked)
class BandListWidget(entity_list_widget.EntityListWidget):
def __init__(self, items: list, clicked): super().__init__(items, clicked)
#!/usr/bin/env python3 from ui.lists_display import entity_list_widget class BandListWidget(entity_list_widget.EntityListWidget):
28
64
33
11
16
BabyCakes13/GlacierImagePredictor
gits/ui/lists_display/bands/band_list_widget.py
Python
BandListWidget
BandListWidget
5
7
5
5
110dc9b02b1a869d513d9527f92e51dabae45b08
bigcode/the-stack
train
ac7d0d6a41bb6143bdaf69d8
train
function
def progress(state, progress=0.0): if len(state_file_name): global last_state_datetime if last_state_datetime < datetime.now() + timedelta(milliseconds=-1000) or state is None: last_state_datetime = datetime.now() with open(state_file_name, 'w') as f: if state...
def progress(state, progress=0.0):
if len(state_file_name): global last_state_datetime if last_state_datetime < datetime.now() + timedelta(milliseconds=-1000) or state is None: last_state_datetime = datetime.now() with open(state_file_name, 'w') as f: if state is not None: f...
under the License. from datetime import datetime, timedelta # state output # ============ state_file_name = '' last_state_datetime = datetime.now() def configure_progress(file_name): global state_file_name state_file_name = file_name progress(None) def progress(state, progress=0.0):
64
64
94
10
54
kodavatimahendra/nnabla
python/src/nnabla/utils/progress.py
Python
progress
progress
30
37
30
30
23944094b7570b966c67a22cb1e5fa0810279045
bigcode/the-stack
train
adea57f8429cf10660fd777c
train
function
def configure_progress(file_name): global state_file_name state_file_name = file_name progress(None)
def configure_progress(file_name):
global state_file_name state_file_name = file_name progress(None)
# 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 datetime import datetime, timedelta # state output # ============ state_file_name = '' last_state_datetime = datetime.now() def config...
64
64
24
6
58
kodavatimahendra/nnabla
python/src/nnabla/utils/progress.py
Python
configure_progress
configure_progress
24
27
24
24
c77969318bde54131e1fe445f37be5e33ba68bfb
bigcode/the-stack
train
3b47334c41f87c07d2cebc04
train
class
class ActionServer: def serve_actions(self, itr): obs_ready, act_ready = self.sync.obs_ready, self.sync.act_ready step_np, agent_inputs = self.step_buffer_np, self.agent_inputs for t in range(self.batch_spec.T): for b in obs_ready: b.acquire() # Workers written ...
class ActionServer:
def serve_actions(self, itr): obs_ready, act_ready = self.sync.obs_ready, self.sync.act_ready step_np, agent_inputs = self.step_buffer_np, self.agent_inputs for t in range(self.batch_spec.T): for b in obs_ready: b.acquire() # Workers written obs and rew, first pr...
import numpy as np from rlpyt.agents.base import AgentInputs from rlpyt.utils.synchronize import drain_queue from rlpyt.utils.logging import logger EVAL_TRAJ_CHECK = 20 # [steps]. class ActionServer:
54
256
863
4
50
csingh27sewts/rlpyt
rlpyt/samplers/parallel/gpu/action_server.py
Python
ActionServer
ActionServer
12
89
12
13
3ede8a7203180aa92b832212557834b30db6e8c4
bigcode/the-stack
train
d17b9cb752648368b7a15a2e
train
class
class NoOverlapAlternatingActionServer: def serve_actions(self, itr): obs_ready = self.sync.obs_ready obs_ready_pair = self.obs_ready_pair act_ready_pair = self.act_ready_pair step_np, step_np_pair = self.step_buffer_np, self.step_buffer_np_pair agent_inputs, agent_inputs_pa...
class NoOverlapAlternatingActionServer:
def serve_actions(self, itr): obs_ready = self.sync.obs_ready obs_ready_pair = self.obs_ready_pair act_ready_pair = self.act_ready_pair step_np, step_np_pair = self.step_buffer_np, self.step_buffer_np_pair agent_inputs, agent_inputs_pair = self.agent_inputs, self.agent_inputs...
_trajectories is not None and t % EVAL_TRAJ_CHECK == 0 and alt == 0): if len(traj_infos) >= self.eval_max_trajectories: for b in obs_ready_pair[1 - alt]: b.acquire() # Now all workers waiting. self.s...
256
256
1,304
8
247
csingh27sewts/rlpyt
rlpyt/samplers/parallel/gpu/action_server.py
Python
NoOverlapAlternatingActionServer
NoOverlapAlternatingActionServer
196
318
196
197
2459f0281d04cc65547b04b4ae492d9404a143a3
bigcode/the-stack
train
56afaf1dbe605f2ad517c719
train
class
class AlternatingActionServer: """Two environment instance groups may execute partially simultaneously.""" def serve_actions(self, itr): obs_ready_pair = self.obs_ready_pair act_ready_pair = self.act_ready_pair step_np_pair = self.step_buffer_np_pair agent_inputs_pair = self.age...
class AlternatingActionServer:
"""Two environment instance groups may execute partially simultaneously.""" def serve_actions(self, itr): obs_ready_pair = self.obs_ready_pair act_ready_pair = self.act_ready_pair step_np_pair = self.step_buffer_np_pair agent_inputs_pair = self.agent_inputs_pair # Can e...
_reward. self.agent.reset_one(idx=b_reset) action, agent_info = self.agent.step(*agent_inputs) step_np.action[:] = action step_np.agent_info[:] = agent_info if self.eval_max_trajectories is not None and t % EVAL_TRAJ_CHECK == 0: self.sync.s...
256
256
1,021
6
249
csingh27sewts/rlpyt
rlpyt/samplers/parallel/gpu/action_server.py
Python
AlternatingActionServer
AlternatingActionServer
92
193
92
92
a9b76e5b4438aeea94ff6c55d74b0c4365297e10
bigcode/the-stack
train
64f57b1a4a7bf810478c2b15
train
function
def _entry(model_name, paper_model_name, paper_arxiv_id, batch_size=BATCH_SIZE, ttp=False, args=dict(), model_desc=None): return dict( model=model_name, model_description=model_desc, paper_model_name=paper_model_name, paper_arxiv_id=paper_arxiv_id, batch_size=batch...
def _entry(model_name, paper_model_name, paper_arxiv_id, batch_size=BATCH_SIZE, ttp=False, args=dict(), model_desc=None):
return dict( model=model_name, model_description=model_desc, paper_model_name=paper_model_name, paper_arxiv_id=paper_arxiv_id, batch_size=batch_size, ttp=ttp, args=args)
_transform from timm.models import TestTimePoolHead import os NUM_GPU = 1 BATCH_SIZE = 256 * NUM_GPU def _entry(model_name, paper_model_name, paper_arxiv_id, batch_size=BATCH_SIZE, ttp=False, args=dict(), model_desc=None):
64
64
84
33
30
michalwols/pytorch-image-models
sotabench.py
Python
_entry
_entry
12
21
12
13
3c11df212513570f09bcb49a10b6058aee057a75
bigcode/the-stack
train
321bd04f2c80d4ce4460c707
train
function
@torch.fx.wrap def _user_func_with_complex_return_type(x): return list(torch.split(x, 1, 1))
@torch.fx.wrap def _user_func_with_complex_return_type(x):
return list(torch.split(x, 1, 1))
= 3 if self.is_scalar else self.conv2(y) x = self.op(x, y) x = self.relu(x) x = self.op(y, x) x = self.relu(x) return x @torch.fx.wrap def _user_func_with_complex_return_type(x):
64
64
28
15
48
jaketae/pytorch
test/quantization/fx/test_quantize_fx.py
Python
_user_func_with_complex_return_type
_user_func_with_complex_return_type
204
206
204
205
3a21a204c5c4f97b0944debd0ee8d1b56ce1d484
bigcode/the-stack
train
8d4b5dfcfd96f01c8b68eafe
train
class
@skipIfNoFBGEMM class TestQuantizeFx(QuantizationTestCase): def test_pattern_match(self): """ test MatchAllNode with conv - bn - add - relu pattern """ class M(torch.nn.Module): def __init__(self): super().__init__() self.conv = nn.Conv...
@skipIfNoFBGEMM class TestQuantizeFx(QuantizationTestCase):
def test_pattern_match(self): """ test MatchAllNode with conv - bn - add - relu pattern """ class M(torch.nn.Module): def __init__(self): super().__init__() self.conv = nn.Conv2d(1, 1, 1) self.bn = nn.BatchNorm2d(1) ...
(pattern): relu, (_, _, extra_input) = pattern return [extra_input] conv_relu_config = { "pattern": (nn.ReLU, nn.Conv2d), "fuser_method": fuse_conv_relu, } conv_res_relu_config = { "pattern": (nn.ReLU, (torch.add, nn.Conv2d, MatchAllNo...
255
256
30,144
20
235
jaketae/pytorch
test/quantization/fx/test_quantize_fx.py
Python
TestQuantizeFx
TestQuantizeFx
674
4,320
674
675
71ab84b6e324867d1a4ff49fdf07d9c9a889ac4b
bigcode/the-stack
train
6f72e7dcab8a5b275a4ff241
train
class
class TestFuseFx(QuantizationTestCase): def test_fuse_conv_bn_relu(self): class M(torch.nn.Module): def __init__(self): super().__init__() self.conv1d = nn.Conv1d(1, 1, 1) self.conv2d = nn.Conv2d(1, 1, 1) self.conv3d = nn.Conv3d(1, ...
class TestFuseFx(QuantizationTestCase):
def test_fuse_conv_bn_relu(self): class M(torch.nn.Module): def __init__(self): super().__init__() self.conv1d = nn.Conv1d(1, 1, 1) self.conv2d = nn.Conv2d(1, 1, 1) self.conv3d = nn.Conv3d(1, 1, 1) self.bn1d = nn.Bat...
__init__(self, binary_op, ibinary_op, is_inplace, relu_callable, is_scalar): """ ibinary_op means inplace binary op """ super().__init__() self.conv1 = torch.nn.Conv2d(1, 1, 1).float() self.conv2 = torch.nn.Conv2d(1, 1, 1).float() self.op = ibinary_op if...
256
256
3,923
10
246
jaketae/pytorch
test/quantization/fx/test_quantize_fx.py
Python
TestFuseFx
TestFuseFx
208
671
208
208
2ca6b84dfe60eabb717423a39f365a6d681932da
bigcode/the-stack
train
e52667e5da326dee6bc555d1
train
class
class BinaryOp(torch.nn.Module): def __init__(self, binary_op, ibinary_op, is_inplace, is_scalar): """ ibinary_op means inplace binary op """ super().__init__() self.conv1 = torch.nn.Conv2d(1, 1, 1).float() self.conv2 = torch.nn.Conv2d(1, 1, 1).float() self.is_scalar ...
class BinaryOp(torch.nn.Module):
def __init__(self, binary_op, ibinary_op, is_inplace, is_scalar): """ ibinary_op means inplace binary op """ super().__init__() self.conv1 = torch.nn.Conv2d(1, 1, 1).float() self.conv2 = torch.nn.Conv2d(1, 1, 1).float() self.is_scalar = is_scalar self.op = ibi...
Optional, List TEST_WITH_ROCM = os.getenv('PYTORCH_TEST_WITH_ROCM', '0') == '1' def get_supported_device_types(): return ['cpu', 'cuda'] if torch.cuda.is_available() and not TEST_WITH_ROCM else ['cpu'] class BinaryOp(torch.nn.Module):
64
64
184
7
57
jaketae/pytorch
test/quantization/fx/test_quantize_fx.py
Python
BinaryOp
BinaryOp
147
164
147
147
0cffada23e5b2e2db992bc2e5abc7d6cfcd2b2eb
bigcode/the-stack
train
8bf68f1697d47db265fda067
train
class
class BinaryOpRelu(torch.nn.Module): def __init__(self, binary_op, ibinary_op, is_inplace, relu_callable, is_scalar): """ ibinary_op means inplace binary op """ super().__init__() self.conv1 = torch.nn.Conv2d(1, 1, 1).float() self.conv2 = torch.nn.Conv2d(1, 1...
class BinaryOpRelu(torch.nn.Module):
def __init__(self, binary_op, ibinary_op, is_inplace, relu_callable, is_scalar): """ ibinary_op means inplace binary op """ super().__init__() self.conv1 = torch.nn.Conv2d(1, 1, 1).float() self.conv2 = torch.nn.Conv2d(1, 1, 1).float() self.op = ibinar...
.is_scalar = is_scalar self.op = ibinary_op if ibinary_op and is_inplace else binary_op def forward(self, x, y): y = 3 if self.is_scalar else y x = self.op(x, y) return x class BinaryOpRelu(torch.nn.Module):
68
68
229
9
58
jaketae/pytorch
test/quantization/fx/test_quantize_fx.py
Python
BinaryOpRelu
BinaryOpRelu
179
202
179
179
41684b4511f5982845a9568bf11f086e916bc98c
bigcode/the-stack
train
7fb0b25eab3c5ceebbffd4f8
train
class
class TestQuantizeFxModels(QuantizationTestCase): @skipIfNoFBGEMM @unittest.skipIf(not TEST_CUDA, "gpu is not available.") def test_static_gpu_convert_basic(self): class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.relu1 = nn.ReLU(...
class TestQuantizeFxModels(QuantizationTestCase): @skipIfNoFBGEMM @unittest.skipIf(not TEST_CUDA, "gpu is not available.")
def test_static_gpu_convert_basic(self): class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.relu1 = nn.ReLU() self.conv1 = nn.Conv2d(1, 6, 5) self.linear1 = nn.Linear(120, 1) def forward(self, x...
, } self.checkGraphModuleNodes( m, expected_node_occurrence=expected_occurrence) @unittest.skip("This is no longer needed right now, can enable later with new api") def test_qmatmul(self): class M(torch.nn.Module): def forward(self, x, y): ...
256
256
4,873
39
217
jaketae/pytorch
test/quantization/fx/test_quantize_fx.py
Python
TestQuantizeFxModels
TestQuantizeFxModels
6,558
7,095
6,558
6,560
fc9197abfb8d5953c765bef51d29135a5b3aec6d
bigcode/the-stack
train
75b9cee8e1879201f2df5e25
train
class
@skipIfNoFBGEMM class TestQuantizeFxOps(QuantizationTestCase): def setUp(self): super().setUp() self.custom_qconfig = torch.ao.quantization.QConfig( activation=torch.ao.quantization.observer.HistogramObserver.with_args( qscheme=torch.per_tensor_symmetric, dtype=torch.qint...
@skipIfNoFBGEMM class TestQuantizeFxOps(QuantizationTestCase):
def setUp(self): super().setUp() self.custom_qconfig = torch.ao.quantization.QConfig( activation=torch.ao.quantization.observer.HistogramObserver.with_args( qscheme=torch.per_tensor_symmetric, dtype=torch.qint8 ), weight=torch.ao.quantization.defau...
_activation_post_process(mod) and mod.dtype == torch.quint8: if backend == "fbgemm": self.assertEqual(mod.quant_min, 0) self.assertEqual(mod.quant_max, 127) else: self.assertEqual(mod.quan...
256
256
20,360
21
235
jaketae/pytorch
test/quantization/fx/test_quantize_fx.py
Python
TestQuantizeFxOps
TestQuantizeFxOps
4,322
6,556
4,322
4,323
aeca342d3cc998e355f5226a595eb610af60f1d3
bigcode/the-stack
train
77a1ddeb10015494caca1956
train
class
class BinaryOpNonQuantizedInput(torch.nn.Module): def __init__(self, binary_op, ibinary_op, is_inplace, is_scalar): """ ibinary_op means inplace binary op """ super().__init__() self.is_scalar = is_scalar self.op = ibinary_op if ibinary_op and is_inplace else binary_op d...
class BinaryOpNonQuantizedInput(torch.nn.Module):
def __init__(self, binary_op, ibinary_op, is_inplace, is_scalar): """ ibinary_op means inplace binary op """ super().__init__() self.is_scalar = is_scalar self.op = ibinary_op if ibinary_op and is_inplace else binary_op def forward(self, x, y): y = 3 if self.is_s...
y = 3 if self.is_scalar else self.conv2(y) # x = x + y x = self.op(x, y) # x = y + x x = self.op(y, x) return x class BinaryOpNonQuantizedInput(torch.nn.Module):
64
64
110
11
52
jaketae/pytorch
test/quantization/fx/test_quantize_fx.py
Python
BinaryOpNonQuantizedInput
BinaryOpNonQuantizedInput
166
177
166
166
24d4e1d04542450a999d7355c53e611685f478ac
bigcode/the-stack
train
dc262e28537e71165d5617d0
train
function
def get_supported_device_types(): return ['cpu', 'cuda'] if torch.cuda.is_available() and not TEST_WITH_ROCM else ['cpu']
def get_supported_device_types():
return ['cpu', 'cuda'] if torch.cuda.is_available() and not TEST_WITH_ROCM else ['cpu']
import ConvModel from torch.testing import FileCheck import copy import itertools import operator import unittest import io from typing import Callable, Optional, List TEST_WITH_ROCM = os.getenv('PYTORCH_TEST_WITH_ROCM', '0') == '1' def get_supported_device_types():
64
64
30
6
58
jaketae/pytorch
test/quantization/fx/test_quantize_fx.py
Python
get_supported_device_types
get_supported_device_types
144
145
144
144
5df5f8b7f4b7158021389a064e103abc7f8d640c
bigcode/the-stack
train
ec4fa3b7b96b6e07af006c99
train
class
class Migration(migrations.Migration): dependencies = [ ('tasks', '0004_job_code'), ] operations = [ migrations.AlterField( model_name='job', name='code', field=models.TextField(null=True), ), ]
class Migration(migrations.Migration):
dependencies = [ ('tasks', '0004_job_code'), ] operations = [ migrations.AlterField( model_name='job', name='code', field=models.TextField(null=True), ), ]
# Generated by Django 2.2.1 on 2020-05-11 14:00 from django.db import migrations, models class Migration(migrations.Migration):
38
64
55
7
30
Anton-Shevchenko/tester
src/tasks/migrations/0005_auto_20200511_1400.py
Python
Migration
Migration
6
18
6
7
0a256c76e4829fbbbec464d4ae5494c4fd9d2782
bigcode/the-stack
train
6a2904b22f667d8b0448291b
train
class
class DatabaseError(SeedError): """ Database error. """ pass
class DatabaseError(SeedError):
""" Database error. """ pass
__init__(self, message): self.message = message def __str__(self): return self.message class SchemaError(SeedError): """ Schema error. """ pass class DataError(SeedError): """ Data error. """ pass class DatabaseError(SeedError):
64
64
16
7
56
okosioc/flask-seed
app/seed/error.py
Python
DatabaseError
DatabaseError
33
35
33
33
645a815de8c8ab9a7ddb175c91f8a6d877e97ebf
bigcode/the-stack
train
dbd4cacf5ed8d098b10a7177
train
class
class SchemaError(SeedError): """ Schema error. """ pass
class SchemaError(SeedError):
""" Schema error. """ pass
weiminfeng. :date: 2021/6/9 """ class SeedError(Exception): """ Base class for exceptions. """ def __init__(self, message): self.message = message def __str__(self): return self.message class SchemaError(SeedError):
64
64
16
7
56
okosioc/flask-seed
app/seed/error.py
Python
SchemaError
SchemaError
23
25
23
23
336cb906380b8eb83c7b515ef4a104a35fbf4a9d
bigcode/the-stack
train
2968477ea3c0508159faabd7
train
class
class SeedError(Exception): """ Base class for exceptions. """ def __init__(self, message): self.message = message def __str__(self): return self.message
class SeedError(Exception):
""" Base class for exceptions. """ def __init__(self, message): self.message = message def __str__(self): return self.message
# -*- coding: utf-8 -*- """ error ~~~~~~~~~~~~~~ Error defintion. :copyright: (c) 2020 by weiminfeng. :date: 2021/6/9 """ class SeedError(Exception):
56
64
40
5
51
okosioc/flask-seed
app/seed/error.py
Python
SeedError
SeedError
13
20
13
13
c85a9e7c9fd2e2171b85d434f7f795563a00cdd3
bigcode/the-stack
train
475c1799eaf33b0d83c6c7b3
train
class
class DataError(SeedError): """ Data error. """ pass
class DataError(SeedError):
""" Data error. """ pass
""" class SeedError(Exception): """ Base class for exceptions. """ def __init__(self, message): self.message = message def __str__(self): return self.message class SchemaError(SeedError): """ Schema error. """ pass class DataError(SeedError):
64
64
16
7
56
okosioc/flask-seed
app/seed/error.py
Python
DataError
DataError
28
30
28
28
f59d2f5ae983470358a437e5d42b0d0d6628f782
bigcode/the-stack
train
b714c77fba4202b0fba15be0
train
class
class MemberLookup(LookupBase): url = '/admin/membership/lookups/member/' @property def label_from_instance(self): return lambda x: '{0} ({1})'.format(x.fullname, x.user.username) @classmethod def get_values(self, query): return [ {'id': m.pk, 'value': m.fullname} ...
class MemberLookup(LookupBase):
url = '/admin/membership/lookups/member/' @property def label_from_instance(self): return lambda x: '{0} ({1})'.format(x.fullname, x.user.username) @classmethod def get_values(self, query): return [ {'id': m.pk, 'value': m.fullname} for m in Member.objects.f...
from django.db.models import Q from postgresqleu.util.backendlookups import LookupBase from postgresqleu.util.auth import authenticate_backend_group from postgresqleu.membership.models import Member class MemberLookup(LookupBase):
51
64
143
8
42
bradfordboyle/pgeu-system
postgresqleu/membership/backendlookups.py
Python
MemberLookup
MemberLookup
8
24
8
8
54ba70cc9ac366a73fe0463f73c84a59325b2ce4
bigcode/the-stack
train
cdeb4d3b1d8729ad460c8c34
train
class
class Migration(migrations.Migration): dependencies = [("profiles", "0005_auto_20200128_2138")] operations = [ migrations.AlterField( model_name="profile", name="subscription_last_checked", field=models.DateTimeField(default=profiles.utils.utcnow), ) ]
class Migration(migrations.Migration):
dependencies = [("profiles", "0005_auto_20200128_2138")] operations = [ migrations.AlterField( model_name="profile", name="subscription_last_checked", field=models.DateTimeField(default=profiles.utils.utcnow), ) ]
# Generated by Django 2.2.3 on 2020-01-29 20:23 from django.db import migrations, models import profiles.utils class Migration(migrations.Migration):
42
64
65
7
34
jgarber623/openstates.org
profiles/migrations/0006_auto_20200129_2023.py
Python
Migration
Migration
7
17
7
8
4b9b524e9731943f8dbcd56c766ec01d77f3898d
bigcode/the-stack
train
5865a2c31adcbd3fe4dacece
train
class
class TrezorPlugin(HW_PluginBase): # Derived classes provide: # # class-static variables: client_class, firmware_URL, handler_class, # libraries_available, libraries_URL, minimum_firmware, # wallet_class, ckd_public, types firmware_URL = 'https://wallet.trezor.io' libraries_URL = '...
class TrezorPlugin(HW_PluginBase): # Derived classes provide: # # class-static variables: client_class, firmware_URL, handler_class, # libraries_available, libraries_URL, minimum_firmware, # wallet_class, ckd_public, types
firmware_URL = 'https://wallet.trezor.io' libraries_URL = 'https://github.com/trezor/python-trezor' minimum_firmware = (1, 5, 2) keystore_class = TrezorKeyStore minimum_library = (0, 12, 0) maximum_library = (0, 13) SUPPORTED_XTYPES = ('standard', 'p2wpkh-p2sh', 'p2wpkh', 'p2wsh-p2sh', 'p2ws...
_pubkeys = tx.get_sorted_pubkeys(txin) tx_hash = txin['prevout_hash'] if txin.get('prev_tx') is None: raise Exception(_('Offline signing with {} is not supported for legacy inputs.').format(self.device)) prev_tx[tx_hash] = txin['prev_tx'] for x_pubkey in x...
256
256
3,577
60
195
glemercier/electrum-smart
plugins/trezor/trezor.py
Python
TrezorPlugin
TrezorPlugin
106
474
106
112
ed977bd2f223e0e8fb2efdb69b918120929c8b11
bigcode/the-stack
train
c05b7912dec4f79ab8d84a9d
train
class
class TrezorInitSettings(NamedTuple): word_count: int label: str pin_enabled: bool passphrase_enabled: bool recovery_type: Any = None no_backup: bool = False
class TrezorInitSettings(NamedTuple):
word_count: int label: str pin_enabled: bool passphrase_enabled: bool recovery_type: Any = None no_backup: bool = False
xpub, s = parse_xpubkey(x_pubkey) if xpub == self.get_master_public_key(): xpub_path[xpub] = self.get_derivation() self.plugin.sign_transaction(self, tx, prev_tx, xpub_path) class TrezorInitSettings(NamedTuple):
64
64
50
10
54
glemercier/electrum-smart
plugins/trezor/trezor.py
Python
TrezorInitSettings
TrezorInitSettings
98
104
98
98
9ac6f2152b433e897ed1d84d6aff1f7a14ca8c64
bigcode/the-stack
train
e720ce07caa1befd0623071b
train
class
class TrezorKeyStore(Hardware_KeyStore): hw_type = 'trezor' device = 'TREZOR' def get_derivation(self): return self.derivation def get_script_gen(self): return SCRIPT_GEN_LEGACY def get_client(self, force_pair=True): return self.plugin.get_client(self, force_pair) def...
class TrezorKeyStore(Hardware_KeyStore):
hw_type = 'trezor' device = 'TREZOR' def get_derivation(self): return self.derivation def get_script_gen(self): return SCRIPT_GEN_LEGACY def get_client(self, force_pair=True): return self.plugin.get_client(self, force_pair) def decrypt_message(self, sequence, message,...
ZORLIB = False RECOVERY_TYPE_SCRAMBLED_WORDS, RECOVERY_TYPE_MATRIX = range(2) PASSPHRASE_ON_DEVICE = object() # TREZOR initialization methods TIM_NEW, TIM_RECOVER = range(2) TREZOR_PRODUCT_KEY = 'Trezor' # script "generation" SCRIPT_GEN_LEGACY, SCRIPT_GEN_P2SH_SEGWIT, SCRIPT_GEN_NATIVE_SEGWIT = range(0, 3)...
111
111
372
11
100
glemercier/electrum-smart
plugins/trezor/trezor.py
Python
TrezorKeyStore
TrezorKeyStore
53
95
53
53
11dc75b78d3c025d57b23abddcb8ef3449103263
bigcode/the-stack
train
39d7a8bd1fa7436707de2e27
train
function
@curry def mean_prediction_evaluator(test_data: pd.DataFrame, prediction_column: str = "prediction", eval_name: str = None) -> EvalReturnType: """ Computes mean for the specified column. Parameters ---------- test_data : Pandas' DataFrame ...
@curry def mean_prediction_evaluator(test_data: pd.DataFrame, prediction_column: str = "prediction", eval_name: str = None) -> EvalReturnType:
""" Computes mean for the specified column. Parameters ---------- test_data : Pandas' DataFrame A Pandas' DataFrame with a column to compute the mean prediction_column : Strings The name of the column in `test_data` to compute the mean. eval_name : String, optional (defaul...
("mse_evaluator__", mean_squared_error) return eval_fn(test_data, prediction_column, target_column, eval_name) @curry def mean_prediction_evaluator(test_data: pd.DataFrame, prediction_column: str = "prediction", eval_name: str = None) -> EvalReturnType:
64
64
183
38
26
WesleyBatista/fklearn
src/fklearn/validation/evaluators.py
Python
mean_prediction_evaluator
mean_prediction_evaluator
504
531
504
507
d5a9581b947996dd3059a051f46221215ef549d2
bigcode/the-stack
train
0721063bbd00dc90bb285934
train
function
@curry def permutation_evaluator(test_data: pd.DataFrame, predict_fn: PredictFnType, eval_fn: EvalFnType, baseline: bool = True, features: List[str] = None, shuffle_all_at_once: bool = False...
@curry def permutation_evaluator(test_data: pd.DataFrame, predict_fn: PredictFnType, eval_fn: EvalFnType, baseline: bool = True, features: List[str] = None, shuffle_all_at_once: bool = False...
""" Permutation importance evaluator. It works by shuffling one or more features on test_data dataframe, getting the preditions with predict_fn, and evaluating the results with eval_fn. Parameters ---------- test_data : Pandas' DataFrame A Pandas' DataFrame with with target, predict...
time_col if split_values is None: split_values = unique_values else: if not (all(sv in unique_values for sv in split_values)): raise ValueError('All split values must be present in the column (after date formatting it') return {eval_name + "_" + str(value): eval_fn(test_data.l...
159
159
532
70
89
WesleyBatista/fklearn
src/fklearn/validation/evaluators.py
Python
permutation_evaluator
permutation_evaluator
729
798
729
736
bbe94d88ba3e43751ce2f6679735040d328e6d68
bigcode/the-stack
train
7d858a38038c4bfd188f959f
train
function
@curry def split_evaluator(test_data: pd.DataFrame, eval_fn: EvalFnType, split_col: str, split_values: Iterable = None, eval_name: str = None) -> EvalReturnType: """ Splits the dataset into the categories in `split_col` and evaluate...
@curry def split_evaluator(test_data: pd.DataFrame, eval_fn: EvalFnType, split_col: str, split_values: Iterable = None, eval_name: str = None) -> EvalReturnType:
""" Splits the dataset into the categories in `split_col` and evaluate model performance in each split. Useful when you belive the model performs differs in a sub population defined by `split_col`. Parameters ---------- test_data : Pandas' DataFrame A Pandas' DataFrame with with tar...
ators: List List of evaluator functions Returns ---------- log: dict A log-like dictionary with the column mean """ return fp.merge(e(test_data) for e in evaluators) @curry def split_evaluator(test_data: pd.DataFrame, eval_fn: EvalFnType, spli...
96
96
323
50
46
WesleyBatista/fklearn
src/fklearn/validation/evaluators.py
Python
split_evaluator
split_evaluator
628
669
628
633
be8504610e44dfc2a43ffc18c62c1778abe00014
bigcode/the-stack
train
740651f351e28836c542d3b6
train
function
def generic_sklearn_evaluator(name_prefix: str, sklearn_metric: Callable[..., float]) -> UncurriedEvalFnType: """ Returns an evaluator build from a metric from sklearn.metrics Parameters ---------- name_prefix: str The default name of the evaluator will be name_prefix + target_column. ...
def generic_sklearn_evaluator(name_prefix: str, sklearn_metric: Callable[..., float]) -> UncurriedEvalFnType:
""" Returns an evaluator build from a metric from sklearn.metrics Parameters ---------- name_prefix: str The default name of the evaluator will be name_prefix + target_column. sklearn_metric: Callable Metric function from sklearn.metrics. It should take as parameters y_true, y_...
r2_score, recall_score, roc_auc_score) from toolz import curry from fklearn.types import (EvalFnType, EvalReturnType, PredictFnType, UncurriedEvalFnType) def generic_sklearn_evaluator(name_prefix: str, sklearn_metric: Callable[..., float]) -> UncurriedEvalFnType...
72
72
240
27
45
WesleyBatista/fklearn
src/fklearn/validation/evaluators.py
Python
generic_sklearn_evaluator
generic_sklearn_evaluator
18
52
18
18
5936e4144fc87503f76a63c04ff6c4af87596232
bigcode/the-stack
train
36e602de29a0455fb528c56c
train
function
@curry def mse_evaluator(test_data: pd.DataFrame, prediction_column: str = "prediction", target_column: str = "target", eval_name: str = None) -> EvalReturnType: """ Computes the Mean Squared Error, given true label and predictions. Parameters -----...
@curry def mse_evaluator(test_data: pd.DataFrame, prediction_column: str = "prediction", target_column: str = "target", eval_name: str = None) -> EvalReturnType:
""" Computes the Mean Squared Error, given true label and predictions. Parameters ---------- test_data : Pandas' DataFrame A Pandas' DataFrame with with target and predictions. prediction_column : Strings The name of the column in `test_data` with the predictions. target_c...
2_score) return eval_fn(test_data, prediction_column, target_column, eval_name) @curry def mse_evaluator(test_data: pd.DataFrame, prediction_column: str = "prediction", target_column: str = "target", eval_name: str = None) -> EvalReturnType:
65
65
217
46
19
WesleyBatista/fklearn
src/fklearn/validation/evaluators.py
Python
mse_evaluator
mse_evaluator
472
501
472
476
c34b0daf33fbab608abce13102946977ab96e81a
bigcode/the-stack
train
13241b969a64700fece00d9c
train
function
@curry def temporal_split_evaluator(test_data: pd.DataFrame, eval_fn: EvalFnType, time_col: str, time_format: str = "%Y-%m", split_values: Iterable[str] = None, eval_name: str...
@curry def temporal_split_evaluator(test_data: pd.DataFrame, eval_fn: EvalFnType, time_col: str, time_format: str = "%Y-%m", split_values: Iterable[str] = None, eval_name: str...
""" Splits the dataset into the temporal categories by `time_col` and evaluate model performance in each split. The splits are implicitly defined by the `time_format`. For example, for the default time format ("%Y-%m"), we will split by year and month. Parameters ---------- test_data :...
= test_data[split_col].unique() if eval_name is None: eval_name = 'split_evaluator__' + split_col return {eval_name + "_" + str(value): eval_fn(test_data.loc[lambda df: df[split_col] == value]) for value in split_values} @curry def temporal_split_evaluator(test_data: pd.DataFrame, ...
129
129
430
64
65
WesleyBatista/fklearn
src/fklearn/validation/evaluators.py
Python
temporal_split_evaluator
temporal_split_evaluator
672
726
672
678
69b7bee0aabfda92b01818c7784f59458cba69bf
bigcode/the-stack
train
99326e0b0dfbe2fe354feec0
train
function
@curry def logloss_evaluator(test_data: pd.DataFrame, prediction_column: str = "prediction", target_column: str = "target", eval_name: str = None) -> EvalReturnType: """ Computes the logloss score, given true label and prediction scores. Par...
@curry def logloss_evaluator(test_data: pd.DataFrame, prediction_column: str = "prediction", target_column: str = "target", eval_name: str = None) -> EvalReturnType:
""" Computes the logloss score, given true label and prediction scores. Parameters ---------- test_data : Pandas' DataFrame A Pandas' DataFrame with with target and prediction scores. prediction_column : Strings The name of the column in `test_data` with the prediction scores. ...
__", fbeta_score) return eval_fn(eval_data, prediction_column, target_column, eval_name, beta=beta) @curry def logloss_evaluator(test_data: pd.DataFrame, prediction_column: str = "prediction", target_column: str = "target", eval_name: str = None) ->...
72
72
242
47
25
WesleyBatista/fklearn
src/fklearn/validation/evaluators.py
Python
logloss_evaluator
logloss_evaluator
281
312
281
285
60dccca404506f509ac4bbed8e92f55de0689334
bigcode/the-stack
train
ac13975206dac22b68b94b32
train
function
@curry def expected_calibration_error_evaluator(test_data: pd.DataFrame, prediction_column: str = "prediction", target_column: str = "target", eval_name: str = None, ...
@curry def expected_calibration_error_evaluator(test_data: pd.DataFrame, prediction_column: str = "prediction", target_column: str = "target", eval_name: str = None, ...
""" Computes the expected calibration error (ECE), given true label and prediction scores. See "On Calibration of Modern Neural Networks"(https://arxiv.org/abs/1706.04599) for more information. The ECE is the distance between the actuals observed frequency and the predicted probabilities, for a giv...
: Pandas' DataFrame A Pandas' DataFrame with with target and prediction scores. prediction_column : Strings The name of the column in `test_data` with the prediction scores. target_column : String The name of the column in `test_data` with the binary target. eval_name : String, o...
241
241
805
67
174
WesleyBatista/fklearn
src/fklearn/validation/evaluators.py
Python
expected_calibration_error_evaluator
expected_calibration_error_evaluator
349
436
349
355
c4a01f1da4748173dc5ee873504f02779968c361
bigcode/the-stack
train
f4bc0c07ff9f59512bbb6248
train
function
@curry def brier_score_evaluator(test_data: pd.DataFrame, prediction_column: str = "prediction", target_column: str = "target", eval_name: str = None) -> EvalReturnType: """ Computes the Brier score, given true label and prediction sc...
@curry def brier_score_evaluator(test_data: pd.DataFrame, prediction_column: str = "prediction", target_column: str = "target", eval_name: str = None) -> EvalReturnType:
""" Computes the Brier score, given true label and prediction scores. Parameters ---------- test_data : Pandas' DataFrame A Pandas' DataFrame with with target and prediction scores. prediction_column : Strings The name of the column in `test_data` with the prediction scores. ...
: df[target_column].astype(int)}) return eval_fn(eval_data, prediction_column, target_column, eval_name) @curry def brier_score_evaluator(test_data: pd.DataFrame, prediction_column: str = "prediction", target_column: str = "target", eval...
73
73
246
48
25
WesleyBatista/fklearn
src/fklearn/validation/evaluators.py
Python
brier_score_evaluator
brier_score_evaluator
315
346
315
319
81d337318d5f1466daf8ef796d90c612a3d89f6e
bigcode/the-stack
train
215e1c7cd1bc8753ce5ad3e1
train
function
@curry def fbeta_score_evaluator(test_data: pd.DataFrame, threshold: float = 0.5, beta: float = 1.0, prediction_column: str = "prediction", target_column: str = "target", eval_name: str = No...
@curry def fbeta_score_evaluator(test_data: pd.DataFrame, threshold: float = 0.5, beta: float = 1.0, prediction_column: str = "prediction", target_column: str = "target", eval_name: str = No...
""" Computes the F-beta score, given true label and prediction scores. Parameters ---------- test_data : pandas.DataFrame A Pandas' DataFrame with with target and prediction scores. threshold : float A threshold for the prediction column above which samples will be cl...
)}) eval_fn = generic_sklearn_evaluator("recall_evaluator__", recall_score) return eval_fn(eval_data, prediction_column, target_column, eval_name) @curry def fbeta_score_evaluator(test_data: pd.DataFrame, threshold: float = 0.5, beta: float = 1.0, ...
104
104
347
68
36
WesleyBatista/fklearn
src/fklearn/validation/evaluators.py
Python
fbeta_score_evaluator
fbeta_score_evaluator
235
278
235
241
be6541fa661bd85efef28db266a9aed92ea10f82
bigcode/the-stack
train
9cfe35b82cd63e92cfbdaf1f
train
function
@curry def precision_evaluator(test_data: pd.DataFrame, threshold: float = 0.5, prediction_column: str = "prediction", target_column: str = "target", eval_name: str = None) -> EvalReturnType: """ Computes the precisi...
@curry def precision_evaluator(test_data: pd.DataFrame, threshold: float = 0.5, prediction_column: str = "prediction", target_column: str = "target", eval_name: str = None) -> EvalReturnType:
""" Computes the precision score, given true label and prediction scores. Parameters ---------- test_data : pandas.DataFrame A Pandas' DataFrame with with target and prediction scores. threshold : float A threshold for the prediction column above which samples will be ...
df: df[target_column].astype(int)}) return eval_fn(eval_data, prediction_column, target_column, eval_name) @curry def precision_evaluator(test_data: pd.DataFrame, threshold: float = 0.5, prediction_column: str = "prediction", target_column: s...
82
82
274
56
26
WesleyBatista/fklearn
src/fklearn/validation/evaluators.py
Python
precision_evaluator
precision_evaluator
157
192
157
162
0d80da47057e1e1c1b17f3e0920e74b913513695
bigcode/the-stack
train
ee538ac88215d60837aa54e7
train
function
@curry def pr_auc_evaluator(test_data: pd.DataFrame, prediction_column: str = "prediction", target_column: str = "target", eval_name: str = None) -> EvalReturnType: """ Computes the PR AUC score, given true label and prediction scores. Paramete...
@curry def pr_auc_evaluator(test_data: pd.DataFrame, prediction_column: str = "prediction", target_column: str = "target", eval_name: str = None) -> EvalReturnType:
""" Computes the PR AUC score, given true label and prediction scores. Parameters ---------- test_data : Pandas' DataFrame A Pandas' DataFrame with target and prediction scores. prediction_column : Strings The name of the column in `test_data` with the prediction scores. t...
df[target_column].astype(int)}) return eval_fn(eval_data, prediction_column, target_column, eval_name) @curry def pr_auc_evaluator(test_data: pd.DataFrame, prediction_column: str = "prediction", target_column: str = "target", eval_name: str = None) ->...
71
71
239
47
24
WesleyBatista/fklearn
src/fklearn/validation/evaluators.py
Python
pr_auc_evaluator
pr_auc_evaluator
124
154
124
128
a6e36c761a1154be624c7e1bbd473a62ac6cd40d
bigcode/the-stack
train
e0d28b287b42a149d897df03
train
function
@curry def auc_evaluator(test_data: pd.DataFrame, prediction_column: str = "prediction", target_column: str = "target", eval_name: str = None) -> EvalReturnType: """ Computes the ROC AUC score, given true label and prediction scores. Parameters ----...
@curry def auc_evaluator(test_data: pd.DataFrame, prediction_column: str = "prediction", target_column: str = "target", eval_name: str = None) -> EvalReturnType:
""" Computes the ROC AUC score, given true label and prediction scores. Parameters ---------- test_data : Pandas' DataFrame A Pandas' DataFrame with target and prediction scores. prediction_column : Strings The name of the column in `test_data` with the prediction scores. ...
score = np.nan if eval_name is None: eval_name = name_prefix + target_column return {eval_name: score} return p @curry def auc_evaluator(test_data: pd.DataFrame, prediction_column: str = "prediction", target_column: str = "target", ...
80
80
267
46
33
WesleyBatista/fklearn
src/fklearn/validation/evaluators.py
Python
auc_evaluator
auc_evaluator
55
87
55
59
6f32d9cd4cb64e7ede31a90cc2bb7b19c355f572
bigcode/the-stack
train
8d40e85ba17af22313c38b67
train
function
@curry def roc_auc_evaluator(test_data: pd.DataFrame, prediction_column: str = "prediction", target_column: str = "target", eval_name: str = None) -> EvalReturnType: """ Computes the ROC AUC score, given true label and prediction scores. Par...
@curry def roc_auc_evaluator(test_data: pd.DataFrame, prediction_column: str = "prediction", target_column: str = "target", eval_name: str = None) -> EvalReturnType:
""" Computes the ROC AUC score, given true label and prediction scores. Parameters ---------- test_data : Pandas' DataFrame A Pandas' DataFrame with target and prediction scores. prediction_column : Strings The name of the column in `test_data` with the prediction scores. ...
" " Receiver Operating Characteristics curve.") return roc_auc_evaluator(test_data, prediction_column, target_column, eval_name) @curry def roc_auc_evaluator(test_data: pd.DataFrame, prediction_column: str = "prediction", target_column: str = "target", ...
73
73
244
47
26
WesleyBatista/fklearn
src/fklearn/validation/evaluators.py
Python
roc_auc_evaluator
roc_auc_evaluator
90
121
90
94
274d434d943e93de2c8ed3aa605a1415533fffc1
bigcode/the-stack
train
5bfe34a9496fc4738de568d5
train
function
@curry def correlation_evaluator(test_data: pd.DataFrame, prediction_column: str = "prediction", target_column: str = "target", eval_name: str = None) -> EvalReturnType: """ Computes the Pearson correlation between prediction and targ...
@curry def correlation_evaluator(test_data: pd.DataFrame, prediction_column: str = "prediction", target_column: str = "target", eval_name: str = None) -> EvalReturnType:
""" Computes the Pearson correlation between prediction and target. Parameters ---------- test_data : Pandas' DataFrame A Pandas' DataFrame with with target and prediction. prediction_column : Strings The name of the column in `test_data` with the prediction. target_column...
valuator__' + prediction_column return {eval_name: test_data[prediction_column].mean()} @curry def correlation_evaluator(test_data: pd.DataFrame, prediction_column: str = "prediction", target_column: str = "target", eval_name: str = None...
68
69
231
46
22
WesleyBatista/fklearn
src/fklearn/validation/evaluators.py
Python
correlation_evaluator
correlation_evaluator
534
566
534
538
95f8c770fdd68209d6cee54578f7fb59fb5a01e2
bigcode/the-stack
train
b28396bb9591ca77877c1e2e
train
function
@curry def hash_evaluator(test_data: pd.DataFrame, hash_columns: List[str] = None, eval_name: str = None, consider_index: bool = False) -> EvalReturnType: """ Computes the hash of a pandas dataframe, filtered by hash columns. The purpose is to uniquel...
@curry def hash_evaluator(test_data: pd.DataFrame, hash_columns: List[str] = None, eval_name: str = None, consider_index: bool = False) -> EvalReturnType:
""" Computes the hash of a pandas dataframe, filtered by hash columns. The purpose is to uniquely identify a dataframe, to be able to check if two dataframes are equal or not. Parameters ---------- test_data : Pandas' DataFrame A Pandas' DataFrame to be hashed. hash_columns : L...
permutation_results = {f: permutation_eval([f]) for f in features} feature_importance = {'permutation_importance': permutation_results} if baseline: baseline_results = {'permutation_importance_baseline': eval_fn(predict_fn(test_data))} else: baseline_results = {} return fp.mer...
120
120
401
46
74
WesleyBatista/fklearn
src/fklearn/validation/evaluators.py
Python
hash_evaluator
hash_evaluator
801
847
801
805
ce8251976917dd4977aedf61b3f849960fd0e3df
bigcode/the-stack
train
e8c2affd6d96ddc6dfceccd3
train
function
@curry def spearman_evaluator(test_data: pd.DataFrame, prediction_column: str = "prediction", target_column: str = "target", eval_name: str = None) -> EvalReturnType: """ Computes the Spearman correlation between prediction and target. The...
@curry def spearman_evaluator(test_data: pd.DataFrame, prediction_column: str = "prediction", target_column: str = "target", eval_name: str = None) -> EvalReturnType:
""" Computes the Spearman correlation between prediction and target. The Spearman correlation evaluates the rank order between two variables: https://en.wikipedia.org/wiki/Spearman%27s_rank_correlation_coefficient Parameters ---------- test_data : Pandas' DataFrame A Pandas' DataFra...
score = test_data[[prediction_column, target_column]].corr(method="pearson").iloc[0, 1] return {eval_name: score} @curry def spearman_evaluator(test_data: pd.DataFrame, prediction_column: str = "prediction", target_column: str = "target", eval_na...
79
79
266
47
32
WesleyBatista/fklearn
src/fklearn/validation/evaluators.py
Python
spearman_evaluator
spearman_evaluator
569
603
569
573
295cfabe69ca4fe0a22ecaecd78e91197d403ba4
bigcode/the-stack
train
5efacb67236ef6fc45d3fa0f
train
function
@curry def recall_evaluator(test_data: pd.DataFrame, threshold: float = 0.5, prediction_column: str = "prediction", target_column: str = "target", eval_name: str = None) -> EvalReturnType: """ Computes the recall score, given tr...
@curry def recall_evaluator(test_data: pd.DataFrame, threshold: float = 0.5, prediction_column: str = "prediction", target_column: str = "target", eval_name: str = None) -> EvalReturnType:
""" Computes the recall score, given true label and prediction scores. Parameters ---------- test_data : pandas.DataFrame A Pandas' DataFrame with with target and prediction scores. threshold : float A threshold for the prediction column above which samples will be cl...
iction_column] > threshold).astype(int)}) return eval_fn(eval_data, prediction_column, target_column, eval_name) @curry def recall_evaluator(test_data: pd.DataFrame, threshold: float = 0.5, prediction_column: str = "prediction", target_column: str = "t...
82
82
275
56
26
WesleyBatista/fklearn
src/fklearn/validation/evaluators.py
Python
recall_evaluator
recall_evaluator
195
232
195
200
9590d77225534559ee2b2e885656f45aea6acf30
bigcode/the-stack
train
3a9c542c0fe32db22d8f4521
train
function
@curry def combined_evaluators(test_data: pd.DataFrame, evaluators: List[EvalFnType]) -> EvalReturnType: """ Combine partially applies evaluation functions. Parameters ---------- test_data : Pandas' DataFrame A Pandas' DataFrame to apply the evaluators on evalua...
@curry def combined_evaluators(test_data: pd.DataFrame, evaluators: List[EvalFnType]) -> EvalReturnType:
""" Combine partially applies evaluation functions. Parameters ---------- test_data : Pandas' DataFrame A Pandas' DataFrame to apply the evaluators on evaluators: List List of evaluator functions Returns ---------- log: dict A log-like dictionary with the c...
score = test_data[[prediction_column, target_column]].corr(method="spearman").iloc[0, 1] return {eval_name: score} @curry def combined_evaluators(test_data: pd.DataFrame, evaluators: List[EvalFnType]) -> EvalReturnType:
64
64
117
31
33
WesleyBatista/fklearn
src/fklearn/validation/evaluators.py
Python
combined_evaluators
combined_evaluators
606
625
606
608
097b2fcf26dd503d2b2e219b80b87df5faca26e5
bigcode/the-stack
train
2223193d2cea283eb124888e
train
function
@curry def r2_evaluator(test_data: pd.DataFrame, prediction_column: str = "prediction", target_column: str = "target", eval_name: str = None) -> EvalReturnType: """ Computes the R2 score, given true label and predictions. Parameters ---------- test...
@curry def r2_evaluator(test_data: pd.DataFrame, prediction_column: str = "prediction", target_column: str = "target", eval_name: str = None) -> EvalReturnType:
""" Computes the R2 score, given true label and predictions. Parameters ---------- test_data : Pandas' DataFrame A Pandas' DataFrame with with target and prediction. prediction_column : Strings The name of the column in `test_data` with the prediction. target_column : Stri...
ictions"].values, sample_weight=sample_weight) return {eval_name: distance} @curry def r2_evaluator(test_data: pd.DataFrame, prediction_column: str = "prediction", target_column: str = "target", eval_name: str = None) -> EvalReturnType:
65
65
217
47
18
WesleyBatista/fklearn
src/fklearn/validation/evaluators.py
Python
r2_evaluator
r2_evaluator
439
469
439
443
e055eb23e07914807d27540c6e58291001dc6598
bigcode/the-stack
train
c68c6f5fafe0c8aeca5d7f50
train
function
def get_runner_cls(runner): '''Get a runner's class object, given its name.''' for cls in ZephyrBinaryRunner.get_runners(): if cls.name() == runner: return cls raise ValueError('unknown runner "{}"'.format(runner))
def get_runner_cls(runner):
'''Get a runner's class object, given its name.''' for cls in ZephyrBinaryRunner.get_runners(): if cls.name() == runner: return cls raise ValueError('unknown runner "{}"'.format(runner))
2 from west.runners import nrfjprog from west.runners import nsim from west.runners import openocd from west.runners import pyocd from west.runners import qemu from west.runners import xtensa from west.runners import intel_s1000 def get_runner_cls(runner):
64
64
59
7
56
ulfalizer/west
src/west/runners/__init__.py
Python
get_runner_cls
get_runner_cls
27
32
27
27
493a8e2088ceeec613e15ebbe11a3ec87a54e7c8
bigcode/the-stack
train
9690f7c953564d2f7884bc8a
train
class
class SomeRandomBenchmark(test.Benchmark): """This Benchmark should automatically be registered in the registry.""" def _dontRunThisBenchmark(self): _ran_somebenchmark_but_shouldnt[0] = True def notBenchmarkMethod(self): _ran_somebenchmark_but_shouldnt[0] = True def benchmark1(self): _ran_someben...
class SomeRandomBenchmark(test.Benchmark):
"""This Benchmark should automatically be registered in the registry.""" def _dontRunThisBenchmark(self): _ran_somebenchmark_but_shouldnt[0] = True def notBenchmarkMethod(self): _ran_somebenchmark_but_shouldnt[0] = True def benchmark1(self): _ran_somebenchmark_1[0] = True def benchmark2(self):...
from tensorflow.python.platform import gfile from tensorflow.python.platform import test # Used by SomeRandomBenchmark class below. _ran_somebenchmark_1 = [False] _ran_somebenchmark_2 = [False] _ran_somebenchmark_but_shouldnt = [False] class SomeRandomBenchmark(test.Benchmark):
64
64
104
8
56
fraudies/tensorflow
tensorflow/python/kernel_tests/benchmark_test.py
Python
SomeRandomBenchmark
SomeRandomBenchmark
39
52
39
39
c43fa9da53280c0fad64f1db86aa934c89dad114
bigcode/the-stack
train
2e17f7de2a4db17dc597748b
train
class
class BenchmarkTest(test.TestCase): def testGlobalBenchmarkRegistry(self): registry = list(benchmark.GLOBAL_BENCHMARK_REGISTRY) self.assertEqual(len(registry), 2) self.assertTrue(SomeRandomBenchmark in registry) self.assertTrue(TestReportingBenchmark in registry) def testRunSomeRandomBenchmark(sel...
class BenchmarkTest(test.TestCase):
def testGlobalBenchmarkRegistry(self): registry = list(benchmark.GLOBAL_BENCHMARK_REGISTRY) self.assertEqual(len(registry), 2) self.assertTrue(SomeRandomBenchmark in registry) self.assertTrue(TestReportingBenchmark in registry) def testRunSomeRandomBenchmark(self): # Validate that SomeBenchmark...
"""This Benchmark should automatically be registered in the registry.""" def _dontRunThisBenchmark(self): _ran_somebenchmark_but_shouldnt[0] = True def notBenchmarkMethod(self): _ran_somebenchmark_but_shouldnt[0] = True def benchmark1(self): _ran_somebenchmark_1[0] = True def benchmark2(self): ...
256
256
1,307
7
249
fraudies/tensorflow
tensorflow/python/kernel_tests/benchmark_test.py
Python
BenchmarkTest
BenchmarkTest
76
207
76
77
16aca2ebe794b7cff00e78ab3adfcc2200390bd6
bigcode/the-stack
train
d085065b7b561d1212b9de46
train
class
class TestReportingBenchmark(test.Benchmark): """This benchmark (maybe) reports some stuff.""" def benchmarkReport1(self): self.report_benchmark(iters=1) def benchmarkReport2(self): self.report_benchmark( iters=2, name="custom_benchmark_name", extras={"number_key": 3, ...
class TestReportingBenchmark(test.Benchmark):
"""This benchmark (maybe) reports some stuff.""" def benchmarkReport1(self): self.report_benchmark(iters=1) def benchmarkReport2(self): self.report_benchmark( iters=2, name="custom_benchmark_name", extras={"number_key": 3, "other_key": "string"}) def benchmark_...
Method(self): _ran_somebenchmark_but_shouldnt[0] = True def benchmark1(self): _ran_somebenchmark_1[0] = True def benchmark2(self): _ran_somebenchmark_2[0] = True class TestReportingBenchmark(test.Benchmark):
64
64
154
8
55
fraudies/tensorflow
tensorflow/python/kernel_tests/benchmark_test.py
Python
TestReportingBenchmark
TestReportingBenchmark
55
73
55
55
244bed69878cc6a8bc0cd8c7ad3041124ba832fb
bigcode/the-stack
train
aa8a355d724c9a4c56c0f75a
train
class
class Unseekable: def __init__(self, fp): self.fp = fp def write(self, data): return self.fp.write(data) def flush(self): self.fp.flush()
class Unseekable:
def __init__(self, fp): self.fp = fp def write(self, data): return self.fp.write(data) def flush(self): self.fp.flush()
): self.fp = fp self.offset = 0 def write(self, data): n = self.fp.write(data) self.offset += n return n def tell(self): return self.offset def flush(self): self.fp.flush() class Unseekable:
64
64
44
5
59
oleksandr-pavlyk/cpython
Lib/test/test_zipfile.py
Python
Unseekable
Unseekable
2,379
2,387
2,379
2,379
250e0475d3d4113549198d77ff8ed26199917a38
bigcode/the-stack
train
4a733e71d660ba0720901d78
train
class
@requires_bz2() class Bzip2TestsWithSourceFile(AbstractTestsWithSourceFile, unittest.TestCase): compression = zipfile.ZIP_BZIP2
@requires_bz2() class Bzip2TestsWithSourceFile(AbstractTestsWithSourceFile, unittest.TestCase):
compression = zipfile.ZIP_BZIP2
('deflateme') self.assertEqual(sinfo.compress_type, zipfile.ZIP_STORED) self.assertEqual(dinfo.compress_type, zipfile.ZIP_DEFLATED) @requires_bz2() class Bzip2TestsWithSourceFile(AbstractTestsWithSourceFile, unittest.TestCase):
64
64
36
25
39
oleksandr-pavlyk/cpython
Lib/test/test_zipfile.py
Python
Bzip2TestsWithSourceFile
Bzip2TestsWithSourceFile
663
666
663
665
0e56f1b5e6fa289b2454b17bc512d4f5ad0df734
bigcode/the-stack
train
53d8d03a6f7072708402eb78
train
class
@requires_lzma() class LzmaBadCrcTests(AbstractBadCrcTests, unittest.TestCase): compression = zipfile.ZIP_LZMA zip_with_bad_crc = ( b'PK\x03\x04\x14\x03\x00\x00\x0e\x00nu\x0c=FA' b'KE\x1b\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00af' b'ile\t\x04\x05\x00]\x00\x00\x00\x04\x004\x19I' ...
@requires_lzma() class LzmaBadCrcTests(AbstractBadCrcTests, unittest.TestCase):
compression = zipfile.ZIP_LZMA zip_with_bad_crc = ( b'PK\x03\x04\x14\x03\x00\x00\x0e\x00nu\x0c=FA' b'KE\x1b\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00af' b'ile\t\x04\x05\x00]\x00\x00\x00\x04\x004\x19I' b'\xee\x8d\xe9\x17\x89:3`\tq!.8\x00PK' b'\x01\x02\x14\x03\x14\x03\x00\x0...
x80\x80\x81\x00\x00\x00\x00afilePK' b'\x05\x06\x00\x00\x00\x00\x01\x00\x01\x003\x00\x00\x00[\x00' b'\x00\x00\x00\x00') @requires_lzma() class LzmaBadCrcTests(AbstractBadCrcTests, unittest.TestCase):
86
86
288
24
62
oleksandr-pavlyk/cpython
Lib/test/test_zipfile.py
Python
LzmaBadCrcTests
LzmaBadCrcTests
2,120
2,132
2,120
2,121
c80bdf5b0942effc508438b2f856711e3ae550d3
bigcode/the-stack
train
18e12c68a232f09b03af0593
train
class
class TestWithDirectory(unittest.TestCase): def setUp(self): os.mkdir(TESTFN2) def test_extract_dir(self): with zipfile.ZipFile(findfile("zipdir.zip")) as zipf: zipf.extractall(TESTFN2) self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a"))) self.assertTrue(os.pat...
class TestWithDirectory(unittest.TestCase):
def setUp(self): os.mkdir(TESTFN2) def test_extract_dir(self): with zipfile.ZipFile(findfile("zipdir.zip")) as zipf: zipf.extractall(TESTFN2) self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a"))) self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a", "b"))) ...
.open('ones') as zopen1: pass self.assertEqual(startcount, fd_count()) def test_write_while_reading(self): with zipfile.ZipFile(TESTFN2, 'w', zipfile.ZIP_DEFLATED) as zipf: zipf.writestr('ones', self.data1) with zipfile.ZipFile(TESTFN2, 'a', zipfile.ZIP_DEFLA...
212
212
707
8
204
oleksandr-pavlyk/cpython
Lib/test/test_zipfile.py
Python
TestWithDirectory
TestWithDirectory
2,570
2,632
2,570
2,570
5bf1ce6505f932667e6ee9b64d95302d82a0635d
bigcode/the-stack
train
79a0a67364eefbfcbba24236
train
class
@requires_bz2() class Bzip2TestsWithRandomBinaryFiles(AbstractTestsWithRandomBinaryFiles, unittest.TestCase): compression = zipfile.ZIP_BZIP2
@requires_bz2() class Bzip2TestsWithRandomBinaryFiles(AbstractTestsWithRandomBinaryFiles, unittest.TestCase):
compression = zipfile.ZIP_BZIP2
@requires_zlib() class DeflateTestsWithRandomBinaryFiles(AbstractTestsWithRandomBinaryFiles, unittest.TestCase): compression = zipfile.ZIP_DEFLATED @requires_bz2() class Bzip2TestsWithRandomBinaryFiles(AbstractTestsWithRandomBinaryFiles, ...
64
64
38
27
36
oleksandr-pavlyk/cpython
Lib/test/test_zipfile.py
Python
Bzip2TestsWithRandomBinaryFiles
Bzip2TestsWithRandomBinaryFiles
2,351
2,354
2,351
2,353
f19b6018cadef5a857249da8b8f0a585bdc602fd
bigcode/the-stack
train
fc35fc5a95635531b6fce720
train
class
@requires_lzma() class LzmaWriterTests(AbstractWriterTests, unittest.TestCase): compression = zipfile.ZIP_LZMA
@requires_lzma() class LzmaWriterTests(AbstractWriterTests, unittest.TestCase):
compression = zipfile.ZIP_LZMA
Case): compression = zipfile.ZIP_DEFLATED @requires_bz2() class Bzip2WriterTests(AbstractWriterTests, unittest.TestCase): compression = zipfile.ZIP_BZIP2 @requires_lzma() class LzmaWriterTests(AbstractWriterTests, unittest.TestCase):
64
64
31
20
43
oleksandr-pavlyk/cpython
Lib/test/test_zipfile.py
Python
LzmaWriterTests
LzmaWriterTests
1,135
1,137
1,135
1,136
cdc6024995c9304559087a903e38dd3aa4c3ac3b
bigcode/the-stack
train
3d2a9f92a874975f992c0270
train
class
@requires_lzma() class LzmaTestsWithRandomBinaryFiles(AbstractTestsWithRandomBinaryFiles, unittest.TestCase): compression = zipfile.ZIP_LZMA
@requires_lzma() class LzmaTestsWithRandomBinaryFiles(AbstractTestsWithRandomBinaryFiles, unittest.TestCase):
compression = zipfile.ZIP_LZMA
requires_bz2() class Bzip2TestsWithRandomBinaryFiles(AbstractTestsWithRandomBinaryFiles, unittest.TestCase): compression = zipfile.ZIP_BZIP2 @requires_lzma() class LzmaTestsWithRandomBinaryFiles(AbstractTestsWithRandomBinaryFiles, unittest.T...
64
64
38
27
36
oleksandr-pavlyk/cpython
Lib/test/test_zipfile.py
Python
LzmaTestsWithRandomBinaryFiles
LzmaTestsWithRandomBinaryFiles
2,356
2,359
2,356
2,358
dec57ec314cdd946de7f36410e82fcfc70267930
bigcode/the-stack
train
5c1b96f21fd4d5b9594c0f6b
train
class
class ZipInfoTests(unittest.TestCase): def test_from_file(self): zi = zipfile.ZipInfo.from_file(__file__) self.assertEqual(posixpath.basename(zi.filename), 'test_zipfile.py') self.assertFalse(zi.is_dir()) self.assertEqual(zi.file_size, os.path.getsize(__file__)) def test_from_fi...
class ZipInfoTests(unittest.TestCase):
def test_from_file(self): zi = zipfile.ZipInfo.from_file(__file__) self.assertEqual(posixpath.basename(zi.filename), 'test_zipfile.py') self.assertFalse(zi.is_dir()) self.assertEqual(zi.file_size, os.path.getsize(__file__)) def test_from_file_pathlike(self): zi = zipfile...
/")) self.assertEqual(zinfo.external_attr, (0o40775 << 16) | 0x10) target = os.path.join(TESTFN2, "target") os.mkdir(target) zipf.extractall(target) self.assertTrue(os.path.isdir(os.path.join(target, "x"))) self.assertEqual(os.listdir(target), ["x"...
111
111
370
8
103
oleksandr-pavlyk/cpython
Lib/test/test_zipfile.py
Python
ZipInfoTests
ZipInfoTests
2,635
2,667
2,635
2,635
accde98ab6143716530a0c94d0d8b1746d7443b6
bigcode/the-stack
train
b939c4ccebf7b9278b5b6469
train
class
class UnseekableTests(unittest.TestCase): def test_writestr(self): for wrapper in (lambda f: f), Tellable, Unseekable: with self.subTest(wrapper=wrapper): f = io.BytesIO() f.write(b'abc') bf = io.BufferedWriter(f) with zipfile.ZipFi...
class UnseekableTests(unittest.TestCase):
def test_writestr(self): for wrapper in (lambda f: f), Tellable, Unseekable: with self.subTest(wrapper=wrapper): f = io.BytesIO() f.write(b'abc') bf = io.BufferedWriter(f) with zipfile.ZipFile(wrapper(bf), 'w', zipfile.ZIP_STORED) a...
): compression = zipfile.ZIP_BZIP2 @requires_lzma() class LzmaTestsWithRandomBinaryFiles(AbstractTestsWithRandomBinaryFiles, unittest.TestCase): compression = zipfile.ZIP_LZMA # Provide the tell() method but not seek() class Tellable: def __init__(self, fp): s...
184
184
615
9
175
oleksandr-pavlyk/cpython
Lib/test/test_zipfile.py
Python
UnseekableTests
UnseekableTests
2,389
2,441
2,389
2,389
f106de1e430c275f49bb0073bd66e570b51d0704
bigcode/the-stack
train
fd6a2be76a9f9b537646b14f
train
class
class AbstractBadCrcTests: def test_testzip_with_bad_crc(self): """Tests that files with bad CRCs return their name from testzip.""" zipdata = self.zip_with_bad_crc with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf: # testzip returns the name of the first corrupt file,...
class AbstractBadCrcTests:
def test_testzip_with_bad_crc(self): """Tests that files with bad CRCs return their name from testzip.""" zipdata = self.zip_with_bad_crc with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf: # testzip returns the name of the first corrupt file, or None self.a...
', compression=zipfile.ZIP_BZIP2) as zf: zf.writestr('a.txt', b'a') with mock.patch('zipfile.bz2', None): with zipfile.ZipFile(zip_file) as zf: self.assertRaises(RuntimeError, zf.extract, 'a.txt') def tearDown(self): unlink(TESTFN) unlink(TESTFN2) cla...
93
93
311
7
86
oleksandr-pavlyk/cpython
Lib/test/test_zipfile.py
Python
AbstractBadCrcTests
AbstractBadCrcTests
2,048
2,076
2,048
2,048
722797dd3946debfbd0bd5601205f371f4ebeb0c
bigcode/the-stack
train
9f169e8bda10d045a8e398a2
train
class
class StoredTestZip64InSmallFiles(AbstractTestZip64InSmallFiles, unittest.TestCase): compression = zipfile.ZIP_STORED def large_file_exception_test(self, f, compression): with zipfile.ZipFile(f, "w", compression, allowZip64=False) as zipfp: self.assertRaise...
class StoredTestZip64InSmallFiles(AbstractTestZip64InSmallFiles, unittest.TestCase):
compression = zipfile.ZIP_STORED def large_file_exception_test(self, f, compression): with zipfile.ZipFile(f, "w", compression, allowZip64=False) as zipfp: self.assertRaises(zipfile.LargeZipFile, zipfp.write, TESTFN, "another.name") def large_file_exceptio...
, "a", self.compression, allowZip64=True) zipf.debug = 100 self.assertEqual(len(zipf.namelist()), numfiles) numfiles2 = 15 for i in range(numfiles, numfiles2): zipf.writestr("foo%08d" % i, "%d" % (i**3 % 57)) self.assertEqual(len(zipf.na...
256
256
2,610
21
235
oleksandr-pavlyk/cpython
Lib/test/test_zipfile.py
Python
StoredTestZip64InSmallFiles
StoredTestZip64InSmallFiles
820
1,079
820
821
0938cf312de8570c64bbb261fd4733c6ea63ecfd
bigcode/the-stack
train
fe91644cc16658e77c3b41d0
train
class
class AbstractTestsWithSourceFile: @classmethod def setUpClass(cls): cls.line_gen = [bytes("Zipfile test line %d. random float: %f\n" % (i, random()), "ascii") for i in range(FIXEDTEST_SIZE)] cls.data = b''.join(cls.line_gen) def setUp(s...
class AbstractTestsWithSourceFile: @classmethod
def setUpClass(cls): cls.line_gen = [bytes("Zipfile test line %d. random float: %f\n" % (i, random()), "ascii") for i in range(FIXEDTEST_SIZE)] cls.data = b''.join(cls.line_gen) def setUp(self): # Make a source file with some lines ...
test.support import (findfile, requires_zlib, requires_bz2, requires_lzma, captured_stdout, requires_subprocess) from test.support.os_helper import ( TESTFN, unlink, rmtree, temp_dir, temp_cwd, fd_count ) TESTFN2 = TESTFN + "2" TESTFNDIR = TESTFN + "d" FIXEDTEST_SIZE = 1000 DATAFILES_DI...
256
256
3,449
11
245
oleksandr-pavlyk/cpython
Lib/test/test_zipfile.py
Python
AbstractTestsWithSourceFile
AbstractTestsWithSourceFile
49
450
49
50
cd162efb74728099c089428dfc6ea7c56297d0de
bigcode/the-stack
train
9d00ae9c8f71c3d4510891d9
train
class
class AbstractTestZip64InSmallFiles: # These tests test the ZIP64 functionality without using large files, # see test_zipfile64 for proper tests. @classmethod def setUpClass(cls): line_gen = (bytes("Test of zipfile line %d." % i, "ascii") for i in range(0, FIXEDTEST_SIZE)) ...
class AbstractTestZip64InSmallFiles: # These tests test the ZIP64 functionality without using large files, # see test_zipfile64 for proper tests. @classmethod
def setUpClass(cls): line_gen = (bytes("Test of zipfile line %d." % i, "ascii") for i in range(0, FIXEDTEST_SIZE)) cls.data = b'\n'.join(line_gen) def setUp(self): self._limit = zipfile.ZIP64_LIMIT self._filecount_limit = zipfile.ZIP_FILECOUNT_LIMIT z...
IP_DEFLATED def test_per_file_compression(self): """Check that files within a Zip archive can have different compression options.""" with zipfile.ZipFile(TESTFN2, "w") as zipfp: zipfp.write(TESTFN, 'storeme', zipfile.ZIP_STORED) zipfp.write(TESTFN, 'deflateme', zipfi...
256
256
1,409
38
217
oleksandr-pavlyk/cpython
Lib/test/test_zipfile.py
Python
AbstractTestZip64InSmallFiles
AbstractTestZip64InSmallFiles
674
817
674
678
6a99468b46255b15940f53fe83e5704c957c3365
bigcode/the-stack
train
eb8d51016b965b77b7880a69
train
function
def build_alpharep_fixture(): """ Create a zip file with this structure: . ├── a.txt ├── b │ ├── c.txt │ ├── d │ │ └── e.txt │ └── f.txt └── g └── h └── i.txt This fixture has the following key characteristics: - a file at the root (a) ...
def build_alpharep_fixture():
""" Create a zip file with this structure: . ├── a.txt ├── b │ ├── c.txt │ ├── d │ │ └── e.txt │ └── f.txt └── g └── h └── i.txt This fixture has the following key characteristics: - a file at the root (a) - a file two levels deep (b/d...
self.count += 1 return result def add_dirs(zf): """ Given a writable zip file zf, inject directory entries for any directories implied by the presence of children. """ for name in zipfile.CompleteDirs._implied_dirs(zf.namelist()): zf.writestr(name, b"") return zf def b...
86
86
288
7
78
oleksandr-pavlyk/cpython
Lib/test/test_zipfile.py
Python
build_alpharep_fixture
build_alpharep_fixture
2,821
2,854
2,821
2,821
a1950f22413e78fa3870df2fe6547192487cafbf
bigcode/the-stack
train
0b7eb811401b744fc2240b68
train
class
class TestExecutablePrependedZip(unittest.TestCase): """Test our ability to open zip files with an executable prepended.""" def setUp(self): self.exe_zip = findfile('exe_with_zip', subdir='ziptestdata') self.exe_zip64 = findfile('exe_with_z64', subdir='ziptestdata') def _test_zip_works(sel...
class TestExecutablePrependedZip(unittest.TestCase):
"""Test our ability to open zip files with an executable prepended.""" def setUp(self): self.exe_zip = findfile('exe_with_zip', subdir='ziptestdata') self.exe_zip64 = findfile('exe_with_z64', subdir='ziptestdata') def _test_zip_works(self, name): # bpo28494 sanity check: ensure is_...
filecmd(opt, zip_name, extdir) self.assertEqual(out, b'') with zipfile.ZipFile(zip_name) as zf: for zi in zf.infolist(): path = os.path.join(extdir, zi.filename.replace('/', os.sep)) i...
120
120
400
10
110
oleksandr-pavlyk/cpython
Lib/test/test_zipfile.py
Python
TestExecutablePrependedZip
TestExecutablePrependedZip
2,750
2,787
2,750
2,750
5dd72db3b4103556072e180cb13b8b831309a891
bigcode/the-stack
train
3df5be1de08fdc8420907667
train
class
@requires_zlib() class DeflateWriterTests(AbstractWriterTests, unittest.TestCase): compression = zipfile.ZIP_DEFLATED
@requires_zlib() class DeflateWriterTests(AbstractWriterTests, unittest.TestCase):
compression = zipfile.ZIP_DEFLATED
.assertRaises(ValueError, w.write, b'') self.assertEqual(zipf.read('test'), data) class StoredWriterTests(AbstractWriterTests, unittest.TestCase): compression = zipfile.ZIP_STORED @requires_zlib() class DeflateWriterTests(AbstractWriterTests, unittest.TestCase):
64
64
29
18
45
oleksandr-pavlyk/cpython
Lib/test/test_zipfile.py
Python
DeflateWriterTests
DeflateWriterTests
1,127
1,129
1,127
1,128
45fe4fc37f56da157abb3a7bae40cbbd37a1e3b5
bigcode/the-stack
train
e6f5de39d442aa783bf383b8
train
function
def get_files(test): yield TESTFN2 with TemporaryFile() as f: yield f test.assertFalse(f.closed) with io.BytesIO() as f: yield f test.assertFalse(f.closed)
def get_files(test):
yield TESTFN2 with TemporaryFile() as f: yield f test.assertFalse(f.closed) with io.BytesIO() as f: yield f test.assertFalse(f.closed)
g'), ('ziptest2dir/ziptest3dir/_ziptest3', 'azsxdcfvgb'), ('ziptest2dir/ziptest3dir/ziptest4dir/_ziptest3', '6y7u8i9o0p')] def get_files(test):
63
64
50
5
58
oleksandr-pavlyk/cpython
Lib/test/test_zipfile.py
Python
get_files
get_files
40
47
40
40
3322b8f5e7a3c8178c09ff9e9d8f33556c8d4b0b
bigcode/the-stack
train
66bb19d26b04d8fc204d1a26
train
class
@requires_lzma() class LzmaTestsWithSourceFile(AbstractTestsWithSourceFile, unittest.TestCase): compression = zipfile.ZIP_LZMA
@requires_lzma() class LzmaTestsWithSourceFile(AbstractTestsWithSourceFile, unittest.TestCase):
compression = zipfile.ZIP_LZMA
FLATED) @requires_bz2() class Bzip2TestsWithSourceFile(AbstractTestsWithSourceFile, unittest.TestCase): compression = zipfile.ZIP_BZIP2 @requires_lzma() class LzmaTestsWithSourceFile(AbstractTestsWithSourceFile, unittest.TestCase):
64
64
36
25
38
oleksandr-pavlyk/cpython
Lib/test/test_zipfile.py
Python
LzmaTestsWithSourceFile
LzmaTestsWithSourceFile
668
671
668
670
6b68736494ed473ef90ca5e0e27a11d564696087
bigcode/the-stack
train
e4faf4e7d22c3dfef884f0fe
train
class
class ExtractTests(unittest.TestCase): def make_test_file(self): with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp: for fpath, fdata in SMALL_TEST_DATA: zipfp.writestr(fpath, fdata) def test_extract(self): with temp_cwd(): self.make_test_fi...
class ExtractTests(unittest.TestCase):
def make_test_file(self): with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp: for fpath, fdata in SMALL_TEST_DATA: zipfp.writestr(fpath, fdata) def test_extract(self): with temp_cwd(): self.make_test_file() with zipfile.ZipFile(TE...
w") as zipfp: # syntax errors are printed to stdout with captured_stdout() as s: zipfp.writepy(os.path.join(TESTFN2, "mod1.py")) self.assertIn("SyntaxError", s.getvalue()) # as it will not have compiled the python file, it will ...
256
256
1,876
7
249
oleksandr-pavlyk/cpython
Lib/test/test_zipfile.py
Python
ExtractTests
ExtractTests
1,333
1,522
1,333
1,334
931c65b86b33297add78e7b7759176f12a33256f
bigcode/the-stack
train
72bafb391a832a97df15f364
train
class
class AbstractWriterTests: def tearDown(self): unlink(TESTFN2) def test_close_after_close(self): data = b'content' with zipfile.ZipFile(TESTFN2, "w", self.compression) as zipf: w = zipf.open('test', 'w') w.write(data) w.close() self.asser...
class AbstractWriterTests:
def tearDown(self): unlink(TESTFN2) def test_close_after_close(self): data = b'content' with zipfile.ZipFile(TESTFN2, "w", self.compression) as zipf: w = zipf.open('test', 'w') w.write(data) w.close() self.assertTrue(w.closed) ...
SmallFiles, unittest.TestCase): compression = zipfile.ZIP_BZIP2 @requires_lzma() class LzmaTestZip64InSmallFiles(AbstractTestZip64InSmallFiles, unittest.TestCase): compression = zipfile.ZIP_LZMA class AbstractWriterTests:
64
64
193
5
58
oleksandr-pavlyk/cpython
Lib/test/test_zipfile.py
Python
AbstractWriterTests
AbstractWriterTests
1,098
1,122
1,098
1,099
45ace494bf98052e4533e0c291fe545b271f6df8
bigcode/the-stack
train
8834bf4dcdb4f09e50df99bb
train
class
class TestPath(unittest.TestCase): def setUp(self): self.fixtures = contextlib.ExitStack() self.addCleanup(self.fixtures.close) def zipfile_alpharep(self): with self.subTest(): yield build_alpharep_fixture() with self.subTest(): yield add_dirs(build_alpha...
class TestPath(unittest.TestCase):
def setUp(self): self.fixtures = contextlib.ExitStack() self.addCleanup(self.fixtures.close) def zipfile_alpharep(self): with self.subTest(): yield build_alpharep_fixture() with self.subTest(): yield add_dirs(build_alpharep_fixture()) def zipfile_ond...
levels deep (b/d/e) - multiple files in a directory (b/c, b/f) - a directory containing only a directory (g/h) "alpha" because it uses alphabet "rep" because it's a representative example """ data = io.BytesIO() zf = zipfile.ZipFile(data, "w") zf.writestr("a.txt", b"content of a") ...
256
256
2,749
7
248
oleksandr-pavlyk/cpython
Lib/test/test_zipfile.py
Python
TestPath
TestPath
2,871
3,201
2,871
2,871
e7f7b341a80059bac90099d022c3688122247c43
bigcode/the-stack
train
7e3f9b7a9102f9016a0965df
train
class
class CommandLineTest(unittest.TestCase): def zipfilecmd(self, *args, **kwargs): rc, out, err = script_helper.assert_python_ok('-m', 'zipfile', *args, **kwargs) return out.replace(os.linesep.encode(), b'\n') def zipfilecmd_failure(self, *ar...
class CommandLineTest(unittest.TestCase):
def zipfilecmd(self, *args, **kwargs): rc, out, err = script_helper.assert_python_ok('-m', 'zipfile', *args, **kwargs) return out.replace(os.linesep.encode(), b'\n') def zipfilecmd_failure(self, *args): return script_helper.assert_py...
_file_bytes(self): zi = zipfile.ZipInfo.from_file(os.fsencode(__file__), 'test') self.assertEqual(posixpath.basename(zi.filename), 'test') self.assertFalse(zi.is_dir()) self.assertEqual(zi.file_size, os.path.getsize(__file__)) def test_from_file_fileno(self): with open(__fil...
235
235
785
8
227
oleksandr-pavlyk/cpython
Lib/test/test_zipfile.py
Python
CommandLineTest
CommandLineTest
2,670
2,747
2,670
2,671
c4f864097bc947e3434a52521250d2130f166d37
bigcode/the-stack
train
6852bb23e26e98312034a31f
train
function
def add_dirs(zf): """ Given a writable zip file zf, inject directory entries for any directories implied by the presence of children. """ for name in zipfile.CompleteDirs._implied_dirs(zf.namelist()): zf.writestr(name, b"") return zf
def add_dirs(zf):
""" Given a writable zip file zf, inject directory entries for any directories implied by the presence of children. """ for name in zipfile.CompleteDirs._implied_dirs(zf.namelist()): zf.writestr(name, b"") return zf
self, i): self.count = 0 self._orig_iter = iter(i) def __iter__(self): return self def __next__(self): result = next(self._orig_iter) self.count += 1 return result def add_dirs(zf):
64
64
69
6
57
oleksandr-pavlyk/cpython
Lib/test/test_zipfile.py
Python
add_dirs
add_dirs
2,811
2,818
2,811
2,811
02f30da78ace32ca2dae14ee8fab51ad0df56795
bigcode/the-stack
train
c1a15e6795c6043e4f2d59a5
train
class
class OtherTests(unittest.TestCase): def test_open_via_zip_info(self): # Create the ZIP archive with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp: zipfp.writestr("name", "foo") with self.assertWarns(UserWarning): zipfp.writestr("name", "bar") ...
class OtherTests(unittest.TestCase):
def test_open_via_zip_info(self): # Create the ZIP archive with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp: zipfp.writestr("name", "foo") with self.assertWarns(UserWarning): zipfp.writestr("name", "bar") self.assertEqual(zipfp.namel...
2, 'r') as zipfp: writtenfile = zipfp.extract(arcname, targetpath) self.assertEqual(writtenfile, correctfile, msg='extract %r: %r != %r' % (arcname, writtenfile, correctfile)) self.check_file(correctfile, conte...
256
256
6,213
7
249
oleksandr-pavlyk/cpython
Lib/test/test_zipfile.py
Python
OtherTests
OtherTests
1,525
2,045
1,525
1,525
ae8fcca9a1c58f8522479d7cc741b4de81ffa8f4
bigcode/the-stack
train
023c8aed90a87001061f1bd8
train
function
def pass_alpharep(meth): """ Given a method, wrap it in a for loop that invokes method with each subtest. """ @functools.wraps(meth) def wrapper(self): for alpharep in self.zipfile_alpharep(): meth(self, alpharep=alpharep) return wrapper
def pass_alpharep(meth):
""" Given a method, wrap it in a for loop that invokes method with each subtest. """ @functools.wraps(meth) def wrapper(self): for alpharep in self.zipfile_alpharep(): meth(self, alpharep=alpharep) return wrapper
b"content of e") zf.writestr("b/f.txt", b"content of f") zf.writestr("g/h/i.txt", b"content of i") zf.filename = "alpharep.zip" return zf def pass_alpharep(meth):
64
64
74
8
55
oleksandr-pavlyk/cpython
Lib/test/test_zipfile.py
Python
pass_alpharep
pass_alpharep
2,857
2,868
2,857
2,857
a05ea5aaaf4964946a307e6412522b99590c4e73
bigcode/the-stack
train
84563a92ba7821499bde5203
train
class
@requires_zlib() class DeflateTestZip64InSmallFiles(AbstractTestZip64InSmallFiles, unittest.TestCase): compression = zipfile.ZIP_DEFLATED
@requires_zlib() class DeflateTestZip64InSmallFiles(AbstractTestZip64InSmallFiles, unittest.TestCase):
compression = zipfile.ZIP_DEFLATED
Equal(zinfo.compress_size, expected_compress_size) self.assertEqual(zinfo.header_offset, expected_header_offset) self.assertEqual(zf.read(zinfo), expected_content) @requires_zlib() class DeflateTestZip64InSmallFiles(AbstractTestZip64InSmallFiles, ...
64
64
38
27
37
oleksandr-pavlyk/cpython
Lib/test/test_zipfile.py
Python
DeflateTestZip64InSmallFiles
DeflateTestZip64InSmallFiles
1,082
1,085
1,082
1,084
66ce5e26ee80b8b1782c1fa0952964671987e200
bigcode/the-stack
train
dfb99900cb7970f82cceda9f
train
class
@requires_bz2() class Bzip2TestZip64InSmallFiles(AbstractTestZip64InSmallFiles, unittest.TestCase): compression = zipfile.ZIP_BZIP2
@requires_bz2() class Bzip2TestZip64InSmallFiles(AbstractTestZip64InSmallFiles, unittest.TestCase):
compression = zipfile.ZIP_BZIP2
lib() class DeflateTestZip64InSmallFiles(AbstractTestZip64InSmallFiles, unittest.TestCase): compression = zipfile.ZIP_DEFLATED @requires_bz2() class Bzip2TestZip64InSmallFiles(AbstractTestZip64InSmallFiles, unittest.TestCase):
64
64
40
29
34
oleksandr-pavlyk/cpython
Lib/test/test_zipfile.py
Python
Bzip2TestZip64InSmallFiles
Bzip2TestZip64InSmallFiles
1,087
1,090
1,087
1,089
267338c111078df3036076b904bf10843642f2f5
bigcode/the-stack
train
b5f43d73786aa4c4952ad52f
train
class
class StoredWriterTests(AbstractWriterTests, unittest.TestCase): compression = zipfile.ZIP_STORED
class StoredWriterTests(AbstractWriterTests, unittest.TestCase):
compression = zipfile.ZIP_STORED
w = zipf.open('test', 'w') w.write(data) w.close() self.assertTrue(w.closed) self.assertRaises(ValueError, w.write, b'') self.assertEqual(zipf.read('test'), data) class StoredWriterTests(AbstractWriterTests, unittest.TestCase):
64
64
23
12
52
oleksandr-pavlyk/cpython
Lib/test/test_zipfile.py
Python
StoredWriterTests
StoredWriterTests
1,124
1,125
1,124
1,124
ca7cba6573ffefed987822eb5f29d8af0bd392f9
bigcode/the-stack
train
e1af2eca36f17f3525f50dfa
train
class
class StoredTestsWithRandomBinaryFiles(AbstractTestsWithRandomBinaryFiles, unittest.TestCase): compression = zipfile.ZIP_STORED
class StoredTestsWithRandomBinaryFiles(AbstractTestsWithRandomBinaryFiles, unittest.TestCase):
compression = zipfile.ZIP_STORED
(len(testdata), len(self.data)) self.assertEqual(testdata, self.data) def test_random_open(self): for f in get_files(self): self.zip_random_open_test(f, self.compression) class StoredTestsWithRandomBinaryFiles(AbstractTestsWithRandomBinaryFiles, ...
64
64
30
19
45
oleksandr-pavlyk/cpython
Lib/test/test_zipfile.py
Python
StoredTestsWithRandomBinaryFiles
StoredTestsWithRandomBinaryFiles
2,342
2,344
2,342
2,343
729fa23610da02bfd26b6e61d23ae0449f2fd7f0
bigcode/the-stack
train
b40c9d613222e99e4451f5bb
train
class
class AbstractTestsWithRandomBinaryFiles: @classmethod def setUpClass(cls): datacount = randint(16, 64)*1024 + randint(1, 1024) cls.data = b''.join(struct.pack('<f', random()*randint(-1000, 1000)) for i in range(datacount)) def setUp(self): # Make a sourc...
class AbstractTestsWithRandomBinaryFiles: @classmethod
def setUpClass(cls): datacount = randint(16, 64)*1024 + randint(1, 1024) cls.data = b''.join(struct.pack('<f', random()*randint(-1000, 1000)) for i in range(datacount)) def setUp(self): # Make a source file with some lines with open(TESTFN, "wb") as f...
# _readbuffer returns the same content (ie. rewind to the start of # the file to read forward to the required position). old_read_size = fp.MIN_READ_SIZE fp.MIN_READ_SIZE = 1 fp._readbuffer = b'' fp._offset = 0 fp.seek(0, os.SEEK_SET) ...
210
210
701
12
198
oleksandr-pavlyk/cpython
Lib/test/test_zipfile.py
Python
AbstractTestsWithRandomBinaryFiles
AbstractTestsWithRandomBinaryFiles
2,251
2,339
2,251
2,252
28d0dbc17557035e6d6589cf40cfd773674d55c6
bigcode/the-stack
train
b341a175ce17a65e981db5b3
train
class
class jaraco: class itertools: class Counter: def __init__(self, i): self.count = 0 self._orig_iter = iter(i) def __iter__(self): return self def __next__(self): result = next(self._orig_iter) ...
class jaraco:
class itertools: class Counter: def __init__(self, i): self.count = 0 self._orig_iter = iter(i) def __iter__(self): return self def __next__(self): result = next(self._orig_iter) self.count ...
): output = subprocess.check_output([self.exe_zip64, sys.executable]) self.assertIn(b'number in executable: 5', output) # Poor man's technique to consume a (smallish) iterable. consume = tuple # from jaraco.itertools 5.0 class jaraco:
64
64
75
4
59
oleksandr-pavlyk/cpython
Lib/test/test_zipfile.py
Python
jaraco
jaraco
2,795
2,808
2,795
2,795
14f3c6d1804abe13969bc5e911e838a0535279f8
bigcode/the-stack
train
55041eaaea23d798a3e30dda
train
class
class StoredBadCrcTests(AbstractBadCrcTests, unittest.TestCase): compression = zipfile.ZIP_STORED zip_with_bad_crc = ( b'PK\003\004\024\0\0\0\0\0 \213\212;:r' b'\253\377\f\0\0\0\f\0\0\0\005\0\0\000af' b'ilehello,AworldP' b'K\001\002\024\003\024\0\0\0\0\0 \213\212;:' b'r\2...
class StoredBadCrcTests(AbstractBadCrcTests, unittest.TestCase):
compression = zipfile.ZIP_STORED zip_with_bad_crc = ( b'PK\003\004\024\0\0\0\0\0 \213\212;:r' b'\253\377\f\0\0\0\f\0\0\0\005\0\0\000af' b'ilehello,AworldP' b'K\001\002\024\003\024\0\0\0\0\0 \213\212;:' b'r\253\377\f\0\0\0\f\0\0\0\005\0\0\0\0' b'\0\0\0\0\0\0\0\200\...
), mode="r") as zipf: with zipf.open('afile', 'r') as corrupt_file: corrupt_file.MIN_READ_SIZE = 2 with self.assertRaises(zipfile.BadZipFile): while corrupt_file.read(2): pass class StoredBadCrcTests(AbstractBadCrcTests, unittest.Te...
72
72
241
16
55
oleksandr-pavlyk/cpython
Lib/test/test_zipfile.py
Python
StoredBadCrcTests
StoredBadCrcTests
2,079
2,089
2,079
2,079
7ad800431118288e11ea3c7ee703fd687464fa5d
bigcode/the-stack
train
21cad0528653d37ac7aa4a32
train
class
@requires_zlib() class DeflateBadCrcTests(AbstractBadCrcTests, unittest.TestCase): compression = zipfile.ZIP_DEFLATED zip_with_bad_crc = ( b'PK\x03\x04\x14\x00\x00\x00\x08\x00n}\x0c=FA' b'KE\x10\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00af' b'ile\xcbH\xcd\xc9\xc9W(\xcf/\xcaI\xc9\xa0' ...
@requires_zlib() class DeflateBadCrcTests(AbstractBadCrcTests, unittest.TestCase):
compression = zipfile.ZIP_DEFLATED zip_with_bad_crc = ( b'PK\x03\x04\x14\x00\x00\x00\x08\x00n}\x0c=FA' b'KE\x10\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00af' b'ile\xcbH\xcd\xc9\xc9W(\xcf/\xcaI\xc9\xa0' b'=\x13\x00PK\x01\x02\x14\x03\x14\x00\x00\x00\x08\x00n' b'}\x0c=FAKE\x10...
001\0\0\0\000afi' b'lePK\005\006\0\0\0\0\001\0\001\0003\000' b'\0\0/\0\0\0\0\0') @requires_zlib() class DeflateBadCrcTests(AbstractBadCrcTests, unittest.TestCase):
79
79
264
22
57
oleksandr-pavlyk/cpython
Lib/test/test_zipfile.py
Python
DeflateBadCrcTests
DeflateBadCrcTests
2,091
2,102
2,091
2,092
1e938cbd42b52b63c2cad3fc1411870c2b101dfa
bigcode/the-stack
train
046a5adad2184f6a6c149a6e
train
class
class DecryptionTests(unittest.TestCase): """Check that ZIP decryption works. Since the library does not support encryption at the moment, we use a pre-generated encrypted ZIP file.""" data = ( b'PK\x03\x04\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00\x1a\x00' b'\x00\x00\x08\x00\x...
class DecryptionTests(unittest.TestCase):
"""Check that ZIP decryption works. Since the library does not support encryption at the moment, we use a pre-generated encrypted ZIP file.""" data = ( b'PK\x03\x04\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00\x1a\x00' b'\x00\x00\x08\x00\x00\x00test.txt\xfa\x10\xa0gly|\xfa-\xc5\xc...
= ( b'PK\x03\x04\x14\x03\x00\x00\x0e\x00nu\x0c=FA' b'KE\x1b\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00af' b'ile\t\x04\x05\x00]\x00\x00\x00\x04\x004\x19I' b'\xee\x8d\xe9\x17\x89:3`\tq!.8\x00PK' b'\x01\x02\x14\x03\x14\x03\x00\x00\x0e\x00nu\x0c=FA' b'KE\x1b\x00\x00\x00n\x00\x...
256
256
1,426
8
248
oleksandr-pavlyk/cpython
Lib/test/test_zipfile.py
Python
DecryptionTests
DecryptionTests
2,135
2,248
2,135
2,135
58a3d95f6937107615a7a6134fd3c2f6012c894c
bigcode/the-stack
train
52b7df386f45a5eec6cc64ff
train
class
class Tellable: def __init__(self, fp): self.fp = fp self.offset = 0 def write(self, data): n = self.fp.write(data) self.offset += n return n def tell(self): return self.offset def flush(self): self.fp.flush()
class Tellable:
def __init__(self, fp): self.fp = fp self.offset = 0 def write(self, data): n = self.fp.write(data) self.offset += n return n def tell(self): return self.offset def flush(self): self.fp.flush()
): compression = zipfile.ZIP_BZIP2 @requires_lzma() class LzmaTestsWithRandomBinaryFiles(AbstractTestsWithRandomBinaryFiles, unittest.TestCase): compression = zipfile.ZIP_LZMA # Provide the tell() method but not seek() class Tellable:
64
64
71
4
60
oleksandr-pavlyk/cpython
Lib/test/test_zipfile.py
Python
Tellable
Tellable
2,363
2,377
2,363
2,363
e59924c5c79fa588c2eb7423eb4fa6bb6ce00190
bigcode/the-stack
train