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
3113546ba94301f7b95dea9d
train
function
@app.route('/add', methods=['GET', 'POST']) def add(): if request.method == 'GET': # View return render_template('add.html') else: # request.method = POST # add pad to settings name = request.form.getlist('name')[0] keys = request.form.getlist('keys')[0].split() ...
@app.route('/add', methods=['GET', 'POST']) def add():
if request.method == 'GET': # View return render_template('add.html') else: # request.method = POST # add pad to settings name = request.form.getlist('name')[0] keys = request.form.getlist('keys')[0].split() KEY.add_pad(name, *keys) return redirec...
=KEY.pads, pad_count=pad_count) @app.route('/tap', methods=['POST']) def tap(): pad_id = request.form.getlist('pad_id')[0] KEY.tap(pad_id) return redirect('/') @app.route('/add', methods=['GET', 'POST']) def add():
63
64
91
15
48
kekeho/ctrlpad
ctrlpad.py
Python
add
add
21
33
21
22
33c81b250109ab30dd138733cacd85e4ef87dc20
bigcode/the-stack
train
09b618f422eb267ff9fc3f5b
train
function
@app.route('/tap', methods=['POST']) def tap(): pad_id = request.form.getlist('pad_id')[0] KEY.tap(pad_id) return redirect('/')
@app.route('/tap', methods=['POST']) def tap():
pad_id = request.form.getlist('pad_id')[0] KEY.tap(pad_id) return redirect('/')
/') KEY = libctrlpad.Key('pads.json') @app.route('/', methods=['GET']) def index(): pad_count = list(range(len(KEY.pads))) return render_template('index.html', pads=KEY.pads, pad_count=pad_count) @app.route('/tap', methods=['POST']) def tap():
64
64
37
12
52
kekeho/ctrlpad
ctrlpad.py
Python
tap
tap
14
18
14
15
4a94ee6afb329bd233e55f74ba4694714baf342a
bigcode/the-stack
train
c582de680e28a9b807fb905b
train
function
@app.route('/', methods=['GET']) def index(): pad_count = list(range(len(KEY.pads))) return render_template('index.html', pads=KEY.pads, pad_count=pad_count)
@app.route('/', methods=['GET']) def index():
pad_count = list(range(len(KEY.pads))) return render_template('index.html', pads=KEY.pads, pad_count=pad_count)
from flask import Flask, render_template, request, redirect import libctrlpad app = Flask(__name__, static_folder='./templates/assets', template_folder='./templates/') KEY = libctrlpad.Key('pads.json') @app.route('/', methods=['GET']) def index():
55
64
41
10
45
kekeho/ctrlpad
ctrlpad.py
Python
index
index
8
11
8
9
7e2e4cc76ad739638e243cb7618aab6a3c0660b9
bigcode/the-stack
train
69fd61c387359c1691a83186
train
class
class TestAsyncIOCursor(AsyncIOMockServerTestCase): def test_cursor(self): cursor = self.collection.find() self.assertTrue(isinstance(cursor, motor_asyncio.AsyncIOMotorCursor)) self.assertFalse(cursor.started, "Cursor shouldn't start immediately") @asyncio_test def test_count(self):...
class TestAsyncIOCursor(AsyncIOMockServerTestCase):
def test_cursor(self): cursor = self.collection.find() self.assertTrue(isinstance(cursor, motor_asyncio.AsyncIOMotorCursor)) self.assertFalse(cursor.started, "Cursor shouldn't start immediately") @asyncio_test def test_count(self): yield from self.make_test_data() co...
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the Li...
256
256
3,588
14
242
onovy/motor
test/asyncio_tests/test_asyncio_cursor.py
Python
TestAsyncIOCursor
TestAsyncIOCursor
39
492
39
39
0df78383a208541b550fb80184d9836d380531c6
bigcode/the-stack
train
13c7350e4644b142a91a8a98
train
class
class TestAsyncIOCursorMaxTimeMS(AsyncIOTestCase): def setUp(self): super(TestAsyncIOCursorMaxTimeMS, self).setUp() self.loop.run_until_complete(self.maybe_skip()) def tearDown(self): self.loop.run_until_complete(self.disable_timeout()) super(TestAsyncIOCursorMaxTimeMS, self).te...
class TestAsyncIOCursorMaxTimeMS(AsyncIOTestCase):
def setUp(self): super(TestAsyncIOCursorMaxTimeMS, self).setUp() self.loop.run_until_complete(self.maybe_skip()) def tearDown(self): self.loop.run_until_complete(self.disable_timeout()) super(TestAsyncIOCursorMaxTimeMS, self).tearDown() @asyncio.coroutine def maybe_skip...
id': 1}, {'_id': 2}]) aggregate = listener.first_command_started('aggregate') self.assertEqual(aggregate.command['cursor']['batchSize'], 2) getMore = listener.first_command_started('getMore') self.assertEqual(getMore.command['batchSize'], 2) @asyncio_test def tes...
255
256
936
14
241
onovy/motor
test/asyncio_tests/test_asyncio_cursor.py
Python
TestAsyncIOCursorMaxTimeMS
TestAsyncIOCursorMaxTimeMS
495
629
495
495
d071f10de04b2845435cd0fcad0886f0a77b9ed5
bigcode/the-stack
train
851fa666118061b6b78920f3
train
class
class Formatodenominaciones(Document): pass
class Formatodenominaciones(Document):
pass
# -*- coding: utf-8 -*- # Copyright (c) 2017, Pedro Antonio Fernández Gómez and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe.model.document import Document class Formatodenominaciones(Document):
59
64
9
7
51
Nirchains/metal
metalgrafica/metalgrafica/doctype/formato_denominaciones/formato_denominaciones.py
Python
Formatodenominaciones
Formatodenominaciones
9
10
9
9
f4a426390c4c89a564dce8b54f603ac59ba3b030
bigcode/the-stack
train
708b4be66f12b0952bc3da33
train
class
class ContactCardForm(forms.ModelForm): class Meta: model = Contact exclude = ['user']
class ContactCardForm(forms.ModelForm):
class Meta: model = Contact exclude = ['user']
from django import forms from contacts.models import Contact class ContactCardForm(forms.ModelForm):
19
64
23
8
10
arbaishev/phonebook
contacts/forms.py
Python
ContactCardForm
ContactCardForm
5
8
5
5
ee45319344be97f71086351767e8b323a5b3526b
bigcode/the-stack
train
aab1021cb675e0fd76de8121
train
function
def script_path(filename): """ A convenience function to get the absolute path to a file in this tutorial's directory. This allows the tutorial to be launched from any directory. """ import os filepath = os.path.join(os.path.dirname(__file__)) return os.path.join(filepath, filename)
def script_path(filename):
""" A convenience function to get the absolute path to a file in this tutorial's directory. This allows the tutorial to be launched from any directory. """ import os filepath = os.path.join(os.path.dirname(__file__)) return os.path.join(filepath, filename)
from metaflow import FlowSpec, IncludeFile, step def script_path(filename):
17
64
67
5
11
mblackgeo/metaflow-sandbox
tutorials/02-statistics/stats.py
Python
script_path
script_path
4
14
4
4
cfacaf971fdad43b66c0b5a0285604c660add1a7
bigcode/the-stack
train
32d535839bed355d6c290925
train
class
class MovieStatsFlow(FlowSpec): """ A flow to generate some statistics about the movie genres. The flow performs the following steps: 1) Ingests a CSV into a Pandas Dataframe. 2) Fan-out over genre using Metaflow foreach. 3) Compute quartiles for each genre. 4) Save a dictionary of genre sp...
class MovieStatsFlow(FlowSpec):
""" A flow to generate some statistics about the movie genres. The flow performs the following steps: 1) Ingests a CSV into a Pandas Dataframe. 2) Fan-out over genre using Metaflow foreach. 3) Compute quartiles for each genre. 4) Save a dictionary of genre specific statistics. """ ...
from metaflow import FlowSpec, IncludeFile, step def script_path(filename): """ A convenience function to get the absolute path to a file in this tutorial's directory. This allows the tutorial to be launched from any directory. """ import os filepath = os.path.join(os.path.dirname(__file...
87
186
622
8
79
mblackgeo/metaflow-sandbox
tutorials/02-statistics/stats.py
Python
MovieStatsFlow
MovieStatsFlow
17
104
17
17
c60d4b97e44b76fa7e3db0992a800e57a10e1dc4
bigcode/the-stack
train
a42a3231c82cebcf8f5383ba
train
class
class PocketToKindleStack(core.Stack): def __init__(self, scope: core.Construct, id: str, # pylint: disable=redefined-builtin lambda_notifications: aws_lambda.IFunction, **kwargs) -> None: super().__init__(scope, id, **kwargs) # CloudWatch LogGroup and Stream to store 'since' ti...
class PocketToKindleStack(core.Stack):
def __init__(self, scope: core.Construct, id: str, # pylint: disable=redefined-builtin lambda_notifications: aws_lambda.IFunction, **kwargs) -> None: super().__init__(scope, id, **kwargs) # CloudWatch LogGroup and Stream to store 'since' timestamp value since_log_group = ...
from os import environ as env from aws_cdk import ( aws_events, aws_events_targets, aws_iam, aws_lambda, aws_logs, aws_s3, aws_s3_notifications, aws_sns, aws_sns_subscriptions, core, ) from utils.cdk import ( DEFAULT_LOG_RETENTION, code_from_path, get_bucket, ge...
122
243
810
9
113
shaftoe/api-l3x-in
lib/stacks/pocket_to_kindle/__init__.py
Python
PocketToKindleStack
PocketToKindleStack
28
127
28
29
d6e8c02539ad7cdb2267b3743d2c3538325058a3
bigcode/the-stack
train
e4198e04a590eb39096ec4e4
train
class
@enum.unique class DatabaseSessionAction(enum.Enum): """ Enum representing the database session transaction action selected for a command decorated by :py:func:`.with_database_session`. You will not need to use this class unless you provide ``pass_action = True`` to :py:func:`.with_database_session...
@enum.unique class DatabaseSessionAction(enum.Enum):
""" Enum representing the database session transaction action selected for a command decorated by :py:func:`.with_database_session`. You will not need to use this class unless you provide ``pass_action = True`` to :py:func:`.with_database_session`. """ DRY_RUN = "rollback" PROMPT = "pr...
"geocode", "de_identify", "refresh_materialized_view", ] LOG = logging.getLogger(__name__) CACHE_TTL = 60 * 60 * 24 * 365 # 1 year CACHE_SIZE = maxsize @enum.unique class DatabaseSessionAction(enum.Enum):
64
64
95
11
52
UWIT-IAM/uw-redcap-client
lib/id3c/cli/command/__init__.py
Python
DatabaseSessionAction
DatabaseSessionAction
38
49
38
39
aabef070fee1b5dff5a3c0ce5995d5d38e66b7b8
bigcode/the-stack
train
3bdf1790c5f81c42ffad696c
train
function
def with_database_session(command = None, *, pass_action: bool = False): """ Decorator to provide database session and error handling for a *command*. The *command* callable must be a :py:class:`click.Command` instance. The decorated *command* is called with a ``db`` keyword argument to provide a ...
def with_database_session(command = None, *, pass_action: bool = False):
""" Decorator to provide database session and error handling for a *command*. The *command* callable must be a :py:class:`click.Command` instance. The decorated *command* is called with a ``db`` keyword argument to provide a :class:`~id3c.db.session.DatabaseSession` object. The call happens w...
location", "manifest", "user", "sequence_read_set", "consensus_genome", "redcap_det", "receiving", "geocode", "de_identify", "refresh_materialized_view", ] LOG = logging.getLogger(__name__) CACHE_TTL = 60 * 60 * 24 * 365 # 1 year CACHE_SIZE = maxsize @enum.unique class Database...
199
199
666
16
183
UWIT-IAM/uw-redcap-client
lib/id3c/cli/command/__init__.py
Python
with_database_session
with_database_session
52
141
52
52
d592ebae5cb235a18cc61536a8405232b38e9e60
bigcode/the-stack
train
a44c95118e69ebdaf6f04137
train
function
@contextmanager def pickled_cache(filename: str = None) -> Iterator[TTLCache]: """ Context manager for reading/writing a :class:`TTLCache` from/to the given *filename*. If *filename* exists, it is unpickled and the :class:`TTLCache` object is returned. If *filename* does not exist, an empty cache ...
@contextmanager def pickled_cache(filename: str = None) -> Iterator[TTLCache]:
""" Context manager for reading/writing a :class:`TTLCache` from/to the given *filename*. If *filename* exists, it is unpickled and the :class:`TTLCache` object is returned. If *filename* does not exist, an empty cache will be returned. In either case, the cache object will be written back to ...
.confirm(ask_to_commit) else: commit = action is DatabaseSessionAction.COMMIT if commit: LOG.info( "Committing all changes" if processed_without_error else \ "Committing successfully processed record...
114
114
383
20
93
UWIT-IAM/uw-redcap-client
lib/id3c/cli/command/__init__.py
Python
pickled_cache
pickled_cache
144
187
144
145
863275f50e5ca88f31a698757c412543b2544e6c
bigcode/the-stack
train
41f9ededb35cd7942a4b8cd9
train
class
class DEPSFileTest(cros_test_lib.MoxTempDirTestCase): def setUp(self): testdata = os.path.dirname(os.path.abspath(__file__)) self.test_base = os.path.join(testdata, 'testdata/chrome_set_ver_unittest') self.repo_root = os.path.join(self.tempdir, 'repo_root') self.repo...
class DEPSFileTest(cros_test_lib.MoxTempDirTestCase):
def setUp(self): testdata = os.path.dirname(os.path.abspath(__file__)) self.test_base = os.path.join(testdata, 'testdata/chrome_set_ver_unittest') self.repo_root = os.path.join(self.tempdir, 'repo_root') self.repo_root_zip = os.path.join(self.test_base, ...
#!/usr/bin/python2 # Copyright (c) 2012 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Unittests for chrome_set_ver.""" import mox import os import shutil import sys sys.path.insert(0, os.path.join(os.path.dirnam...
177
256
1,606
16
160
flatcar-linux/chromite
scripts/chrome_set_ver_unittest.py
Python
DEPSFileTest
DEPSFileTest
28
165
28
29
2b315ae3791c915e7bdcc06d7937142af1688355
bigcode/the-stack
train
e1e150506b9adc751cdfa09e
train
class
class TestEndedException(Exception): """Exception thrown by test to mark completion.""" pass
class TestEndedException(Exception):
"""Exception thrown by test to mark completion.""" pass
path(__file__)), '..', '..')) from chromite.lib import cros_build_lib from chromite.lib import cros_test_lib from chromite.lib import git from chromite.scripts import chrome_set_ver # pylint: disable=W0212,R0904 class TestEndedException(Exception):
64
64
19
6
57
flatcar-linux/chromite
scripts/chrome_set_ver_unittest.py
Python
TestEndedException
TestEndedException
23
25
23
23
de379de09a20a8c32c74ca188491eb0714813760
bigcode/the-stack
train
37830a45cfdcea8787c75187
train
function
@router.put("/{plan_id}") def update_meal_plan( plan_id: str, meal_plan: MealPlanIn, session: Session = Depends(generate_session), current_user=Depends(get_current_user), ): """ Updates a meal plan based off ID """ processed_plan = process_meals(session, meal_plan) processed_plan = MealPlanI...
@router.put("/{plan_id}") def update_meal_plan( plan_id: str, meal_plan: MealPlanIn, session: Session = Depends(generate_session), current_user=Depends(get_current_user), ):
""" Updates a meal plan based off ID """ processed_plan = process_meals(session, meal_plan) processed_plan = MealPlanInDB(uid=plan_id, **processed_plan.dict()) db.meals.update(session, plan_id, processed_plan.dict()) return SnackResponse.info("Mealplan Updated")
als.create(session, processed_plan.dict()) return SnackResponse.success("Mealplan Created") @router.put("/{plan_id}") def update_meal_plan( plan_id: str, meal_plan: MealPlanIn, session: Session = Depends(generate_session), current_user=Depends(get_current_user), ):
64
64
110
46
18
sephrat/mealie
mealie/routes/mealplans/crud.py
Python
update_meal_plan
update_meal_plan
37
49
37
43
1022a7bdf2f3ff85d31b194c0ad344e72e8cb182
bigcode/the-stack
train
b9e5dc3f85d98b342067cd64
train
function
@router.get("/today/image", tags=["Meal Plan"]) def get_todays_image(session: Session = Depends(generate_session), group_name: str = "Home"): """ Returns the image for todays meal-plan. """ group_in_db: GroupInDB = db.groups.get(session, group_name, "name") recipe = get_todays_meal(session, group_i...
@router.get("/today/image", tags=["Meal Plan"]) def get_todays_image(session: Session = Depends(generate_session), group_name: str = "Home"):
""" Returns the image for todays meal-plan. """ group_in_db: GroupInDB = db.groups.get(session, group_name, "name") recipe = get_todays_meal(session, group_in_db) if recipe: recipe_image = image.read_image(recipe.slug, image_type=image.IMG_OPTIONS.ORIGINAL_IMAGE) else: rais...
.get(session, current_user.group, "name") recipe = get_todays_meal(session, group_in_db) return recipe.slug @router.get("/today/image", tags=["Meal Plan"]) def get_todays_image(session: Session = Depends(generate_session), group_name: str = "Home"):
64
64
149
34
29
sephrat/mealie
mealie/routes/mealplans/crud.py
Python
get_todays_image
get_todays_image
81
97
81
82
305b7e177da04fdc8e0c7a950394afa9059a90f4
bigcode/the-stack
train
85eb1db1f2b6cbaa3cfb784d
train
function
@router.get("/this-week", response_model=MealPlanInDB) def get_this_week(session: Session = Depends(generate_session), current_user: UserInDB = Depends(get_current_user)): """ Returns the meal plan data for this week """ return db.groups.get_meals(session, current_user.group)[0]
@router.get("/this-week", response_model=MealPlanInDB) def get_this_week(session: Session = Depends(generate_session), current_user: UserInDB = Depends(get_current_user)):
""" Returns the meal plan data for this week """ return db.groups.get_meals(session, current_user.group)[0]
plan from the database """ db.meals.delete(session, plan_id) return SnackResponse.error("Mealplan Deleted") @router.get("/this-week", response_model=MealPlanInDB) def get_this_week(session: Session = Depends(generate_session), current_user: UserInDB = Depends(get_current_user)):
64
64
65
39
25
sephrat/mealie
mealie/routes/mealplans/crud.py
Python
get_this_week
get_this_week
61
65
61
62
85252204b6dbd356a74ee5a3bcc5083d6aa521ce
bigcode/the-stack
train
f909dd8e50154965dbc195fc
train
function
@router.post("/create") def create_meal_plan( data: MealPlanIn, session: Session = Depends(generate_session), current_user=Depends(get_current_user) ): """ Creates a meal plan database entry """ processed_plan = process_meals(session, data) db.meals.create(session, processed_plan.dict()) return Sna...
@router.post("/create") def create_meal_plan( data: MealPlanIn, session: Session = Depends(generate_session), current_user=Depends(get_current_user) ):
""" Creates a meal plan database entry """ processed_plan = process_meals(session, data) db.meals.create(session, processed_plan.dict()) return SnackResponse.success("Mealplan Created")
(generate_session), ): """ Returns a list of all available Meal Plan """ return db.groups.get_meals(session, current_user.group) @router.post("/create") def create_meal_plan( data: MealPlanIn, session: Session = Depends(generate_session), current_user=Depends(get_current_user) ):
64
64
77
36
28
sephrat/mealie
mealie/routes/mealplans/crud.py
Python
create_meal_plan
create_meal_plan
26
34
26
29
9565818c0bf61af3b7cde6837ff82370d5fe9b67
bigcode/the-stack
train
e11d9bf94ee9362778eb40e2
train
function
@router.delete("/{plan_id}") def delete_meal_plan(plan_id, session: Session = Depends(generate_session), current_user=Depends(get_current_user)): """ Removes a meal plan from the database """ db.meals.delete(session, plan_id) return SnackResponse.error("Mealplan Deleted")
@router.delete("/{plan_id}") def delete_meal_plan(plan_id, session: Session = Depends(generate_session), current_user=Depends(get_current_user)):
""" Removes a meal plan from the database """ db.meals.delete(session, plan_id) return SnackResponse.error("Mealplan Deleted")
=plan_id, **processed_plan.dict()) db.meals.update(session, plan_id, processed_plan.dict()) return SnackResponse.info("Mealplan Updated") @router.delete("/{plan_id}") def delete_meal_plan(plan_id, session: Session = Depends(generate_session), current_user=Depends(get_current_user)):
64
64
61
31
33
sephrat/mealie
mealie/routes/mealplans/crud.py
Python
delete_meal_plan
delete_meal_plan
52
58
52
53
d1fc26fcc9fbb808e4e0e8c9bd41744615cee373
bigcode/the-stack
train
aedf104faea4161203817d02
train
function
@router.get("/today", tags=["Meal Plan"]) def get_today(session: Session = Depends(generate_session), current_user: UserInDB = Depends(get_current_user)): """ Returns the recipe slug for the meal scheduled for today. If no meal is scheduled nothing is returned """ group_in_db: GroupInDB = db.groups...
@router.get("/today", tags=["Meal Plan"]) def get_today(session: Session = Depends(generate_session), current_user: UserInDB = Depends(get_current_user)):
""" Returns the recipe slug for the meal scheduled for today. If no meal is scheduled nothing is returned """ group_in_db: GroupInDB = db.groups.get(session, current_user.group, "name") recipe = get_todays_meal(session, group_in_db) return recipe.slug
(get_current_user)): """ Returns the meal plan data for this week """ return db.groups.get_meals(session, current_user.group)[0] @router.get("/today", tags=["Meal Plan"]) def get_today(session: Session = Depends(generate_session), current_user: UserInDB = Depends(get_current_user)):
64
64
101
34
30
sephrat/mealie
mealie/routes/mealplans/crud.py
Python
get_today
get_today
68
78
68
69
c0657e3295cd87b3fe2cd912ca43a2c237ac5227
bigcode/the-stack
train
8019bf21c87f333dcc188f21
train
function
@router.get("/all", response_model=list[MealPlanInDB]) def get_all_meals( current_user: UserInDB = Depends(get_current_user), session: Session = Depends(generate_session), ): """ Returns a list of all available Meal Plan """ return db.groups.get_meals(session, current_user.group)
@router.get("/all", response_model=list[MealPlanInDB]) def get_all_meals( current_user: UserInDB = Depends(get_current_user), session: Session = Depends(generate_session), ):
""" Returns a list of all available Meal Plan """ return db.groups.get_meals(session, current_user.group)
router = APIRouter(prefix="/api/meal-plans", tags=["Meal Plan"]) @router.get("/all", response_model=list[MealPlanInDB]) def get_all_meals( current_user: UserInDB = Depends(get_current_user), session: Session = Depends(generate_session), ):
63
64
68
44
19
sephrat/mealie
mealie/routes/mealplans/crud.py
Python
get_all_meals
get_all_meals
16
23
16
20
5ac89ac1a7f2936c018dd542fd343fdf2d844d61
bigcode/the-stack
train
78cfe3eb06971df34074ed42
train
function
def test_load_templates(): """Test that the templates can be loaded.""" template_keys = ["a", "b", "c"] templates = ENV.get_templates(True) for key in template_keys: assert templates[key] templates[key].render(ENV.get_configs(True))
def test_load_templates():
"""Test that the templates can be loaded.""" template_keys = ["a", "b", "c"] templates = ENV.get_templates(True) for key in template_keys: assert templates[key] templates[key].render(ENV.get_configs(True))
""" datazen - Tests for the 'templates' API. """ # internal from . import ENV def test_load_templates():
26
64
59
5
20
vkottler/datazen
tests/test_templates.py
Python
test_load_templates
test_load_templates
9
17
9
9
baeeda772676500d61518976f16d4ca74242d1a1
bigcode/the-stack
train
b18be05469fb894a354922fa
train
class
class GraphPermissionRepository(PermissionRepository): """Graph-aware storage layer for permissions.""" # Mapping from ListPermissionsSortKey to the name of an attribute on the PermissionTuple # returned by get_permissions() on the graph. SORT_FIELD = {ListPermissionsSortKey.NAME: "name", ListPermissio...
class GraphPermissionRepository(PermissionRepository):
"""Graph-aware storage layer for permissions.""" # Mapping from ListPermissionsSortKey to the name of an attribute on the PermissionTuple # returned by get_permissions() on the graph. SORT_FIELD = {ListPermissionsSortKey.NAME: "name", ListPermissionsSortKey.DATE: "created_on"} def __init__(self, g...
from typing import TYPE_CHECKING from grouper.entities.pagination import PaginatedList from grouper.entities.permission import Permission, PermissionNotFoundException from grouper.models.permission import Permission as SQLPermission from grouper.repositories.interfaces import PermissionRepository from grouper.usecases...
110
119
399
8
101
bonniech3n/merou
grouper/repositories/permission.py
Python
GraphPermissionRepository
GraphPermissionRepository
16
62
16
16
037de5b806391946c484ed6b34faabb9074ebf90
bigcode/the-stack
train
732a38e14b0321da07116677
train
class
class SQLPermissionRepository(PermissionRepository): """SQL storage layer for permissions.""" def __init__(self, session): # type: (Session) -> None self.session = session def get_permission(self, name): # type: (str) -> Optional[Permission] permission = SQLPermission.get(s...
class SQLPermissionRepository(PermissionRepository):
"""SQL storage layer for permissions.""" def __init__(self, session): # type: (Session) -> None self.session = session def get_permission(self, name): # type: (str) -> Optional[Permission] permission = SQLPermission.get(self.session, name=name) if not permission: ...
Permission(name=p.name, description=p.description, created_on=p.created_on) for p in perm_tuples ] return PaginatedList[Permission]( values=permissions, total=total, offset=pagination.offset, limit=pagination.limit ) class SQLPermissionRepository(PermissionRep...
64
64
194
8
56
bonniech3n/merou
grouper/repositories/permission.py
Python
SQLPermissionRepository
SQLPermissionRepository
65
92
65
65
c66f3ef97e0ce5f85e7d23d07f1f5361573f8133
bigcode/the-stack
train
d1c2f68989dcf683f487c5fc
train
function
@with_solutions(6000, 807320) def solve17(data): # Set and Forget tape = [int(x) for x in data.split(',')] SCAFFOLD = 35 MAPPING = {'^':'↑', 'v':'↓', '<':'←', '>':'→', '→':'R','←':'L'} inputQ, outputQ = IQueue(), IQueue() vm = IntCodeVM(tape, inputQ, outputQ) vm.start('camera') def ...
@with_solutions(6000, 807320) def solve17(data): # Set and Forget
tape = [int(x) for x in data.split(',')] SCAFFOLD = 35 MAPPING = {'^':'↑', 'v':'↓', '<':'←', '>':'→', '→':'R','←':'L'} inputQ, outputQ = IQueue(), IQueue() vm = IntCodeVM(tape, inputQ, outputQ) vm.start('camera') def move(point, dir): dx, dy = DIRECTIONS[dir][0] return (po...
# Part 1 signal = [int(c) for c in data] for phase in range(100): phase_output = [] for n in range(len(signal)): pattern = nth_pattern(n) output_digit = sum([a * b for (a,b) in zip(signal, pattern)]) phase_output.append(abs(output_digit) % 10) signal ...
256
256
869
23
233
wmdrthr/advent-of-code
2019/adventofcode.py
Python
solve17
solve17
1,156
1,271
1,156
1,160
effb9c5dc1b7e8d493ac75e3ab6ae058c9ed25f0
bigcode/the-stack
train
bb832ca1402e262435107816
train
function
@with_solutions(13547311, 236453) def solve5(data): # Sunny with a Chance of Asteroids tape = [int(x) for x in data.split(',')] outputQ = IQueue() vm = IntCodeVM(tape, IQueue([1]), outputQ).run() assert(vm.state is VMState.HALTED) while not outputQ.empty(): output = outputQ.get_nowai...
@with_solutions(13547311, 236453) def solve5(data): # Sunny with a Chance of Asteroids
tape = [int(x) for x in data.split(',')] outputQ = IQueue() vm = IntCodeVM(tape, IQueue([1]), outputQ).run() assert(vm.state is VMState.HALTED) while not outputQ.empty(): output = outputQ.get_nowait() yield output vm.reset(tape, IQueue([5])).run() assert(vm.state is VMState.HA...
valid = lambda p: duplicates(p, lambda v: v == 2) passwords = [p for p in passwords if valid(str(p))] yield len(passwords) @with_solutions(13547311, 236453) def solve5(data): # Sunny with a Chance of Asteroids
64
64
132
28
36
wmdrthr/advent-of-code
2019/adventofcode.py
Python
solve5
solve5
545
562
545
549
109d5e2c1b8269c25ea30e62926e87d8903591f5
bigcode/the-stack
train
c622a3e569691d376b4141c1
train
function
@with_solutions(686, 8384) def solve20(data): # Donut Maze data = [l for l in data.split('\n') if len(l) > 1] grid = {(x,y):c for y,l in enumerate(data) for x,c in enumerate(l)} maze = nx.Graph() start, end = None, None portals = {} for y,row in enumerate(data): for x,v in enumera...
@with_solutions(686, 8384) def solve20(data): # Donut Maze
data = [l for l in data.split('\n') if len(l) > 1] grid = {(x,y):c for y,l in enumerate(data) for x,c in enumerate(l)} maze = nx.Graph() start, end = None, None portals = {} for y,row in enumerate(data): for x,v in enumerate(row): if v != '.': continue ...
return outputQ.get() # Part 1 count = 1 for x in range(50): for y in range(50): if (x, y) == (0,0): continue if check(x, y): count += 1 yield count # Part 2 x, y = 0, 100 while True: if check(x, y): if ch...
163
163
544
22
140
wmdrthr/advent-of-code
2019/adventofcode.py
Python
solve20
solve20
1,315
1,385
1,315
1,319
2d9c4ec41f552f5224e44588adc903d50ae0e019
bigcode/the-stack
train
64f9b8274a54c97892151b33
train
function
@with_solutions(205, 10292) def solve13(data): # Care Package tape = [int(x) for x in data.split(',')] inputQ, outputQ = IQueue(), IQueue() # Part 1 vm = IntCodeVM(tape, inputQ, outputQ) vm.start('breakout') counter = 0 while vm.state is VMState.RUNNING: x = outputQ.get(block...
@with_solutions(205, 10292) def solve13(data): # Care Package
tape = [int(x) for x in data.split(',')] inputQ, outputQ = IQueue(), IQueue() # Part 1 vm = IntCodeVM(tape, inputQ, outputQ) vm.start('breakout') counter = 0 while vm.state is VMState.RUNNING: x = outputQ.get(block = True, timeout = 1) y = outputQ.get(block = True, timeout ...
self.steps *= 2 break simulations = [] for dim in (0, 1, 2): sim = Sim(original_state, dim) simulations.append(sim) threading.Thread(target=Sim.run, args=(sim,)).start() for sim in simulations: sim.thread.join() steps = [sim.step...
118
118
395
21
97
wmdrthr/advent-of-code
2019/adventofcode.py
Python
solve13
solve13
909
967
909
913
4d07ac4975b9314df664278fa53571a2d369986a
bigcode/the-stack
train
31aa614e540bee57e8da98d5
train
function
def guess_day(): """ Today's date, if it's during the Advent of Code. Happy Holidays! Raises exception otherwise. """ today = datetime.now(tz=pytz.timezone('Asia/Kolkata')) if today.year != YEAR or today.month != 12 or today.day > 25: raise Exception('AoC {%d} not currently running, day ...
def guess_day():
""" Today's date, if it's during the Advent of Code. Happy Holidays! Raises exception otherwise. """ today = datetime.now(tz=pytz.timezone('Asia/Kolkata')) if today.year != YEAR or today.month != 12 or today.day > 25: raise Exception('AoC {%d} not currently running, day must be provided....
-id - ', str(err)) print("""Puzzle inputs differ by user. Log in to the Advent of Code site, then check your cookies to get the value of session-id. Save this value in {}""".format(os.path.expanduser(SESSIONID_FILE))) sys.exit(3) def guess_day():
64
64
92
4
60
wmdrthr/advent-of-code
2019/adventofcode.py
Python
guess_day
guess_day
42
50
42
42
64b3419b35e226c5ee19c8c2cea5355e6051c23b
bigcode/the-stack
train
a8354eab4c7f8f1c9694856e
train
function
@with_solutions(4775, 37889219674304) def solve22(data): # Slam Shuffle def shuffle(number_of_cards, p): for line in data.split('\n'): if line == 'deal into new stack': p = (number_of_cards - 1 - p) % number_of_cards else: n = int(line.split(' ')...
@with_solutions(4775, 37889219674304) def solve22(data): # Slam Shuffle
def shuffle(number_of_cards, p): for line in data.split('\n'): if line == 'deal into new stack': p = (number_of_cards - 1 - p) % number_of_cards else: n = int(line.split(' ')[-1]) if line[:3] == 'cut': p = (p - n) % ...
AND B J') springscript('AND C J') springscript('NOT J J') springscript('AND D J') springscript('OR E T') springscript('OR H T') springscript('AND T J') springscript('RUN') vm.reset(tape).run() while True: output = outputQ.get_nowait() if output > 256: yie...
118
118
396
25
92
wmdrthr/advent-of-code
2019/adventofcode.py
Python
solve22
solve22
1,436
1,481
1,436
1,440
ebf96f36eaafd2a636a8b7fc715884912f2c3a1b
bigcode/the-stack
train
861dcad8a79607d7a8de35a0
train
function
def display(grid, tiles): # Given a dict representing a point grid, print the grid, using # the given tileset. max_x = max_y = 0 min_x = min_y = 65536 for point in grid.keys(): min_x = min(min_x, point[0]) max_x = max(max_x, point[0]) min_y = min(min_y, point[1]) max...
def display(grid, tiles): # Given a dict representing a point grid, print the grid, using # the given tileset.
max_x = max_y = 0 min_x = min_y = 65536 for point in grid.keys(): min_x = min(min_x, point[0]) max_x = max(max_x, point[0]) min_y = min(min_y, point[1]) max_y = max(max_y, point[1]) for y in range(min_y, max_x + 1): row = [] for x in range(min_x, max_x + ...
CTIONS: dx, dy = DIRECTIONS[dir][0] yield (dir, (point[0] + dx, point[1] + dy)) def display(grid, tiles): # Given a dict representing a point grid, print the grid, using # the given tileset.
63
64
157
29
34
wmdrthr/advent-of-code
2019/adventofcode.py
Python
display
display
131
147
131
134
dd6e1362d7fab37dc7719681ac6fcf5a058d5730
bigcode/the-stack
train
3452bb360290fe4693ab4fd7
train
function
@with_solutions(134807554, None) def solve25(data): # Cryostasis tape = [int(x) for x in data.split(',')] inputQ, outputQ = IQueue(), IQueue() vm = IntCodeVM(tape, inputQ, outputQ) vm.start('droid') def enter(command): inputQ.put([ord(c) for c in command]) inputQ.put(10) ...
@with_solutions(134807554, None) def solve25(data): # Cryostasis
tape = [int(x) for x in data.split(',')] inputQ, outputQ = IQueue(), IQueue() vm = IntCodeVM(tape, inputQ, outputQ) vm.start('droid') def enter(command): inputQ.put([ord(c) for c in command]) inputQ.put(10) def read_output(print_output=False): output = [] mess...
0].put(buffer[-2:]) buffer = [] # Part 1 vms = [] for n in range(50): interconnect[n].put(n) vm = NetworkedIntCodeVM(tape, interconnect[n], outputQ, interconnect) vms.append(vm) packet = run(vms) yield packet[1] # Part 2 vms = [] for n in range(...
169
169
564
21
148
wmdrthr/advent-of-code
2019/adventofcode.py
Python
solve25
solve25
1,545
1,632
1,545
1,549
e44664a82aeed2d8571103b39a3399ef64b35b47
bigcode/the-stack
train
20f8478c4dcc1149ce1c518b
train
function
@with_solutions(1590844, 1184209) def solve14(data): # Space Stoichiometry pattern = re.compile(r'^((?:\d+ [A-Z]+, )*\d+ [A-Z]+) => (\d+) ([A-Z]+)$') reactions = {} for line in data.split('\n'): match = pattern.search(line) if match: output = (int(match.group(2)), match.gr...
@with_solutions(1590844, 1184209) def solve14(data): # Space Stoichiometry
pattern = re.compile(r'^((?:\d+ [A-Z]+, )*\d+ [A-Z]+) => (\d+) ([A-Z]+)$') reactions = {} for line in data.split('\n'): match = pattern.search(line) if match: output = (int(match.group(2)), match.group(3)) inputs = [] for input in match.group(1).split(', ...
: ball = (x, y) if ball[0] < paddle[0]: inputQ.put(-1) elif ball[0] > paddle[0]: inputQ.put(1) else: inputQ.put(0) while not outputQ.empty(): x = outputQ.get() y = outputQ.get() t = outputQ.get(...
131
131
439
26
104
wmdrthr/advent-of-code
2019/adventofcode.py
Python
solve14
solve14
970
1,028
970
974
1bdbd505e7836aaef0e2049d368e754c919e738a
bigcode/the-stack
train
8d3a9ff70e5f9230925c70a0
train
function
@with_solutions(2465411646, 69781) def solve9(data): # Sensor Boost tape = [int(x) for x in data.split(',')] outputQ = IQueue() # Part 1 vm = IntCodeVM(tape, IQueue([1]), outputQ).run() yield outputQ.get_nowait() # Part 2 vm.inputQ.put(2) vm.reset(tape).run() yield outputQ.ge...
@with_solutions(2465411646, 69781) def solve9(data): # Sensor Boost
tape = [int(x) for x in data.split(',')] outputQ = IQueue() # Part 1 vm = IntCodeVM(tape, IQueue([1]), outputQ).run() yield outputQ.get_nowait() # Part 2 vm.inputQ.put(2) vm.reset(tape).run() yield outputQ.get_nowait()
= chars[pixels[i]] break for row in range(HEIGHT): print(' '.join(image[row*WIDTH:(row+1)*WIDTH])) yield 'CYKBY' @with_solutions(2465411646, 69781) def solve9(data): # Sensor Boost
64
64
108
24
40
wmdrthr/advent-of-code
2019/adventofcode.py
Python
solve9
solve9
699
714
699
703
a3b9e92c5e1e25a5c75559c884b323ecdb9bcdfb
bigcode/the-stack
train
a47f1be0b79fd86137351720
train
class
@dataclass class V3: x: int = 0 y: int = 0 z: int = 0 def __repr__(self): return '<{},{},{}>'.format(self.x, self.y, self.z) def __getitem__(self, dim): if not 0 <= dim <= 2: raise IndexError(f'invalid dimension: {dim}') if dim == 0: return self.x elif d...
@dataclass class V3:
x: int = 0 y: int = 0 z: int = 0 def __repr__(self): return '<{},{},{}>'.format(self.x, self.y, self.z) def __getitem__(self, dim): if not 0 <= dim <= 2: raise IndexError(f'invalid dimension: {dim}') if dim == 0: return self.x elif dim == 1: return self....
]) min_y = min(min_y, point[1]) max_y = max(max_y, point[1]) for y in range(min_y, max_x + 1): row = [] for x in range(min_x, max_x + 1): row.append(tiles[grid[(x, y)]]) print(''.join(row)) @dataclass class V3:
84
84
281
7
77
wmdrthr/advent-of-code
2019/adventofcode.py
Python
V3
V3
150
183
150
151
7ca437aca23e3f33a155e29a4ddcf13028d35c02
bigcode/the-stack
train
96010c8838aa79f8a6d5a64e
train
function
@with_solutions(162439, 367) def solve6(data): # Universal Orbit Map orbital_map = collections.defaultdict(list) primaries = {} satellites = collections.defaultdict(set) entries = [l.strip().split(')', 2) for l in data.split('\n') if len(l) > 1] for a, b in entries: primaries[b] = a ...
@with_solutions(162439, 367) def solve6(data): # Universal Orbit Map
orbital_map = collections.defaultdict(list) primaries = {} satellites = collections.defaultdict(set) entries = [l.strip().split(')', 2) for l in data.split('\n') if len(l) > 1] for a, b in entries: primaries[b] = a orbital_map[a].append(b) # Part 1 orbital_counter = collect...
]), outputQ).run() assert(vm.state is VMState.HALTED) while not outputQ.empty(): output = outputQ.get_nowait() yield output vm.reset(tape, IQueue([5])).run() assert(vm.state is VMState.HALTED) yield outputQ.get_nowait() @with_solutions(162439, 367) def solve6(data): # Universal Orb...
91
91
305
22
69
wmdrthr/advent-of-code
2019/adventofcode.py
Python
solve6
solve6
565
609
565
569
00b2e17d36418977cc3cbd815911dd8115b8d982
bigcode/the-stack
train
0f392ecbea86f97c09b9d098
train
function
def neighbors(point): for dir in DIRECTIONS: dx, dy = DIRECTIONS[dir][0] yield (dir, (point[0] + dx, point[1] + dy))
def neighbors(point):
for dir in DIRECTIONS: dx, dy = DIRECTIONS[dir][0] yield (dir, (point[0] + dx, point[1] + dy))
'→' : [( 1, 0), ['↑', '↓'], 4]} def move(point, direction): (dx, dy) = DIRECTIONS[direction][0] return (point[0] + dx, point[1] + dy) def neighbors(point):
64
64
43
4
60
wmdrthr/advent-of-code
2019/adventofcode.py
Python
neighbors
neighbors
124
127
124
124
066702e8700fea25872d027fccd9533614267e8f
bigcode/the-stack
train
15b4a1503bc08954708e3645
train
function
@with_solutions(2176, 'CYKBY') def solve8(data): # Space Image Format WIDTH, HEIGHT = 25, 6 AREA = WIDTH * HEIGHT layers = [] for layer in range(len(data) // AREA): layers.append(data[layer * AREA : (layer + 1) * AREA]) # Part 1 minzeros = (65536, 0) for index, layer in enumer...
@with_solutions(2176, 'CYKBY') def solve8(data): # Space Image Format
WIDTH, HEIGHT = 25, 6 AREA = WIDTH * HEIGHT layers = [] for layer in range(len(data) // AREA): layers.append(data[layer * AREA : (layer + 1) * AREA]) # Part 1 minzeros = (65536, 0) for index, layer in enumerate(layers): zeros = layer.count('0') if zeros < minzeros[0]...
[4], queueDE, queueEA))] for amp in amps: amp.start() amps[-1].join() while not queueEA.empty(): output = queueEA.get_nowait() max_output = max(max_output, output) yield max_output @with_solutions(2176, 'CYKBY') def solve8(data): # Space Image Format
82
82
275
24
57
wmdrthr/advent-of-code
2019/adventofcode.py
Python
solve8
solve8
662
696
662
666
5770a5d396fe6ad24fdfaab5956cd78192ff357e
bigcode/the-stack
train
3b09ed69d6fbf62e21dec5f1
train
function
def manhattan(a, b = ORIGIN): return abs(a[0] - b[0]) + abs(a[1] - b[1])
def manhattan(a, b = ORIGIN):
return abs(a[0] - b[0]) + abs(a[1] - b[1])
e: if e.args[0] == "'NoneType' object is not an iterator": return else: raise e return wrapped_method return wrapper ################################################################################ # Common Code ORIGIN = (0, 0) def ...
64
64
33
10
54
wmdrthr/advent-of-code
2019/adventofcode.py
Python
manhattan
manhattan
112
113
112
112
4a001e8501a48a9b0ab0a139b1bdef707224c477
bigcode/the-stack
train
906351173d8c86e01698c890
train
function
@with_solutions(1150, 748) def solve4(data): # Secure Container def increasing(n): ns = list(n) if ns == sorted(ns): return True return False def duplicates(n, check): counter = collections.defaultdict(int) for d in list(n): counter[d] += 1 ...
@with_solutions(1150, 748) def solve4(data): # Secure Container
def increasing(n): ns = list(n) if ns == sorted(ns): return True return False def duplicates(n, check): counter = collections.defaultdict(int) for d in list(n): counter[d] += 1 return len([v for v in counter.values() if check(v)]) > 0 ...
2 signal_delay = [sum(v[1]) for (k,v) in grid.items() if v[0] == 3] signal_delay.sort() yield signal_delay[0] @with_solutions(1150, 748) def solve4(data): # Secure Container
64
64
203
21
43
wmdrthr/advent-of-code
2019/adventofcode.py
Python
solve4
solve4
515
542
515
519
cbbcb3f217dba66e6843b007b8dc087d6453fe87
bigcode/the-stack
train
bfb633fe3be70c9a43e5ae96
train
class
class NetworkedIntCodeVM(IntCodeVM): def __init__(self, program = None, inputQ = None, outputQ = None, interconnect = None): IntCodeVM.__init__(self, program, inputQ, outputQ) self.buffer = [] self.idle = False self.interconnect = interconnect def read(self, mo...
class NetworkedIntCodeVM(IntCodeVM):
def __init__(self, program = None, inputQ = None, outputQ = None, interconnect = None): IntCodeVM.__init__(self, program, inputQ, outputQ) self.buffer = [] self.idle = False self.interconnect = interconnect def read(self, modes): destination = self.dest(...
if self.state == VMState.RUNNING: self.state = VMState.HALTED return self def start(self, name): self.thread = threading.Thread(target=IntCodeVM.run, name=name, args=(self,), daemon=True) self.thread.start() return self class NetworkedIntCodeVM(IntCodeVM):
72
72
242
10
61
wmdrthr/advent-of-code
2019/adventofcode.py
Python
NetworkedIntCodeVM
NetworkedIntCodeVM
383
413
383
384
4573bcbb0e69d85c430e7354b1816eb1d0c9abd4
bigcode/the-stack
train
64a842eba97f36549da9f3c1
train
function
def get_session_id(): try: sessionid = open(os.path.expanduser(SESSIONID_FILE)).read() return sessionid.strip() except (OSError, IOError) as err: print('Could not load session-id - ', str(err)) print("""Puzzle inputs differ by user. Log in to the Advent of Code site, then check y...
def get_session_id():
try: sessionid = open(os.path.expanduser(SESSIONID_FILE)).read() return sessionid.strip() except (OSError, IOError) as err: print('Could not load session-id - ', str(err)) print("""Puzzle inputs differ by user. Log in to the Advent of Code site, then check your cookies to get the...
T from dataclasses import dataclass import copy import pytz import requests import networkx as nx YEAR = 2019 SESSIONID_FILE = '~/.config/adventofcode/session' USER_AGENT = 'wmdrthr/advent-of-code' def get_session_id():
64
64
108
5
59
wmdrthr/advent-of-code
2019/adventofcode.py
Python
get_session_id
get_session_id
31
40
31
31
c8e9c7791af15720fdbcfb3c6e7a1cc93dcf974d
bigcode/the-stack
train
8d7c2f4e8fb930be4517edbb
train
class
class IntCodeVM(): def __init__(self, program = None, inputQ = None, outputQ = None): self.state = VMState.START self.reset(program, inputQ, outputQ) def reset(self, program, inputQ = None, outputQ = None): self.ip = 0 self.base = 0 if inputQ: self.inputQ =...
class IntCodeVM():
def __init__(self, program = None, inputQ = None, outputQ = None): self.state = VMState.START self.reset(program, inputQ, outputQ) def reset(self, program, inputQ = None, outputQ = None): self.ip = 0 self.base = 0 if inputQ: self.inputQ = inputQ if o...
elif dim == 1: self.y = value elif dim == 2: self.z = value def __add__(self, other): return V3(self.x + other.x, self.y + other.y, self.z + other.z) def __iadd__(self, other): self.x += other.x self.y += other.y self.z += other.z return self def __int__(s...
256
256
1,291
5
250
wmdrthr/advent-of-code
2019/adventofcode.py
Python
IntCodeVM
IntCodeVM
212
381
212
213
303df12196f6e7fd2e39ebbb27a4e10c173fd9d8
bigcode/the-stack
train
3766033e948a3cbc0cdb338c
train
function
@with_solutions(192, 8381082) def solve19(data): # Tractor Beam tape = [int(x) for x in data.split(',')] grid = collections.defaultdict(int) inputQ, outputQ = IQueue(), IQueue() vm = IntCodeVM(tape, inputQ, outputQ) def check(x, y): vm.reset(tape) inputQ.put([x, y]) ...
@with_solutions(192, 8381082) def solve19(data): # Tractor Beam
tape = [int(x) for x in data.split(',')] grid = collections.defaultdict(int) inputQ, outputQ = IQueue(), IQueue() vm = IntCodeVM(tape, inputQ, outputQ) def check(x, y): vm.reset(tape) inputQ.put([x, y]) vm.run() return outputQ.get() # Part 1 count = 1 ...
x in data.split(',')] tape[0] = 2 vm.reset(tape) vm.start('robot') vm.thread.join() while not outputQ.empty(): output = outputQ.get() yield output @with_solutions(192, 8381082) def solve19(data): # Tractor Beam
72
72
241
22
49
wmdrthr/advent-of-code
2019/adventofcode.py
Python
solve19
solve19
1,274
1,312
1,274
1,278
d1116272707195c1e98036b0654234b977248f2f
bigcode/the-stack
train
59ab69740c7e2571e253911f
train
function
def with_solutions(*expected): def wrapper(f): error_msg = 'Incorrect solution for Part {}: Expected "{}", Actual "{}"' def wrapped_method(*args, **kwargs): fgen = f(*args) try: for index in range(2): actual = next(fgen) ...
def with_solutions(*expected):
def wrapper(f): error_msg = 'Incorrect solution for Part {}: Expected "{}", Actual "{}"' def wrapped_method(*args, **kwargs): fgen = f(*args) try: for index in range(2): actual = next(fgen) if expected[index] is not None...
Unexpected response: (status = {})\n{}'.format(response.status_code, response.content)) data = response.text print('Fetched data for day {}'.format(day)) with open(inputfile, 'w') as output: output.write(data...
64
64
169
7
56
wmdrthr/advent-of-code
2019/adventofcode.py
Python
with_solutions
with_solutions
83
106
83
83
02fb78efe7088b260a0c6c4612f238f07aa9221c
bigcode/the-stack
train
42f03a1e71f0ceab1ac48237
train
function
@with_solutions('11833188', '55005000') def solve16(data): # Flawed Frequency Transmission base_pattern = [0, 1, 0, -1] def nth_pattern(n): if n == 0: return itertools.islice(itertools.cycle(base_pattern), 1, None) pattern = [] for val in base_pattern: patt...
@with_solutions('11833188', '55005000') def solve16(data): # Flawed Frequency Transmission
base_pattern = [0, 1, 0, -1] def nth_pattern(n): if n == 0: return itertools.islice(itertools.cycle(base_pattern), 1, None) pattern = [] for val in base_pattern: pattern += [val] * (n + 1) return itertools.islice(itertools.cycle(pattern), 1, None) # ...
OXYGEN] empty_neighbors = [move(p, dir) for p in oxygenated for dir in DIRECTIONS.keys() if maze[move(p, dir)] == EMPTY] if len(empty_neighbors) == 0: break for p in empty_neighbors: maze[p] = OXYGEN time += 1 yield time @with_solu...
103
103
346
26
76
wmdrthr/advent-of-code
2019/adventofcode.py
Python
solve16
solve16
1,115
1,153
1,115
1,119
8af5003e79646acaa4795e8004fe4bec9132f49c
bigcode/the-stack
train
3b377fb411b1730db4da8425
train
function
@with_solutions(3562672, 8250) def solve2(data): # 1202 Program Alarm tape = [int(x) for x in data.split(',')] # Part 1 program = tape[:] program[1:3] = [12,2] vm = IntCodeVM(program).run() assert(vm.state is VMState.HALTED) yield vm.memory[0] # Part 2 for x in range(100): ...
@with_solutions(3562672, 8250) def solve2(data): # 1202 Program Alarm
tape = [int(x) for x in data.split(',')] # Part 1 program = tape[:] program[1:3] = [12,2] vm = IntCodeVM(program).run() assert(vm.state is VMState.HALTED) yield vm.memory[0] # Part 2 for x in range(100): for y in range(100): program = tape[:] progr...
_fuel <= 0: break total_fuel += extra_fuel fuel = extra_fuel yield total_basic_fuel yield total_fuel @with_solutions(3562672, 8250) def solve2(data): # 1202 Program Alarm
64
64
179
26
37
wmdrthr/advent-of-code
2019/adventofcode.py
Python
solve2
solve2
442
465
442
446
df0a48b7084f509e8e9dbb13954187340aedae3b
bigcode/the-stack
train
5827107dd9476b13ecd08df2
train
function
@with_solutions(2211, 'EFCKUEGC') def solve11(data): # Space Police tape = [int(x) for x in data.split(',')] panel = collections.defaultdict(int) robot = ('↑', ORIGIN) def move(turn): (direction, (x, y)) = robot new_direction = DIRECTIONS[direction][1][turn] dx, dy = DIRE...
@with_solutions(2211, 'EFCKUEGC') def solve11(data): # Space Police
tape = [int(x) for x in data.split(',')] panel = collections.defaultdict(int) robot = ('↑', ORIGIN) def move(turn): (direction, (x, y)) = robot new_direction = DIRECTIONS[direction][1][turn] dx, dy = DIRECTIONS[new_direction][0] return (new_direction, (x + dx, y + dy)) ...
if asteroid != station: targets[angle(asteroid, station)].append((distance(station, asteroid), asteroid)) for angle in targets.keys(): targets[angle].sort(key = lambda t: t[0]) counter = 0 while True: for angle in sorted(targets.keys()): if len(targets[angle]) > 0:...
141
141
471
24
117
wmdrthr/advent-of-code
2019/adventofcode.py
Python
solve11
solve11
767
822
767
771
50fa2527556b54c2f25c7e825ea20b3f5f7bc63e
bigcode/the-stack
train
f42787eea7d6dce4e54f1821
train
function
@with_solutions(3266288, 4896582) def solve1(data): # The Tyranny of the Rocket Equation total_basic_fuel = 0 total_fuel = 0 for module in data.split(): mass = int(module) fuel = math.floor(mass / 3) - 2 total_basic_fuel += fuel total_fuel += fuel while True: ...
@with_solutions(3266288, 4896582) def solve1(data): # The Tyranny of the Rocket Equation
total_basic_fuel = 0 total_fuel = 0 for module in data.split(): mass = int(module) fuel = math.floor(mass / 3) - 2 total_basic_fuel += fuel total_fuel += fuel while True: extra_fuel = math.floor(fuel / 3) - 2 if extra_fuel <= 0: ...
else: self.interconnect[self.buffer[0]].put(self.buffer[1:]) self.buffer = [] self.ip += 2 ################################################################################ # Solvers @with_solutions(3266288, 4896582) def solve1(data): # The Tyranny of the Rocket Equation
64
64
151
29
34
wmdrthr/advent-of-code
2019/adventofcode.py
Python
solve1
solve1
419
439
419
423
922144feb3cfbd13f139beec6f1294e4c88d23d4
bigcode/the-stack
train
2a16c5a1e096738427960b25
train
class
class VMState(Enum): START = 0 INIT = 1 RUNNING = 2 HALTED = 3 CRASHED = 4 INTERRUPTED = 5
class VMState(Enum):
START = 0 INIT = 1 RUNNING = 2 HALTED = 3 CRASHED = 4 INTERRUPTED = 5
iterable: for it in iterable: self.put(it) def put(self, val_or_iterable): try: for val in val_or_iterable: queue.Queue.put(self, val) except TypeError: queue.Queue.put(self, val_or_iterable) class VMState(Enum):
64
64
46
5
59
wmdrthr/advent-of-code
2019/adventofcode.py
Python
VMState
VMState
204
210
204
204
d4ea2ceae67077e289db9e153d7f65787e6410e2
bigcode/the-stack
train
2e113dee7873879294fb7428
train
function
@with_solutions(269, 612) def solve10(data): # Monitoring Station data = [l.strip() for l in data.split('\n') if len(l) > 1] asteroids = [(x, y) for y,l in enumerate(data) for x,c in enumerate(l) if c == '#'] def angle(x, y): angle = math.atan2(x[0] - y[0], y[1] - x[1]) if angle < 0: ...
@with_solutions(269, 612) def solve10(data): # Monitoring Station
data = [l.strip() for l in data.split('\n') if len(l) > 1] asteroids = [(x, y) for y,l in enumerate(data) for x,c in enumerate(l) if c == '#'] def angle(x, y): angle = math.atan2(x[0] - y[0], y[1] - x[1]) if angle < 0: angle += 2 * math.pi return round(angle, 10) # ...
def solve9(data): # Sensor Boost tape = [int(x) for x in data.split(',')] outputQ = IQueue() # Part 1 vm = IntCodeVM(tape, IQueue([1]), outputQ).run() yield outputQ.get_nowait() # Part 2 vm.inputQ.put(2) vm.reset(tape).run() yield outputQ.get_nowait() @with_solutions(269, 612...
114
114
382
20
94
wmdrthr/advent-of-code
2019/adventofcode.py
Python
solve10
solve10
717
764
717
721
b649037832a996a7956b0e3de46fe3ff0d035ced
bigcode/the-stack
train
86fca5428305f888e28b9236
train
class
class IQueue(queue.Queue): def __init__(self, iterable = None): queue.Queue.__init__(self) if iterable: for it in iterable: self.put(it) def put(self, val_or_iterable): try: for val in val_or_iterable: queue.Queue.put(self, val) ...
class IQueue(queue.Queue):
def __init__(self, iterable = None): queue.Queue.__init__(self) if iterable: for it in iterable: self.put(it) def put(self, val_or_iterable): try: for val in val_or_iterable: queue.Queue.put(self, val) except TypeError: ...
, other): self.x += other.x self.y += other.y self.z += other.z return self def __int__(self): return abs(self.x) + abs(self.y) + abs(self.z) ################################################################################ # IntCode VM class IQueue(queue.Queue):
64
64
86
6
57
wmdrthr/advent-of-code
2019/adventofcode.py
Python
IQueue
IQueue
189
202
189
190
066ec1bc4aabd9a981fcb7888d4ef70e1b41963a
bigcode/the-stack
train
5851c82c6802be327c6db821
train
function
def get_data(day): "Get input data for day (1-25) and year (> 2015)" inputfile = 'inputs/input{:02}.txt'.format(day) if os.path.exists(inputfile): data = open(inputfile).read() else: # if trying to fetch the data for the current AoC, check if the # day's puzzle has unlocked yet...
def get_data(day):
"Get input data for day (1-25) and year (> 2015)" inputfile = 'inputs/input{:02}.txt'.format(day) if os.path.exists(inputfile): data = open(inputfile).read() else: # if trying to fetch the data for the current AoC, check if the # day's puzzle has unlocked yet now = date...
if it's during the Advent of Code. Happy Holidays! Raises exception otherwise. """ today = datetime.now(tz=pytz.timezone('Asia/Kolkata')) if today.year != YEAR or today.month != 12 or today.day > 25: raise Exception('AoC {%d} not currently running, day must be provided.'.format(YEAR)) retur...
87
87
290
5
81
wmdrthr/advent-of-code
2019/adventofcode.py
Python
get_data
get_data
52
81
52
52
166ac21114bdc5aed62277c7994707ac462ad579
bigcode/the-stack
train
bd1f9de1abb27e5fbbc6b831
train
function
def move(point, direction): (dx, dy) = DIRECTIONS[direction][0] return (point[0] + dx, point[1] + dy)
def move(point, direction):
(dx, dy) = DIRECTIONS[direction][0] return (point[0] + dx, point[1] + dy)
1), ['→', '←'], 2], '←' : [(-1, 0), ['↓', '↑'], 3], '→' : [( 1, 0), ['↑', '↓'], 4]} def move(point, direction):
63
64
37
6
57
wmdrthr/advent-of-code
2019/adventofcode.py
Python
move
move
120
122
120
120
709dd2571e16d7920155dd9c882967dcd4324e92
bigcode/the-stack
train
2cb6a5a4580a6be48cd18eb3
train
function
@with_solutions(236, 368) def solve15(data): # Oxygen System tape = [int(x) for x in data.split(',')] UNKNOWN = 0 EMPTY = 1 WALL = 2 OXYGEN = 3 maze = collections.defaultdict(int, {(0,0): EMPTY}) oxygen_system = None def navigate(current, dest, prev = None): path = None ...
@with_solutions(236, 368) def solve15(data): # Oxygen System
tape = [int(x) for x in data.split(',')] UNKNOWN = 0 EMPTY = 1 WALL = 2 OXYGEN = 3 maze = collections.defaultdict(int, {(0,0): EMPTY}) oxygen_system = None def navigate(current, dest, prev = None): path = None for dir in DIRECTIONS.keys(): next = move(curre...
) surplus[target] += output_amount * production_ratio - target_amount return ore # Part 1 fuel_cost = calculate('FUEL', 1) yield fuel_cost # Part 2 ore = 1000000000000 target_fuel = ore // fuel_cost fuel = 0 surplus = collections.defaultdict(int) while ore and targe...
182
182
608
20
161
wmdrthr/advent-of-code
2019/adventofcode.py
Python
solve15
solve15
1,031
1,112
1,031
1,035
f038ac951e4fe336bf6678bbfcbd0081d649333e
bigcode/the-stack
train
d2f5459dd27d31f33c6b9c44
train
function
@with_solutions(27061 ,19406) def solve23(data): # Category Six tape = [int(x) for x in data.split(',')] interconnect = [IQueue() for _ in range(50)] outputQ = IQueue() def stop_vms(vms): for vm in vms: vm.interrupt() vm.thread.join() def run(vms, nat=False):...
@with_solutions(27061 ,19406) def solve23(data): # Category Six
tape = [int(x) for x in data.split(',')] interconnect = [IQueue() for _ in range(50)] outputQ = IQueue() def stop_vms(vms): for vm in vms: vm.interrupt() vm.thread.join() def run(vms, nat=False): buffer = [] history = set() for n in range(50...
) final_offset = offset * (1 - final_increment) * inv((1 - increment) % number_of_cards) final_offset %= number_of_cards return (final_offset + p * final_increment) % number_of_cards # Part 1 yield shuffle(10007, 2019) # Part 2 yield shuffle2(119315717514047, 2020, 10174158207...
115
115
385
21
94
wmdrthr/advent-of-code
2019/adventofcode.py
Python
solve23
solve23
1,484
1,542
1,484
1,488
e35d4a709be02f907c9e2fa524c84637b030dff3
bigcode/the-stack
train
581341aa3067e4e5b6ef0046
train
function
@with_solutions(19360288, 1143814750) def solve21(data): # Springdroid Adventure tape = [int(x) for x in data.split(',')] inputQ, outputQ = IQueue(), IQueue() vm = IntCodeVM(tape, inputQ, outputQ) def springscript(program): inputQ.put([ord(c) for c in program]) inputQ.put(10) ...
@with_solutions(19360288, 1143814750) def solve21(data): # Springdroid Adventure
tape = [int(x) for x in data.split(',')] inputQ, outputQ = IQueue(), IQueue() vm = IntCodeVM(tape, inputQ, outputQ) def springscript(program): inputQ.put([ord(c) for c in program]) inputQ.put(10) # Part 1 springscript('OR A J') springscript('AND B J') springscript('AND...
_change = maze.edges[point, neighbor]['level'] if level + level_change >= 0: _queue.add((neighbor, level+level_change)) queue = _queue - visited steps += 1 if target in queue: break yield steps @with_solutions(19360288, 1143814750) def solve21...
87
87
291
27
59
wmdrthr/advent-of-code
2019/adventofcode.py
Python
solve21
solve21
1,388
1,433
1,388
1,392
c78b0aa2754cfbf7a27642985cd792630babfc10
bigcode/the-stack
train
c0d4ba185970ace0c3959eb3
train
function
@with_solutions(7928, 518311327635164) def solve12(data): # The N-Body Problem @dataclass class Moon: position: V3 velocity: V3 def __repr__(self): return '(P{}, V{})'.format(self.position, self.velocity) def __int__(self): return int(self.position...
@with_solutions(7928, 518311327635164) def solve12(data): # The N-Body Problem @dataclass
class Moon: position: V3 velocity: V3 def __repr__(self): return '(P{}, V{})'.format(self.position, self.velocity) def __int__(self): return int(self.position) * int(self.velocity) def time_step(self): self.position += self.velocity ...
color = inputQ.get(block = True, timeout = 1) turn = inputQ.get(block = True, timeout = 1) panel[robot[1]] = color painted.add(robot[1]) robot = move(turn) locations = sorted(panel.keys(), key=manhattan) chars = [U.lookup('LIGHT SHADE'), U.lookup('FULL BLOCK')] for ...
191
191
637
33
158
wmdrthr/advent-of-code
2019/adventofcode.py
Python
solve12
solve12
825
906
825
830
21f73dc979dd0ca2ef776ea38771a63e52bd9a3f
bigcode/the-stack
train
2ccb7be232b82d29d3ec4c0c
train
function
@with_solutions(844468, 4215746) def solve7(data): # Amplification Circuit tape = [int(x) for x in data.split(',')] # Part 1 max_output = 0 vm = IntCodeVM() for phase_setting in itertools.permutations([0, 1, 2, 3, 4]): current_input = 0 for n in range(5): outputQ =...
@with_solutions(844468, 4215746) def solve7(data): # Amplification Circuit
tape = [int(x) for x in data.split(',')] # Part 1 max_output = 0 vm = IntCodeVM() for phase_setting in itertools.permutations([0, 1, 2, 3, 4]): current_input = 0 for n in range(5): outputQ = IQueue() vm.reset(tape, IQueue([phase_setting[n], current_input]), o...
= primaries.get(object, None) while primary is not None: satellites[primary].add(object) primary = primaries.get(primary, None) def count_transfers(current, target): transfers = 0 current = primaries[current] while True: current = primaries[curre...
144
144
483
24
120
wmdrthr/advent-of-code
2019/adventofcode.py
Python
solve7
solve7
612
659
612
616
905bf18a6f1f8a5987bda699f49d3df9a91eaf1a
bigcode/the-stack
train
9b3f5447024a4f096ae64850
train
function
@with_solutions(2129, 134662) def solve3(data): # Crossed Wires grid = collections.defaultdict(lambda: (0, [0,0])) def points(start, direction, distance): x, y = start for step in range(distance): if direction == 'R': point = (x + 1, y) elif directi...
@with_solutions(2129, 134662) def solve3(data): # Crossed Wires
grid = collections.defaultdict(lambda: (0, [0,0])) def points(start, direction, distance): x, y = start for step in range(distance): if direction == 'R': point = (x + 1, y) elif direction == 'U': point = (x, y - 1) elif directi...
# Part 2 for x in range(100): for y in range(100): program = tape[:] program[1:3] = [x,y] vm.reset(program).run() assert(vm.state is VMState.HALTED) if vm.memory[0] == 19690720: n = 100 * x + y yield n @wi...
109
109
365
24
84
wmdrthr/advent-of-code
2019/adventofcode.py
Python
solve3
solve3
468
512
468
472
a50026d08dd6f3d24cc27ccaf19e55285bd80c98
bigcode/the-stack
train
fb92c46bf0a1738a66afcc56
train
class
class ApplicationsTable(commands.Cog): """ Cog for managing applications. """ # Teacher application attributes teacher_app_channel_id: int = int(os.getenv('TEACHER_APPLICATION_CHANNEL_ID')) teacher_app_cat_id: int = int(os.getenv('TEACHER_APPLICATION_CAT_ID')) teacher_parent_channel_id: int = int(o...
class ApplicationsTable(commands.Cog):
""" Cog for managing applications. """ # Teacher application attributes teacher_app_channel_id: int = int(os.getenv('TEACHER_APPLICATION_CHANNEL_ID')) teacher_app_cat_id: int = int(os.getenv('TEACHER_APPLICATION_CAT_ID')) teacher_parent_channel_id: int = int(os.getenv('TEACHER_CHANNEL_ID')) tea...
import discord from discord.ext import commands from mysqldb import the_database from typing import Any, List, Dict, Union from extra import utils import os cosmos_id: int = int(os.getenv('COSMOS_ID')) muffin_id: int = int(os.getenv('MUFFIN_ID')) moderator_role_id: int = int(os.getenv('MOD_ROLE_ID')) admin_role_id: i...
120
256
2,053
7
113
erkantaylan/sloth-bot
extra/reportsupport/applications.py
Python
ApplicationsTable
ApplicationsTable
15
229
15
15
f65d56d93b2d3c5d508d9d48629b12af379c9d42
bigcode/the-stack
train
8d736f4920a7b303ffdc6ec0
train
function
def test(name, expr): if args.filter and args.filter not in name: return vaex_expr = expr + ".nop()" N = 5 # t = timeit.Timer(vaex_expr, globals={'df': df_vaex}) # print(name, expr) # t_vaex = min(t.repeat(3, N))/N/(10**args.n) # print("\tvaex", t_vaex) t_vaex = min(mytimeit(vae...
def test(name, expr):
if args.filter and args.filter not in name: return vaex_expr = expr + ".nop()" N = 5 # t = timeit.Timer(vaex_expr, globals={'df': df_vaex}) # print(name, expr) # t_vaex = min(t.repeat(3, N))/N/(10**args.n) # print("\tvaex", t_vaex) t_vaex = min(mytimeit(vaex_expr, N, scope={'df'...
.buffer_size = len(df_vaex)//args.partitions df_pandas = df[:int(10**args.npandas)].to_pandas_df() if use_dask: df_dask = dd.from_pandas(df_pandas, npartitions=4) timings = {} def mytimeit(expr, N, scope): times = [] for i in range(N): t0 = time.time() eval(expr, scope) times.append...
114
114
380
6
107
skywalk163/vaex
benchmarks/strings.py
Python
test
test
80
109
80
80
402fecee87740bb87bd93900546f08547d926d32
bigcode/the-stack
train
10fa03191e1f753b6e333414
train
function
def mytimeit(expr, N, scope): times = [] for i in range(N): t0 = time.time() eval(expr, scope) times.append(time.time() - t0) return times
def mytimeit(expr, N, scope):
times = [] for i in range(N): t0 = time.time() eval(expr, scope) times.append(time.time() - t0) return times
ex)//args.partitions df_pandas = df[:int(10**args.npandas)].to_pandas_df() if use_dask: df_dask = dd.from_pandas(df_pandas, npartitions=4) timings = {} def mytimeit(expr, N, scope):
64
64
48
10
54
skywalk163/vaex
benchmarks/strings.py
Python
mytimeit
mytimeit
73
79
73
73
1b22270520199f6e260f9eec33dbcf0c2ee169d2
bigcode/the-stack
train
387e1cb54d2965e96689bc60
train
function
def gggg(qq): fr = open(qq, "rb") fw = open("/home/tarena/ggg", "ab") while 1: o = fr.read(1024) if not o: break fw.write(o)
def gggg(qq):
fr = open(qq, "rb") fw = open("/home/tarena/ggg", "ab") while 1: o = fr.read(1024) if not o: break fw.write(o)
def gggg(qq):
7
64
59
7
0
gary-gggggg/gary
2-mouth02/day03/exe05 wife.py
Python
gggg
gggg
1
8
1
1
e5982cd2d73e34962c69651c944f860ae5bf1d09
bigcode/the-stack
train
15fcd10e7240171a4a58c5c8
train
class
class PluginsTestScenarios(JenkinsPluginsBase): scenarios = multiply_scenarios( JenkinsPluginsBase.scenarios, [ ('s1', dict(v1='1.0.0', op='__gt__', v2='0.8.0')), ('s2', dict(v1='1.0.1alpha', op='__gt__', v2='1.0.0')), ('s3', dict(v1='1.0', op='__eq__', v2='1.0.0...
class PluginsTestScenarios(JenkinsPluginsBase):
scenarios = multiply_scenarios( JenkinsPluginsBase.scenarios, [ ('s1', dict(v1='1.0.0', op='__gt__', v2='0.8.0')), ('s2', dict(v1='1.0.1alpha', op='__gt__', v2='1.0.0')), ('s3', dict(v1='1.0', op='__eq__', v2='1.0.0')), ('s4', dict(v1='1.0', op='__eq__...
enkinsException) as context_manager: self.j.get_plugin_info('test') self.assertEqual( jenkins_mock.call_args[0][0].get_full_url(), self.make_url('pluginManager/api/json?depth=2')) self.assertEqual( str(context_manager.exception), 'Could not par...
245
245
818
10
235
jlakin2/python-jenkins
tests/test_plugins.py
Python
PluginsTestScenarios
PluginsTestScenarios
261
327
261
262
f062b44a0e85ba9ca8fbddc09427d72031091087
bigcode/the-stack
train
749d4f3037503c9ac9589200
train
class
class JenkinsPluginsInfoTest(JenkinsPluginsBase): @patch.object(jenkins.Jenkins, 'jenkins_open') def test_simple(self, jenkins_mock): jenkins_mock.return_value = json.dumps(self.plugin_info_json) # expected to return a list of plugins plugins_info = self.j.get_plugins_info() se...
class JenkinsPluginsInfoTest(JenkinsPluginsBase): @patch.object(jenkins.Jenkins, 'jenkins_open')
def test_simple(self, jenkins_mock): jenkins_mock.return_value = json.dumps(self.plugin_info_json) # expected to return a list of plugins plugins_info = self.j.get_plugins_info() self.assertEqual(plugins_info, self.plugin_info_json['plugins']) self.assertEqual( j...
"backupVersion": u'null', u"bundled": u'true', u"deleted": u'false', u"dependencies": [], u"downgradable": u'false', u"enabled": u'true', u"hasUpdate": u'true', u"longName": u"Jenkins Mailer Plugin", ...
216
216
722
24
192
jlakin2/python-jenkins
tests/test_plugins.py
Python
JenkinsPluginsInfoTest
JenkinsPluginsInfoTest
76
152
76
78
fba3b56dd9047fa1077537684ede2fb95036144c
bigcode/the-stack
train
a260ea8f3ecc1536917a1fd0
train
class
class JenkinsPluginInfoTest(JenkinsPluginsBase): @patch.object(jenkins.Jenkins, 'jenkins_open') def test_shortname(self, jenkins_mock): jenkins_mock.return_value = json.dumps(self.plugin_info_json) # expected to return info on a single plugin plugin_info = self.j.get_plugin_info("maile...
class JenkinsPluginInfoTest(JenkinsPluginsBase): @patch.object(jenkins.Jenkins, 'jenkins_open')
def test_shortname(self, jenkins_mock): jenkins_mock.return_value = json.dumps(self.plugin_info_json) # expected to return info on a single plugin plugin_info = self.j.get_plugin_info("mailer") self.assertEqual(plugin_info, self.plugin_info_json['plugins'][0]) self._check_re...
Raises(jenkins.JenkinsException) as context_manager: self.j.get_plugins_info() self.assertEqual( jenkins_mock.call_args[0][0].get_full_url(), self.make_url('pluginManager/api/json?depth=2')) self.assertEqual( str(context_manager.exception), 'Co...
256
256
966
24
232
jlakin2/python-jenkins
tests/test_plugins.py
Python
JenkinsPluginInfoTest
JenkinsPluginInfoTest
155
258
155
157
6b59436d96d77295f5f0c6116fee6a80c4563533
bigcode/the-stack
train
cb81ab4fc0ae1251db96f3bf
train
class
class PluginsTest(JenkinsPluginsBase): def test_plugin_equal(self): p1 = plugins.Plugin(self.plugin_info_json) p2 = plugins.Plugin(self.plugin_info_json) self.assertEqual(p1, p2) def test_plugin_not_equal(self): p1 = plugins.Plugin(self.plugin_info_json) p2 = plugins...
class PluginsTest(JenkinsPluginsBase):
def test_plugin_equal(self): p1 = plugins.Plugin(self.plugin_info_json) p2 = plugins.Plugin(self.plugin_info_json) self.assertEqual(p1, p2) def test_plugin_not_equal(self): p1 = plugins.Plugin(self.plugin_info_json) p2 = plugins.Plugin(self.plugin_info_json) p...
) v2 = plugins.PluginVersion(self.v2) self.assertTrue(op(v2), msg="Unexpectedly found {0} {2} {1} == False " "when comparing versions!" .format(v1, v2, self.op)) class PluginsTest(JenkinsPluginsBase):
64
64
103
8
56
jlakin2/python-jenkins
tests/test_plugins.py
Python
PluginsTest
PluginsTest
330
345
330
331
66cd538fdd0276e37918be3022de8d90ecd5e42b
bigcode/the-stack
train
16429bc10705e0616d62a3fd
train
class
class JenkinsPluginsBase(JenkinsTestBase): plugin_info_json = { u"plugins": [ { u"active": u'true', u"backupVersion": u'null', u"bundled": u'true', u"deleted": u'false', u"dependencies": [], ...
class JenkinsPluginsBase(JenkinsTestBase):
plugin_info_json = { u"plugins": [ { u"active": u'true', u"backupVersion": u'null', u"bundled": u'true', u"deleted": u'false', u"dependencies": [], u"downgradable": u'false', u...
WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. import json from mock import patch from testscenarios.scenarios import multiply_scenarios import jenkins from jenkins import plugins from tests.base import JenkinsTestBase class JenkinsPluginsBase(JenkinsTestBase):
68
68
228
9
58
jlakin2/python-jenkins
tests/test_plugins.py
Python
JenkinsPluginsBase
JenkinsPluginsBase
43
73
43
44
0a835e0cae3c024a8c0a7a38cf1005c4d62a7fd7
bigcode/the-stack
train
efb0dab394219f0139c7ec98
train
class
class PicklePersistence(BasePersistence): """Using python's builtin pickle for making you bot persistent. Attributes: filename (:obj:`str`): The filename for storing the pickle files. When :attr:`single_file` is false this will be used as a prefix. store_user_data (:obj:`bool`): Opt...
class PicklePersistence(BasePersistence):
"""Using python's builtin pickle for making you bot persistent. Attributes: filename (:obj:`str`): The filename for storing the pickle files. When :attr:`single_file` is false this will be used as a prefix. store_user_data (:obj:`bool`): Optional. Whether user_data should be saved b...
#!/usr/bin/env python # # A library that provides a Python interface to the Telegram Bot API # Copyright (C) 2015-2018 # Leandro Toledo de Souza <devs@python-telegram-bot.org> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser Public License as published by #...
229
256
1,819
7
221
shyguy-ry/paddingCheckBot
python-telegram-bot/telegram/ext/picklepersistence.py
Python
PicklePersistence
PicklePersistence
27
236
27
27
edafc9bfbc9d75221d6b2f4845b88202a201e2fc
bigcode/the-stack
train
7ee94db055b061e18e913c57
train
function
def plot(): fig = plt.figure() times = [date.datetime(2020, 1, 1, 12, 00), date.datetime(2020, 1, 2, 12, 00)] line = [2, 2] upper = [3, 4] lower = [1, 0] plt.plot(times, line) plt.fill_between(times, lower, upper) ax = plt.gca() ax.fmt_xdata = dates.DateFormatter("%d %b %Y %H:%M:%S...
def plot():
fig = plt.figure() times = [date.datetime(2020, 1, 1, 12, 00), date.datetime(2020, 1, 2, 12, 00)] line = [2, 2] upper = [3, 4] lower = [1, 0] plt.plot(times, line) plt.fill_between(times, lower, upper) ax = plt.gca() ax.fmt_xdata = dates.DateFormatter("%d %b %Y %H:%M:%S") retu...
import datetime as date import matplotlib.pyplot as plt from matplotlib import dates from helpers import assert_equality def plot():
26
64
127
3
22
dboeckenhoff/tikzplotlib
test/test_datetime_paths.py
Python
plot
plot
9
22
9
9
9c96dec56e1a473a88ddbc899a800e883a9941f1
bigcode/the-stack
train
bf797eb5bb7e55a712f7ad0c
train
function
def test(): assert_equality(plot, __file__[:-3] + "_reference.tex") return
def test():
assert_equality(plot, __file__[:-3] + "_reference.tex") return
] lower = [1, 0] plt.plot(times, line) plt.fill_between(times, lower, upper) ax = plt.gca() ax.fmt_xdata = dates.DateFormatter("%d %b %Y %H:%M:%S") return fig def test():
64
64
23
3
60
dboeckenhoff/tikzplotlib
test/test_datetime_paths.py
Python
test
test
25
27
25
25
11b9b1cf99a26e0435a23dbc1fe0dd113cda402f
bigcode/the-stack
train
4ea691c1db53277287ed5c85
train
class
class PlanExecutor: """ This is an interface between plan tree and execution tree. We traverse the plan tree and build execution tree from it Arguments: plan (AbstractPlan): Physical plan tree which needs to be executed """ def __init__(self, plan: AbstractPlan): self._plan = ...
class PlanExecutor:
""" This is an interface between plan tree and execution tree. We traverse the plan tree and build execution tree from it Arguments: plan (AbstractPlan): Physical plan tree which needs to be executed """ def __init__(self, plan: AbstractPlan): self._plan = plan def _build...
to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import pandas as pd from src.executor.abstract_e...
169
169
564
4
164
gaurav274/Eva
src/executor/plan_executor.py
Python
PlanExecutor
PlanExecutor
30
112
30
30
2cc0f8f9f4f863dcef7f8ebb816dfb1fe9f808de
bigcode/the-stack
train
6c911125a6a68e831d8f259b
train
class
class CaffeNet_caffe(Model): """CaffeNet (AlexNet variant included in Caffe) CaffeNet is a slight variant on AlexNet, described here: https://github.com/BVLC/caffe/tree/master/models/bvlc_reference_caffenet """ model_path = 'gs://modelzoo/vision/caffe_models/CaffeNet.pb' labels_path = 'gs://modelzoo/labe...
class CaffeNet_caffe(Model):
"""CaffeNet (AlexNet variant included in Caffe) CaffeNet is a slight variant on AlexNet, described here: https://github.com/BVLC/caffe/tree/master/models/bvlc_reference_caffenet """ model_path = 'gs://modelzoo/vision/caffe_models/CaffeNet.pb' labels_path = 'gs://modelzoo/labels/ImageNet_standard.txt' s...
the specific language governing permissions and # limitations under the License. # ============================================================================== from __future__ import absolute_import, division, print_function from lucid.modelzoo.vision_base import Model, _layers_from_list_of_dicts, IMAGENET_MEAN_BGR...
64
64
174
8
55
gabgoh/lucid
lucid/modelzoo/caffe_models/others.py
Python
CaffeNet_caffe
CaffeNet_caffe
19
33
19
19
2d96c736bb5c2333889b2150e6a93bcd1da17b2f
bigcode/the-stack
train
ca66b7cadce47b3e2e7a1f4f
train
class
class VGG19_caffe(Model): """VGG16 model used in ImageNet ILSVRC-2014, ported from caffe. VGG19 was introduced by Simonyan & Zisserman (2014): https://arxiv.org/pdf/1409.1556.pdf http://www.robots.ox.ac.uk/~vgg/research/very_deep/ as the Oxford Visual Geometry Group's submission for the ImageNet ILSVRC-2014 ...
class VGG19_caffe(Model):
"""VGG16 model used in ImageNet ILSVRC-2014, ported from caffe. VGG19 was introduced by Simonyan & Zisserman (2014): https://arxiv.org/pdf/1409.1556.pdf http://www.robots.ox.ac.uk/~vgg/research/very_deep/ as the Oxford Visual Geometry Group's submission for the ImageNet ILSVRC-2014 contest. We download the...
512}, {'tags': ['dense'], 'name': 'fc6/fc6', 'depth': 4096}, {'tags': ['dense'], 'name': 'fc7/fc7', 'depth': 4096}, {'tags': ['dense'], 'name': 'prob', 'depth': 1000}, ]) class VGG19_caffe(Model):
80
80
269
8
72
gabgoh/lucid
lucid/modelzoo/caffe_models/others.py
Python
VGG19_caffe
VGG19_caffe
84
102
84
84
e0ccce271779daee148f59754373ac23bc2b592f
bigcode/the-stack
train
eaea10e90271d5c8f889b10e
train
class
class VGG16_caffe(Model): """VGG16 model used in ImageNet ILSVRC-2014, ported from caffe. VGG16 was introduced by Simonyan & Zisserman (2014): https://arxiv.org/pdf/1409.1556.pdf http://www.robots.ox.ac.uk/~vgg/research/very_deep/ as the Oxford Visual Geometry Group's submission for the ImageNet ILSVRC-2014 ...
class VGG16_caffe(Model):
"""VGG16 model used in ImageNet ILSVRC-2014, ported from caffe. VGG16 was introduced by Simonyan & Zisserman (2014): https://arxiv.org/pdf/1409.1556.pdf http://www.robots.ox.ac.uk/~vgg/research/very_deep/ as the Oxford Visual Geometry Group's submission for the ImageNet ILSVRC-2014 contest. We download the...
, {'tags': ['dense'], 'name': 'fc6/fc6', 'depth': 4096} , {'tags': ['dense'], 'name': 'fc7/fc7', 'depth': 4096} , {'tags': ['dense'], 'name': 'prob', 'depth': 1000} , ]) class VGG16_caffe(Model):
81
81
270
8
73
gabgoh/lucid
lucid/modelzoo/caffe_models/others.py
Python
VGG16_caffe
VGG16_caffe
44
62
44
44
748fc7208d6e4e339be169e0c5dd588a4bcb433f
bigcode/the-stack
train
56939e4298d995a9b54dc333
train
function
def request_data_type(request): """ Check if either a file or text was provided to be proccessed. """ req_data = request.get_json() if 'file' in request.files: return 'file' elif 'text' in req_data: return 'text' else: return 'false'
def request_data_type(request):
""" Check if either a file or text was provided to be proccessed. """ req_data = request.get_json() if 'file' in request.files: return 'file' elif 'text' in req_data: return 'text' else: return 'false'
return filepath # TODO need to return an array of paths. return filepath # function to check the file extension def allowed_file_type(filename): return '.' in filename and \ filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS def request_data_type(request):
64
64
71
6
57
akempler/spaceract
app/filemgmnt.py
Python
request_data_type
request_data_type
57
69
57
57
e3440b6ea5cf4923cb7d20b4b7f3426d3f61987c
bigcode/the-stack
train
b1a6823bf6529a9e350cd1ea
train
function
def allowed_file_type(filename): return '.' in filename and \ filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
def allowed_file_type(filename):
return '.' in filename and \ filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
print(filename, flush=True) print(filepath, flush=True) pages[i].save(filepath) # for now returning first page until TODO below. return filepath # TODO need to return an array of paths. return filepath # function to check the file extension def allowed_f...
64
64
31
6
57
akempler/spaceract
app/filemgmnt.py
Python
allowed_file_type
allowed_file_type
53
55
53
53
ead9a7de83a8b6ce2ed3c8f61bd0088b07e97186
bigcode/the-stack
train
bef3ef5e6e094ee9859c2c2d
train
function
def upload_file(request): """ Handle the upload a file. Can be an image or pdf. """ if request.method == 'POST': # if 'file' not in request.files: # return jsonify(error='No file provided with key of "file" found') file = request.files['file'] if file.filename == '': r...
def upload_file(request):
""" Handle the upload a file. Can be an image or pdf. """ if request.method == 'POST': # if 'file' not in request.files: # return jsonify(error='No file provided with key of "file" found') file = request.files['file'] if file.filename == '': return jsonify(error='No fil...
import sys import pdf2image bp = Blueprint('filemgmnt', __name__) UPLOAD_FOLDER = './uploads' # 10485760 bytes = 10.48576mb MAX_CONTENT_LENGTH = 10 * 1024 * 1024 ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'pdf']) def upload_file(request):
79
80
267
5
74
akempler/spaceract
app/filemgmnt.py
Python
upload_file
upload_file
15
49
15
15
aac26e34f3e3ae3217e6e427fc4e62d3315f9541
bigcode/the-stack
train
ba7c08703fbf2f431d89dfb5
train
class
class photos(models.Model): smallphoto =models.CharField(max_length=1000) bigphoto =models.CharField(max_length=1000)
class photos(models.Model):
smallphoto =models.CharField(max_length=1000) bigphoto =models.CharField(max_length=1000)
from django.db import models from django.utils import timezone from django.utils.translation import gettext_lazy as _ from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager class photos(models.Model):
43
64
31
5
37
w60083/SocialNetworkAPI
User/models.py
Python
photos
photos
7
9
7
7
2f5a768847c061f8020caf2c6322c1a0566c7a0e
bigcode/the-stack
train
e8cf2d6020a8a5bf355cf783
train
class
class CustomAccountManager(BaseUserManager): def create_superuser(self, email, user_name, password, **other_fields): other_fields.setdefault('is_staff', True) other_fields.setdefault('is_superuser', True) other_fields.setdefault('is_active', True) if other_fields.get('is_staff') i...
class CustomAccountManager(BaseUserManager):
def create_superuser(self, email, user_name, password, **other_fields): other_fields.setdefault('is_staff', True) other_fields.setdefault('is_superuser', True) other_fields.setdefault('is_active', True) if other_fields.get('is_staff') is not True: raise ValueError( ...
models here. # class User(models.Model): # name= models.CharField(max_length=50) # status = models.CharField(max_length=50,blank=True) # photos = models.OneToOneField(photos, on_delete=models.CASCADE,blank=True) class CustomAccountManager(BaseUserManager):
64
64
209
8
56
w60083/SocialNetworkAPI
User/models.py
Python
CustomAccountManager
CustomAccountManager
17
44
17
18
c726c0077e76c28ffebf7ce9f01619c3f65c20cc
bigcode/the-stack
train
7e88b34b6de775e0876901fd
train
class
class NewUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) user_name = models.CharField(max_length=150, unique=True) first_name = models.CharField(max_length=150, blank=True) start_date = models.DateTimeField(default=timezone.now) photos = models.O...
class NewUser(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(_('email address'), unique=True) user_name = models.CharField(max_length=150, unique=True) first_name = models.CharField(max_length=150, blank=True) start_date = models.DateTimeField(default=timezone.now) photos = models.OneToOneField(photos, on_delete=models.CASCADE, blank...
email: raise ValueError(_('You must provide an email address')) email = self.normalize_email(email) user = self.model(email=email, user_name=user_name, **other_fields) user.set_password(password) user.save() return user class NewUser(Abstra...
64
64
163
10
53
w60083/SocialNetworkAPI
User/models.py
Python
NewUser
NewUser
46
64
46
47
2b5d6185d07d4cd81802d53bf5dc51a0ee957497
bigcode/the-stack
train
4f5ff568719fc46d6a39211d
train
class
class DataReader: storage: Dict[str, List[Tuple[str, float]]] weights: Dict[str, float] goal: Optional[float] current: Optional[float] contents: List[List[str]] def __init__(self, filename: str) -> None: """ Initializer """ self.filename = filename self.weights = {} ...
class DataReader:
storage: Dict[str, List[Tuple[str, float]]] weights: Dict[str, float] goal: Optional[float] current: Optional[float] contents: List[List[str]] def __init__(self, filename: str) -> None: """ Initializer """ self.filename = filename self.weights = {} self.storage =...
from __future__ import annotations from typing import List, Dict, Tuple, Optional import json from src.Backend.DataObject import DataObject DESCRIPTION = 'DESCRIPTION' CURRENT_MARK = "CURRENT MARK" GOAL = 'GOAL' NON_DATA_VALUES = [DESCRIPTION, CURRENT_MARK, GOAL] class DataReader:
67
80
268
4
63
TheMatthewDu/Mark_Book
src/Backend/DataReader.py
Python
DataReader
DataReader
13
50
13
13
c8d2f22911147d1ebb95ad8aed506ad37118e8dc
bigcode/the-stack
train
8332fa104558e22895a31bbd
train
class
class LifeEventServiceClient(metaclass=LifeEventServiceClientMeta): """Service to fetch Google Ads Life Events.""" @staticmethod def _get_default_mtls_endpoint(api_endpoint): """Convert api endpoint to mTLS endpoint. Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to "*.mt...
class LifeEventServiceClient(metaclass=LifeEventServiceClientMeta):
"""Service to fetch Google Ads Life Events.""" @staticmethod def _get_default_mtls_endpoint(api_endpoint): """Convert api endpoint to mTLS endpoint. Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively....
_CLIENT_INFO from .transports.grpc import LifeEventServiceGrpcTransport class LifeEventServiceClientMeta(type): """Metaclass for the LifeEventService client. This provides class-level methods for building and retrieving support objects (e.g. transport) without polluting the client instance objects. ...
255
256
2,961
15
240
wxxlouisa/google-ads-python
google/ads/googleads/v8/services/services/life_event_service/client.py
Python
LifeEventServiceClient
LifeEventServiceClient
72
426
72
72
a1ccfd0979ab8c65acc4af541f72fb770bc9797c
bigcode/the-stack
train
9844f911c338670ffb86c351
train
class
class LifeEventServiceClientMeta(type): """Metaclass for the LifeEventService client. This provides class-level methods for building and retrieving support objects (e.g. transport) without polluting the client instance objects. """ _transport_registry = ( OrderedDict() ) # type: D...
class LifeEventServiceClientMeta(type):
"""Metaclass for the LifeEventService client. This provides class-level methods for building and retrieving support objects (e.g. transport) without polluting the client instance objects. """ _transport_registry = ( OrderedDict() ) # type: Dict[str, Type[LifeEventServiceTransport]...
# type: ignore from google.ads.googleads.v8.resources.types import life_event from google.ads.googleads.v8.services.types import life_event_service from .transports.base import LifeEventServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import LifeEventServiceGrpcTransport class LifeEventServiceClientMeta(ty...
67
67
225
8
58
wxxlouisa/google-ads-python
google/ads/googleads/v8/services/services/life_event_service/client.py
Python
LifeEventServiceClientMeta
LifeEventServiceClientMeta
38
69
38
38
e6db78e92920a309051737db6d24144814988cba
bigcode/the-stack
train
ac076b5c54c99c0ac6012518
train
function
async def test_get_components(jp_fetch): # Ensure all valid components can be found response = await jp_fetch('elyra', 'pipeline', 'components', 'local') assert response.code == 200 payload = json.loads(response.body.decode()) palette = json.loads(pkg_resources.read_text(resources, 'palette.json')) ...
async def test_get_components(jp_fetch): # Ensure all valid components can be found
response = await jp_fetch('elyra', 'pipeline', 'components', 'local') assert response.code == 200 payload = json.loads(response.body.decode()) palette = json.loads(pkg_resources.read_text(resources, 'palette.json')) assert payload == palette
with pytest.raises(HTTPClientError) as e: # await jp_fetch('elyra', 'pipeline', 'config', 'invalid', method='GET') # # assert expected_http_error(e, 400) async def test_get_components(jp_fetch): # Ensure all valid components can be found
64
64
76
19
45
deepti-mahesh/elyra
elyra/pipeline/tests/test_handlers.py
Python
test_get_components
test_get_components
52
58
52
53
ba88e548bcce9f1c28e834f6dfd2dae2a229fdd9
bigcode/the-stack
train
a276402d2a542d11c5f68243
train
function
async def test_get_component_properties_config(jp_fetch): # Ensure all valid component_entry properties can be found response = await jp_fetch('elyra', 'pipeline', 'components', 'local', 'notebooks', 'properties') assert response.code == 200 payload = json.loads(response.body.decode()) properties = ...
async def test_get_component_properties_config(jp_fetch): # Ensure all valid component_entry properties can be found
response = await jp_fetch('elyra', 'pipeline', 'components', 'local', 'notebooks', 'properties') assert response.code == 200 payload = json.loads(response.body.decode()) properties = json.loads(pkg_resources.read_text(resources, 'properties.json')) assert payload == properties
'local') assert response.code == 200 payload = json.loads(response.body.decode()) palette = json.loads(pkg_resources.read_text(resources, 'palette.json')) assert payload == palette async def test_get_component_properties_config(jp_fetch): # Ensure all valid component_entry properties can be found
64
64
87
23
40
deepti-mahesh/elyra
elyra/pipeline/tests/test_handlers.py
Python
test_get_component_properties_config
test_get_component_properties_config
61
67
61
62
a1e914b779b42325fa3a4d15d8ba8bc925de150c
bigcode/the-stack
train
9cc44864c0a15b54ee401360
train
function
@pytest.fixture def jp_server_config(): return { "ServerApp": { "jpserver_extensions": { "elyra": True } } }
@pytest.fixture def jp_server_config():
return { "ServerApp": { "jpserver_extensions": { "elyra": True } } }
import importlib.resources as pkg_resources except ImportError: # Try backported to PY<37 `importlib_resources`. import importlib_resources as pkg_resources # Set Elyra server extension as enabled (overriding server_config fixture from jupyter_server) @pytest.fixture def jp_server_config():
64
64
37
8
56
deepti-mahesh/elyra
elyra/pipeline/tests/test_handlers.py
Python
jp_server_config
jp_server_config
34
42
34
35
02f8a5b762b2d6298b8fa2d4210a04c18b244354
bigcode/the-stack
train
eb0f6d87d61826f58df15d9f
train
class
class HubUser(Document): pass
class HubUser(Document):
pass
# -*- coding: utf-8 -*- # Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe.model.document import Document class HubUser(Document):
61
64
7
5
55
Mindhome/field_service
mindhome_alpha/erpnext/hub_node/doctype/hub_user/hub_user.py
Python
HubUser
HubUser
9
10
9
9
de0cdcb00abd77a5cf5f6bb51dda54373018e6a7
bigcode/the-stack
train
92e6f5c8b0da84bbeca4fe1f
train
function
def worker_func(model_cls, model_kwargs, checkpoint, dataset, data_func, gpu_id, idx_queue, result_queue): """worker function Args: model_cls (type): Model class type. model_kwargs (dict): Arguments to init the model. checkpoint (str): Checkpoint filepath. datase...
def worker_func(model_cls, model_kwargs, checkpoint, dataset, data_func, gpu_id, idx_queue, result_queue):
"""worker function Args: model_cls (type): Model class type. model_kwargs (dict): Arguments to init the model. checkpoint (str): Checkpoint filepath. dataset (:obj:`Dataset`): The dataset to be tested. data_func (callable): The function that generates model inputs. ...
"""parallel test""" import multiprocessing import mmcv import paddle from codes.utils import load_checkpoint def worker_func(model_cls, model_kwargs, checkpoint, dataset, data_func, gpu_id, idx_queue, result_queue):
47
64
208
26
20
ImportPaddle/MVFNet-Paddle
codes/core/evaluation/parallel_test.py
Python
worker_func
worker_func
10
34
10
11
463f7a1c0bfbd16c8c87480adf209175a5ffc95f
bigcode/the-stack
train
1708d1ad89068731a546f28a
train
function
def parallel_test(model_cls, model_kwargs, checkpoint, dataset, data_func, gpus, workers_per_gpu=1): """Parallel testing on multiple GPUs. only for len(data) % num_gpus == 0 Args: model_cls ...
def parallel_test(model_cls, model_kwargs, checkpoint, dataset, data_func, gpus, workers_per_gpu=1):
"""Parallel testing on multiple GPUs. only for len(data) % num_gpus == 0 Args: model_cls (type): Model class type. model_kwargs (dict): Arguments to init the model. checkpoint (str): Checkpoint filepath. dataset (:obj:`Dataset`): The dataset to be tested. data_func ...
load_checkpoint(model, checkpoint, map_location='cpu') paddle.device.set_device('gpu:'.format(gpu_id)) model.cuda() model.eval() with paddle.no_grad(): while True: idx = idx_queue.get() data = dataset[idx] result = model(**data_func(data, gpu_id)) ...
108
108
363
31
77
ImportPaddle/MVFNet-Paddle
codes/core/evaluation/parallel_test.py
Python
parallel_test
parallel_test
37
88
37
43
4b96e7cd28f58c524d1280dfd7f554008256be47
bigcode/the-stack
train
20ea3b8785b56da178a918a6
train
class
class FactoryTestCase(unittest.TestCase): def test_raise_error_if_not_key(self): with self.assertRaises(MissingKey): b64_factory(None) def test_raise_error_if_key_is_invalid(self): with self.assertRaises(InvalidKey): b64_factory('1010:ABAB') def test_generate_b64_o...
class FactoryTestCase(unittest.TestCase):
def test_raise_error_if_not_key(self): with self.assertRaises(MissingKey): b64_factory(None) def test_raise_error_if_key_is_invalid(self): with self.assertRaises(InvalidKey): b64_factory('1010:ABAB') def test_generate_b64_object_with_a_valid_key(self): heade...
import unittest from os import environ from pyrecard.exceptions import MissingKey, InvalidKey from pyrecard.utils.factory import b64_factory, header_factory class FactoryTestCase(unittest.TestCase):
42
94
316
8
33
DiegoMagg/pyrecard
tests/factory_tests.py
Python
FactoryTestCase
FactoryTestCase
7
43
7
8
dae61b016b5ec3f319be4935ead4caa4f2eaf64d
bigcode/the-stack
train
2a5565e44ad089c6a999c0e1
train
class
class Client(BaseClient): # We choose to implement all 4 grants in 1 class """This is the main API for oauth2 client. Its methods define and document parameters mentioned in OAUTH2 RFC 6749. """ DEVICE_FLOW = { # consts for device flow, that can be customized by sub-class "GRANT_TYPE": "urn:i...
class Client(BaseClient): # We choose to implement all 4 grants in 1 class
"""This is the main API for oauth2 client. Its methods define and document parameters mentioned in OAUTH2 RFC 6749. """ DEVICE_FLOW = { # consts for device flow, that can be customized by sub-class "GRANT_TYPE": "urn:ietf:params:oauth:grant-type:device_code", "DEVICE_CODE": "device_cod...
even an error response will be a valid json structure, # so we simply return it here, without needing to invent an exception. return resp.json() except ValueError: self.logger.exception( "Token response is not in json format: %s", resp.text) r...
256
256
3,145
20
235
dsanghan/microsoft-authentication-library-for-python
msal/oauth2cli/oauth2.py
Python
Client
Client
183
462
183
183
9739610ffd6268c382e389ba3aaffee17733f5d1
bigcode/the-stack
train
c880825b431b32ae9e21856d
train
class
class BaseClient(object): # This low-level interface works. Yet you'll find its sub-class # more friendly to remind you what parameters are needed in each scenario. # More on Client Types at https://tools.ietf.org/html/rfc6749#section-2.1 @staticmethod def encode_saml_assertion(assertion): ...
class BaseClient(object): # This low-level interface works. Yet you'll find its sub-class # more friendly to remind you what parameters are needed in each scenario. # More on Client Types at https://tools.ietf.org/html/rfc6749#section-2.1 @staticmethod
def encode_saml_assertion(assertion): return base64.urlsafe_b64encode(assertion).rstrip(b'=') # Per RFC 7522 CLIENT_ASSERTION_TYPE_JWT = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer" CLIENT_ASSERTION_TYPE_SAML2 = "urn:ietf:params:oauth:client-assertion-type:saml2-bearer" client_asse...
"""This OAuth2 client implementation aims to be spec-compliant, and generic.""" # OAuth2 spec https://tools.ietf.org/html/rfc6749 try: from urllib.parse import urlencode, parse_qs except ImportError: from urlparse import parse_qs from urllib import urlencode import logging import warnings import time impor...
144
256
1,871
64
79
dsanghan/microsoft-authentication-library-for-python
msal/oauth2cli/oauth2.py
Python
BaseClient
BaseClient
18
180
18
23
ec6eedff0b16a52b70beb438fb496377c2c68634
bigcode/the-stack
train
0ce9131bfde9f23b8989cdbb
train
class
class ReindexTest(MonicoinTestFramework): def set_test_params(self): self.setup_clean_chain = True self.num_nodes = 1 def reindex(self, justchainstate=False): self.nodes[0].generatetoaddress(3, self.nodes[0].get_deterministic_priv_key().address) blockcount = self.nodes[0].getblo...
class ReindexTest(MonicoinTestFramework):
def set_test_params(self): self.setup_clean_chain = True self.num_nodes = 1 def reindex(self, justchainstate=False): self.nodes[0].generatetoaddress(3, self.nodes[0].get_deterministic_priv_key().address) blockcount = self.nodes[0].getblockcount() self.stop_nodes() ...
up to block 3. - Stop the node and restart it with -reindex-chainstate. Verify that the node has reindexed up to block 3. """ from test_framework.test_framework import MonicoinTestFramework from test_framework.util import assert_equal class ReindexTest(MonicoinTestFramework):
64
64
179
10
53
karbonbaron/monicoin
test/functional/feature_reindex.py
Python
ReindexTest
ReindexTest
16
34
16
16
b8163e272ce6cd547d3b2c02454fd7dd1619daa3
bigcode/the-stack
train
642cff1069c1040f52024333
train
function
def test_keyboard_node(): with pytest.raises(ValueError): KeyboardNode(title="title", text="text", buttons=[]) titles = ("one", "two", "three") buttons = [FillerNode(title) for title in titles] node = KeyboardNode(title="title", text="text", buttons=buttons) assert node.title == "title" ...
def test_keyboard_node():
with pytest.raises(ValueError): KeyboardNode(title="title", text="text", buttons=[]) titles = ("one", "two", "three") buttons = [FillerNode(title) for title in titles] node = KeyboardNode(title="title", text="text", buttons=buttons) assert node.title == "title" assert node.text == "tex...
number number += 1 return str(number) node = FuncNode(title="title", text_func=text_func) assert node.title == "title" assert node.text == "1" assert node.text == "2" assert node.text == "3" def test_keyboard_node():
64
64
114
5
59
Masynchin/textode
tests/test_nodes.py
Python
test_keyboard_node
test_keyboard_node
41
54
41
41
72b72fd6eb1ee75386baeea11e3be7f68d19097d
bigcode/the-stack
train
ffe13c2192dba8861bd3b2f5
train
function
def test_text_node(): node = TextNode(title="title", text="text") assert node.title == "title" assert node.text == "text"
def test_text_node():
node = TextNode(title="title", text="text") assert node.title == "title" assert node.text == "text"
import pytest from textode.constants import TO_MAIN from textode.nodes import ( BackNode, FillerNode, FuncNode, ImageNode, KeyboardNode, TextNode, ) def test_text_node():
48
64
34
5
43
Masynchin/textode
tests/test_nodes.py
Python
test_text_node
test_text_node
14
17
14
14
4d586eb55b9db73da5b844e5b85efb97265ccb82
bigcode/the-stack
train
72f99862f4359c3532b3615a
train
function
def test_image_node(): image_node = ImageNode(title="title", path="image.png", caption="caption") assert image_node.title == "title" assert image_node.caption == "caption" assert image_node.path == "image.png" without_caption = ImageNode(title="title", path="image.png") assert without_caption.c...
def test_image_node():
image_node = ImageNode(title="title", path="image.png", caption="caption") assert image_node.title == "title" assert image_node.caption == "caption" assert image_node.path == "image.png" without_caption = ImageNode(title="title", path="image.png") assert without_caption.caption is None
nested_keyboard = KeyboardNode( title="title", text="text", buttons=[back_node] ) main_keyboard = KeyboardNode( title="title", text="text", buttons=[nested_keyboard] ) assert back_node.get_node_to_back() == main_keyboard def test_image_node():
64
64
75
5
58
Masynchin/textode
tests/test_nodes.py
Python
test_image_node
test_image_node
72
79
72
72
90386a3529efdb6bf3834228247c222c1bd92f68
bigcode/the-stack
train
11f7cf3fa0494ba09bd73e68
train
function
def test_func_node(): number = 0 def text_func(): nonlocal number number += 1 return str(number) node = FuncNode(title="title", text_func=text_func) assert node.title == "title" assert node.text == "1" assert node.text == "2" assert node.text == "3"
def test_func_node():
number = 0 def text_func(): nonlocal number number += 1 return str(number) node = FuncNode(title="title", text_func=text_func) assert node.title == "title" assert node.text == "1" assert node.text == "2" assert node.text == "3"
= TextNode(title="title", text="text") assert node.title == "title" assert node.text == "text" def test_filler_node(): node = FillerNode("both_title_and_text") assert node.title == node.text == "both_title_and_text" def test_func_node():
64
64
78
5
59
Masynchin/textode
tests/test_nodes.py
Python
test_func_node
test_func_node
25
38
25
25
d764842e1bc6dec124aa72d6c6d014aa9831ca17
bigcode/the-stack
train