source
string
points
list
n_points
int64
path
string
repo
string
import pyglet class Resources: # --- Player Parameters --- player_animation_started = False player_images = [] player_animation_time = 1. / 9. player_animation_index = 0 # --- Obstacle Parameters --- obstacle_images = [] # --- Player Methods --- # loads the images needed for the player animation if they haven't been loaded already @staticmethod def load_images(): if len(Resources.player_images) == 0: Resources.player_images.append(pyglet.image.load("res/dinosaur_left.png")) Resources.player_images.append(pyglet.image.load("res/dinosaur_right.png")) Resources.player_images.append(pyglet.image.load("res/dinosaur_normal.png")) if len(Resources.obstacle_images) == 0: Resources.obstacle_images.append(pyglet.image.load("res/cactus_small.png")) Resources.obstacle_images.append(pyglet.image.load("res/cactus_big.png")) Resources.start_player_animation() # starts the player's running animation by scheduling recurring updates to the player's image index @staticmethod def start_player_animation(): if not Resources.player_animation_started: pyglet.clock.schedule_interval(Resources.trigger_player_update, Resources.player_animation_time) Resources.player_animation_started = True # updates the player's image index @staticmethod def trigger_player_update(_): Resources.player_animation_index = 1 - Resources.player_animation_index # returns the current image for the running player @staticmethod def player_running_image(): return Resources.player_images[Resources.player_animation_index] # returns the image for the jumping player @staticmethod def player_jumping_image(): return Resources.player_images[2]
[ { "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
src/dinosaur/game/resources.py
lukDev/dinosaur
""" pangocffi.ffi_instance_builder ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ generates an FFI for pangocffi """ from pathlib import Path from cffi import FFI from typing import Optional class FFIInstanceBuilder: def __init__(self, source: Optional[str] = None): self.source = source def generate(self) -> FFI: # Read the C definitions c_definitions_glib_file = open( str(Path(__file__).parent / 'c_definitions_glib.txt'), 'r' ) c_definitions_pango_file = open( str(Path(__file__).parent / 'c_definitions_pango.txt'), 'r' ) c_definitions_glib = c_definitions_glib_file.read() c_definitions_pango = c_definitions_pango_file.read() ffi = FFI() ffi.cdef(c_definitions_glib) ffi.cdef(c_definitions_pango) if self.source is not None: ffi.set_source(self.source, None) return ffi
[ { "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
env/Lib/site-packages/pangocffi/ffi_instance_builder.py
kodelaben/manimce
from django.contrib.auth.models import BaseUserManager class UserManager(BaseUserManager): def create_user(self, email, password=None, **kwargs): """ Creates and saves a User with the given email and password. """ if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), **kwargs ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password, **kwargs): """ Creates and saves a superuser with the given email and password. """ user = self.create_user( email, password=password, **kwargs ) user.is_staff = True user.is_superuser = True user.save(using=self._db) return user def active(self): return self.get_queryset().filter(is_active=True, is_verified=True)
[ { "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": "more_functions_than_classes", "question": "Does this file define more functions than cla...
3
libdrf/login/managers.py
lumiqa/libdrf
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from typing import Any, Optional from azure.core import AsyncPipelineClient from msrest import Deserializer, Serializer from ._configuration import AutoRestSwaggerBATArrayServiceConfiguration from .operations import ArrayOperations from .. import models class AutoRestSwaggerBATArrayService(object): """Test Infrastructure for AutoRest Swagger BAT. :ivar array: ArrayOperations operations :vartype array: vanilla.body.array.aio.operations.ArrayOperations :param str base_url: Service URL """ def __init__( self, base_url: Optional[str] = None, **kwargs: Any ) -> None: if not base_url: base_url = 'http://localhost:3000' self._config = AutoRestSwaggerBATArrayServiceConfiguration(**kwargs) self._client = AsyncPipelineClient(base_url=base_url, config=self._config, **kwargs) client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) self._serialize.client_side_validation = False self._deserialize = Deserializer(client_models) self.array = ArrayOperations( self._client, self._config, self._serialize, self._deserialize) async def close(self) -> None: await self._client.close() async def __aenter__(self) -> "AutoRestSwaggerBATArrayService": await self._client.__aenter__() return self async def __aexit__(self, *exc_details) -> None: await self._client.__aexit__(*exc_details)
[ { "point_num": 1, "id": "all_return_types_annotated", "question": "Does every function in this file have a return type annotation?", "answer": true }, { "point_num": 2, "id": "more_functions_than_classes", "question": "Does this file define more functions than classes?", "answer"...
3
test/vanilla/Expected/AcceptanceTests/BodyArrayWithNamespaceFolders/vanilla/body/array/aio/_auto_rest_swagger_bat_array_service.py
tasherif-msft/autorest.python
# ---------------------------------------------------------------------- # # Brad T. Aagaard, U.S. Geological Survey # Charles A. Williams, GNS Science # Matthew G. Knepley, University at Buffalo # # This code was developed as part of the Computational Infrastructure # for Geodynamics (http://geodynamics.org). # # Copyright (c) 2010-2021 University of California, Davis # # See LICENSE.md for license information. # # ---------------------------------------------------------------------- # # @file pylith/topology/Field.py # # @brief Python object for managing a vector field over vertices or # cells of a finite-element mesh. from .topology import Field as ModuleField class Field(ModuleField): """Python object for managing a vector field over vertices or cells of a finite-element mesh. """ # PUBLIC METHODS ///////////////////////////////////////////////////// def __init__(self, mesh): """Constructor. """ ModuleField.__init__(self, mesh) return def cleanup(self): """Deallocate PETSc and local data structures. """ self.deallocate() return # End of file
[ { "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
pylith/topology/Field.py
cehanagan/pylith
import random from flask import ( Flask, render_template, jsonify ) app = Flask(__name__) @app.get('/') def index(): return render_template('index.html.j2') @app.get('/api') def api(): return jsonify({'lucky': random.randrange(1, 100)}) application = app
[ { "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
tests/hybrid/flaskapp/application.py
tdesposito/DevPail
""" Test for issue 51: https://github.com/pandas-profiling/pandas-profiling/issues/51 """ from pathlib import Path import pandas as pd import pandas_profiling import requests import numpy as np def test_issue51(get_data_file): # Categorical has empty ('') value file_name = get_data_file( "buggy1.pkl", "https://raw.githubusercontent.com/adamrossnelson/HelloWorld/master/sparefiles/buggy1.pkl", ) df = pd.read_pickle(str(file_name)) report = df.profile_report(title="Pandas Profiling Report") assert ( "<title>Pandas Profiling Report</title>" in report.to_html() ), "Profile report should be generated." def test_issue51_similar(): df = pd.DataFrame( { "test": ["", "hoi", None], "blest": [None, "", "geert"], "bert": ["snor", "", None], } ) report = df.profile_report(title="Pandas Profiling Report") assert ( "<title>Pandas Profiling Report</title>" in report.to_html() ), "Profile report should be generated." # def test_issue51_mixed(): # df = pd.DataFrame( # { # "test": ["", "hoi", None, "friet"], # "blest": [None, "", "geert", "pizza"], # "bert": ["snor", "", np.nan, ""], # "fruit": ["", "ok", np.nan, ""], # } # ) # report = df.profile_report(title="Pandas Profiling Report") # assert ( # "data-toggle=tab>Recoded</a>" in report.to_html() # ), "Recoded should be present" def test_issue51_empty(): df = pd.DataFrame( {"test": ["", "", ""], "blest": ["", "", ""], "bert": ["", "", ""]} ) report = df.profile_report(title="Pandas Profiling Report") assert ( "<title>Pandas Profiling Report</title>" in report.to_html() ), "Profile report should be generated."
[ { "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
tests/issues/test_issue51.py
javiergodoy/pandas-profiling
# -*- coding: utf-8 -*- from pprint import pprint from scrapy.spiders import SitemapSpider class HuluSitemap(SitemapSpider): name = 'hulu_sitemap' allowed_domains = ['hulu.com'] sitemap_urls = ['https://www.hulu.com/sitemap_index.xml'] def sitemap_filter(self, entries): for entry in entries: if 'hulu.com/series/' in entry['loc']: yield entry def parse(self, response): # response.selector.remove_namespaces() return response.xpath('//*')
[ { "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
tv_guide/tv_guide/spiders/hulu.py
bd/tv_tracker
import pygame def scale_image(img, factor): size = round(img.get_width() * factor), round(img.get_height() * factor) return pygame.transform.scale(img, size) def blit_rotate_center(win, image, top_left, angle): rotated_image = pygame.transform.rotate(image, angle) new_rect = rotated_image.get_rect( center=image.get_rect(topleft=top_left).center) win.blit(rotated_image, new_rect.topleft) def blit_text_center(win, font, text): render = font.render(text, 1, (200, 200, 200)) win.blit(render, (win.get_width()/2 - render.get_width() / 2, win.get_height()/2 - render.get_height()/2))
[ { "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_params_annotated", "question": "Does every function parameter in this file have a type annotation (excluding se...
3
sakthiRaceGameFiles/utils.py
sakthiRathinam/sakthiRaceGame
from django.test import Client, TestCase from django.contrib.auth import get_user_model from django.urls import reverse class AdminSiteTests(TestCase): def setUp(self): self.client = Client() self.admin_user = get_user_model().objects.create_superuser( email='admin@danoscarmike.com', password='SillyPassword123' ) self.client.force_login(self.admin_user) self.user = get_user_model().objects.create_user( email='test@danoscarmike.com', password='ReallySillyPassword123', name='Dummy user' ) def test_users_listed(self): """Test that users are listed on user page""" url = reverse('admin:core_user_changelist') res = self.client.get(url) self.assertContains(res, self.user.name) self.assertContains(res, self.user.email) def test_user_change_page(self): """Test that the user edit page works""" url = reverse('admin:core_user_change', args=[self.user.id]) res = self.client.get(url) self.assertEqual(res.status_code, 200) def test_create_user_page(self): """Test that the create user page works""" url = reverse('admin:core_user_add') res = self.client.get(url) self.assertEqual(res.status_code, 200)
[ { "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
app/core/tests/test_admin.py
danoscarmike/recipe-app-api
def jeep(merk): print("Jeep merk "+ merk +" telah terbeli") def sedan(): print("Sedan telah terbeli")
[ { "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": "all_return_types_annotated", "question": "Does every function in this file have a return type annotation?...
3
9 Modul dan Package/Beli/Mobil.py
Rakhid16/pibiti-himatifa-2020
from typing import List, Set class ThroneInheritance: def __init__(self, kingName: str): self.names = [kingName] self.index = {kingName: 0} self.children: List[List[int]] = [[]] self.died: Set[int] = set() def birth(self, parentName: str, childName: str) -> None: iC = len(self.names) self.names.append(childName) self.index[childName] = iC self.children.append([]) iP = self.index[parentName] self.children[iP].append(iC) def death(self, name: str) -> None: i = self.index[name] self.died.add(i) def getInheritanceOrder(self) -> List[str]: opt: List[str] = [] stack = [0] while len(stack) > 0: i = stack.pop() stack += self.children[i][::-1] if i not in self.died: opt.append(self.names[i]) return opt # Your ThroneInheritance object will be instantiated and called as such: # obj = ThroneInheritance(kingName) # obj.birth(parentName,childName) # obj.death(name) # param_3 = obj.getInheritanceOrder()
[ { "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_function_names_snake_case", "question": "Are all function names in this file written in snake_case?", "answer"...
3
Algorithms/1600/stack.py
M-Quadra/LeetCode-problems
# init.py from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_login import LoginManager # init SQLAlchemy so we can use it later in our models db = SQLAlchemy() def create_app(): app = Flask(__name__) app.config['SECRET_KEY'] = '9OLWxND4o83j4K4iuopO' app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite' db.init_app(app) login_manager = LoginManager() login_manager.login_view = 'auth.login' login_manager.init_app(app) from .models import User @login_manager.user_loader def load_user(user_id): # since the user_id is just the primary key of our user table, use it in the query for the user return User.query.get(int(user_id)) # blueprint for auth routes in our app from .auth import auth as auth_blueprint app.register_blueprint(auth_blueprint) # blueprint for non-auth parts of app from .main import main as main_blueprint app.register_blueprint(main_blueprint) return app
[ { "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
__init__.py
Pratik2587/Medical-Cost-Predictor-
from dusk.script import * from dusk.transpile import callable_to_pyast, pyast_to_sir, validate def test_math(): validate(pyast_to_sir(callable_to_pyast(math_stencil))) @stencil def math_stencil(a: Field[Cell], b: Field[Cell], c: Field[Cell], d: Field[Cell]): with levels_upward: a = sqrt(b) b = exp(c) c = log(a) a = sin(b) b = cos(c) c = tan(a) a = arcsin(b) b = arccos(c) c = arctan(a) a = fabs(b) b = floor(c) c = ceil(a) a = isinf(b) b = isnan(c) a = max(b, c) d = min(a, b) c = pow(d, a) a = a + sqrt(b) + cos(c) a = max(min(b, c), d)
[ { "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": "all_params_annotated", "question": "Does every function parameter in this file have a type annotation (excluding s...
3
tests/stencils/test_math.py
Stagno/dusk
import nesmdb.vgm import nesmdb.score def seprsco_to_vgm(seprsco): exprsco = nesmdb.score.seprsco_to_exprsco(seprsco) rawsco = nesmdb.score.exprsco_to_rawsco(exprsco) ndf = nesmdb.score.rawsco_to_ndf(rawsco) ndr = nesmdb.vgm.ndf_to_ndr(ndf) vgm = nesmdb.vgm.ndr_to_vgm(ndr) return vgm def seprsco_to_wav(seprsco): exprsco = nesmdb.score.seprsco_to_exprsco(seprsco) rawsco = nesmdb.score.exprsco_to_rawsco(exprsco) ndf = nesmdb.score.rawsco_to_ndf(rawsco) ndr = nesmdb.vgm.ndf_to_ndr(ndf) vgm = nesmdb.vgm.ndr_to_vgm(ndr) wav = nesmdb.vgm.vgm_to_wav(vgm) return wav def blndsco_to_wav(blndsco): exprsco = nesmdb.score.blndsco_to_exprsco(blndsco) rawsco = nesmdb.score.exprsco_to_rawsco(exprsco) ndf = nesmdb.score.rawsco_to_ndf(rawsco) ndr = nesmdb.vgm.ndf_to_ndr(ndf) vgm = nesmdb.vgm.ndr_to_vgm(ndr) wav = nesmdb.vgm.vgm_to_wav(vgm) return wav
[ { "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
nesmdb/convert.py
youngmg1995/NES-Music-Maker
import math import torch from . import Sampler from torch.distributed import get_world_size, get_rank class DistributedSampler(Sampler): """Sampler that restricts data loading to a subset of the dataset. It is especially useful in conjunction with :class:`torch.nn.parallel.DistributedDataParallel`. In such case, each process can pass a DistributedSampler instance as a DataLoader sampler, and load a subset of the original dataset that is exclusive to it. .. note:: Dataset is assumed to be of constant size. Arguments: dataset: Dataset used for sampling. num_replicas (optional): Number of processes participating in distributed training. rank (optional): Rank of the current process within num_replicas. """ def __init__(self, dataset, num_replicas=None, rank=None): if num_replicas is None: num_replicas = get_world_size() if rank is None: rank = get_rank() self.dataset = dataset self.num_replicas = num_replicas self.rank = rank self.epoch = 0 self.num_samples = int(math.ceil(len(self.dataset) * 1.0 / self.num_replicas)) self.total_size = self.num_samples * self.num_replicas def __iter__(self): # deterministically shuffle based on epoch g = torch.Generator() g.manual_seed(self.epoch) indices = list(torch.randperm(len(self.dataset), generator=g)) # add extra samples to make it evenly divisible indices += indices[:(self.total_size - len(indices))] assert len(indices) == self.total_size # subsample offset = self.num_samples * self.rank indices = indices[offset:offset + self.num_samples] assert len(indices) == self.num_samples return iter(indices) def __len__(self): return self.num_samples def set_epoch(self, epoch): self.epoch = epoch
[ { "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": true ...
3
src/torch/utils/data/distributed.py
warcraft12321/Hyperfoods
from django.test import TestCase, Client from django.contrib.auth import get_user_model from django.urls import reverse class AdminSiteTests(TestCase): def setUp(self): self.client = Client() self.admin_user = get_user_model().objects.create_superuser( email='admin@test.fr', password='test123' ) self.client.force_login(self.admin_user) self.user = get_user_model().objects.create_user( email='test@test.fr', password='test123', name='Test user full name', ) def test_users_listed(self): """Test that users are listed on userpage""" url = reverse('admin:core_user_changelist') res = self.client.get(url) self.assertContains(res, self.user.name) self.assertContains(res, self.user.email) self.assertContains(res, self.admin_user.name) self.assertContains(res, self.admin_user.email) def test_user_change_page(self): """Test if the user page exists and works""" url = reverse("admin:core_user_change", args=[self.user.id]) res = self.client.get(url) self.assertEqual(res.status_code, 200) def test_create_user_page(self): """Test that the create user page works""" url = reverse('admin:core_user_add') res = self.client.get(url) self.assertEqual(res.status_code, 200)
[ { "point_num": 1, "id": "all_function_names_snake_case", "question": "Are all function names in this file written in snake_case?", "answer": false }, { "point_num": 2, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer"...
3
app/core/tests/test_admin.py
pshop/recipe-app-api
import numpy as np from model.indexer_v1 import Indexer class QueryAnalizer: def __init__(self, query, document_list, enable_stemming=True, filter_stopwords=True): self.__query = Indexer([query], enable_stemming=enable_stemming, filter_stopwords=filter_stopwords) self.__indexer = Indexer(document_list, enable_stemming=enable_stemming, filter_stopwords=filter_stopwords) self.result = None def cosine_similarity(self): if self.result is not None: return self.result result = {} for query_term, value in self.__query.words_index.items(): indexer_term = self.__indexer.words_index[query_term] tf_idf_query_term = self.__query.words_index[query_term]["idf"] * \ self.__query.words_index[query_term]["documents"][0]["tf"] tf_documents = list(map(lambda doc: doc["tf"], indexer_term["documents"])) dot_product = np.dot(tf_idf_query_term, tf_documents) result[query_term] = list(zip( list( map( lambda doc: doc["document"].text, indexer_term["documents"])) , list( map( lambda elem: elem / (np.linalg.norm(tf_idf_query_term) + np.linalg.norm(tf_documents)), dot_product )) )) self.result = result for key, elm in self.result.items(): self.result[key] = sorted(elm, key=lambda tup: tup[1], reverse=True) return self.result
[ { "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": fals...
3
IndexerQuery/model/QueryAnalizer.py
Llambi/Web_Semantica
import random from cereal import log from selfdrive.hardware.base import HardwareBase NetworkType = log.DeviceState.NetworkType NetworkStrength = log.DeviceState.NetworkStrength class Pc(HardwareBase): def get_os_version(self): return None def get_device_type(self): return "pc" def get_sound_card_online(self): return True def reboot(self, reason=None): print("REBOOT!") def uninstall(self): print("uninstall") def get_imei(self, slot): return "%015d" % random.randint(0, 1 << 32) def get_serial(self): return "cccccccc" def get_subscriber_info(self): return "" def get_network_type(self): return NetworkType.wifi def get_sim_info(self): return { 'sim_id': '', 'mcc_mnc': None, 'network_type': ["Unknown"], 'sim_state': ["ABSENT"], 'data_connected': False } def get_network_strength(self, network_type): return NetworkStrength.unknown def get_battery_capacity(self): return 100 def get_battery_status(self): return "" def get_battery_current(self): return 0 def get_battery_voltage(self): return 0 def get_battery_charging(self): return True def set_battery_charging(self, on): pass def get_usb_present(self): return False def get_current_power_draw(self): 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": "all_params_annotated", "question": "Does every function parameter in this file have a type annotation (excluding self/cl...
3
selfdrive/hardware/pc/hardware.py
viraatdas/openpilot
"""Useful Job for the task queue. Include this file in the ``task_paths`` list if you need them """ import sys import os import tempfile from pq.api import job @job() async def execute_python(self, code=None): """Execute arbitrary python code on a subprocess. For example: tasks.queue_task('execute.python', code='print("Hello World!")') """ assert isinstance(code, str), "code must be a string" fp, path = tempfile.mkstemp(suffix='.py', text=True) try: with open(path, 'w') as fp: fp.write(code) command = '%s %s' % (sys.executable, path) result = await self.shell(command) finally: os.remove(path) return result @job() async def execute_python_script(self, script=None): """Execute arbitrary python code on a subprocess """ assert isinstance(script, str), "script must be a string" assert os.path.isfile(script), "script %s is not a file" % script command = '%s %s' % (sys.executable, script) result = await self.shell(command) return result
[ { "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_nested_function_def", "question": "Does this file contain any function defined inside another function?", "answ...
3
pq/jobs.py
quantmind/pulsar-queue
import numpy as np from qaoa.operators import Kronecker, SumSigmaXOperator, Propagator class SumSigmaXPropagator(Propagator): def __init__(self,D,theta=0): assert( isinstance(D,SumSigmaXOperator) ) self.kronecker = Kronecker(np.eye(2),D.num_qubits(),dtype=complex) super().__init__(D,theta) def __str__(self): return "SumSigmaXPropagator" def set_control(self,theta): self.theta = theta c = np.cos(self.theta) s = 1j*np.sin(self.theta) self.kronecker.K = np.array(((c,s),(s,c)),dtype=complex) def apply(self,v,u): self.kronecker.apply(v,u) def apply_adjoint(self,v,u): self.kronecker.apply_adjoint(v,u) def as_matrix(self): return self.kronecker.as_matrix()
[ { "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
qaoa/operators/sum_sigma_x_propagator.py
gregvw/pyQAOA
#!/usr/bin/env python3 # (C) Copyright 2020 ECMWF. # # This software is licensed under the terms of the Apache Licence Version 2.0 # which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. # In applying this licence, ECMWF does not waive the privileges and immunities # granted to it by virtue of its status as an intergovernmental organisation # nor does it submit to any jurisdiction. # import os import pathlib import time from climetlab import settings from climetlab.utils import download_and_cache def path_to_url(path): return pathlib.Path(os.path.abspath(path)).as_uri() def test_download_1(): url = "https://github.com/ecmwf/climetlab/raw/main/docs/examples/test.grib?_=%s" % ( time.time(), ) download_and_cache(url) def test_download_2(): url = "https://github.com/ecmwf/climetlab/raw/main/docs/examples/test.grib" download_and_cache(url) def test_download_3(): with settings.temporary("download-out-of-date-urls", True): url = "https://get.ecmwf.int/test-data/climetlab/input/test.txt" download_and_cache(url) def test_download_4(): url = "https://get.ecmwf.int/test-data/climetlab/input/missing.txt" r = download_and_cache(url, return_none_on_404=True) assert r is None, r if __name__ == "__main__": from climetlab.testing import main main(globals())
[ { "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
tests/test_download.py
iacopoff/climetlab
from sklearn.ensemble import GradientBoostingClassifier, GradientBoostingRegressor from sklearn.model_selection import cross_val_score import numpy as np class GradientBoosting: def __init__(self, x_train, y_train, problemtype = 'regression', cv = 5): self.x_train = x_train self.y_train = y_train self.cv = cv if problemtype == 'regression': self.clf = GradientBoostingRegressor() elif problemtype == 'classification': self.clf = GradientBoostingClassifier() def classify(self): self.clf.fit(self.x_train, self.y_train) def regress(self): self.clf.fit(self.x_train, self.y_train) def show_cross_val_score(self): cv_score = cross_val_score(estimator=self.clf, X=self.x_train, y=self.y_train, cv=self.cv, n_jobs=-1) print('Gradient Boosting Cross Validated Score...') print(np.mean(cv_score)) print('\n') def optimise(self): pass
[ { "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
Algorithms/GradientBoosting/GradientBoosting.py
VireshDhawan/Data-Science-Templates
# coding: utf-8 from __future__ import unicode_literals from django.contrib import admin from .models import ThumbnailOption from django.contrib.admin.widgets import AdminFileWidget @admin.register(ThumbnailOption) class ThumbnailOptionAdmin(admin.ModelAdmin): fields = ['source', 'alias', 'options'] class ThumbnailOptionMixin(admin.ModelAdmin): class Media: pass def media(self): pass
[ { "point_num": 1, "id": "has_multiple_inheritance", "question": "Does any class in this file use multiple inheritance?", "answer": false }, { "point_num": 2, "id": "every_class_has_docstring", "question": "Does every class in this file have a docstring?", "answer": false }, {...
3
easy_thumbnails_admin/admin.py
Apkawa/easy-thumbnails-admin
import chainer import numpy as np from chainerrl.agents import a3c from chainerrl import links from chainerrl import misc from chainerrl.optimizers import rmsprop_async from chainerrl import policy from chainerrl import v_function from chainerrl.wrappers import atari_wrappers from chainerrl_visualizer import launch_visualizer class A3CFF(chainer.ChainList, a3c.A3CModel): def __init__(self, n_actions): self.head = links.NIPSDQNHead() self.pi = policy.FCSoftmaxPolicy( self.head.n_output_channels, n_actions) self.v = v_function.FCVFunction(self.head.n_output_channels) super().__init__(self.head, self.pi, self.v) def pi_and_v(self, state): out = self.head(state) return self.pi(out), self.v(out) def phi(x): # Feature extractor return np.asarray(x, dtype=np.float32) / 255 def make_env(): env = atari_wrappers.wrap_deepmind( atari_wrappers.make_atari(env_name), episode_life=False, clip_rewards=False) env.seed(seed) return env seed = 0 env_name = 'BreakoutNoFrameskip-v4' misc.set_random_seed(seed) env = make_env() n_actions = env.action_space.n model = A3CFF(n_actions) opt = rmsprop_async.RMSpropAsync(lr=7e-4, eps=1e-1, alpha=0.99) opt.setup(model) opt.add_hook(chainer.optimizer.GradientClipping(40)) agent = a3c.A3C(model, opt, t_max=5, gamma=0.99, beta=1e-2, phi=phi) agent.load('parameters') ACTION_MEANINGS = { 0: 'NOOP', 1: 'FIRE', 2: 'RIGHT', 3: 'LEFT', } launch_visualizer(agent, env, ACTION_MEANINGS, raw_image_input=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": "all_function_names_snake_case", "question": "Are all function names in this file written in snake_case?",...
3
examples/a3c_breakout/main.py
Ravie403/chainerrl-visualizer
"""Route to all channels""" import requests from common.config import constants from server import endpoints, errors def get(handler, parameters, url_parameters, *ids_parameters): """GET method""" headers = {"Authorization": "Bot " + constants.BOT_TOKEN} try: r = requests.get(endpoints.DISCORD_GUILD_CHANNELS.format(*ids_parameters), headers=headers) r.raise_for_status() except requests.exceptions.HTTPError: handler.logger.exception(errors.DISCORD_API_GET_ERROR_MESSAGE) handler.logger.debug(r.text) handler.send_error(500, errors.DISCORD_API_GET_ERROR_MESSAGE) return etag = handler.get_etag(r.text) if not etag: handler.send_error(304) return handler.send_json(r.text, etag) def post(handler, parameters, url_parameters, *ids_parameters): """POST method""" headers = {"Authorization": "Bot " + constants.BOT_TOKEN, "Content-Type": "application/json"} try: r = requests.post(endpoints.DISCORD_GUILD_CHANNELS.format(*ids_parameters), headers=headers, data=parameters) r.raise_for_status() except requests.exceptions.HTTPError: handler.logger.exception(errors.DISCORD_API_POST_ERROR_MESSAGE) handler.logger.debug(r.text) handler.send_error(500, errors.DISCORD_API_POST_ERROR_MESSAGE) return handler.send_json(r.text)
[ { "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
backend/server/routes/api/v1/discord/guilds/channels/all.py
NezzarClp/Tosurnament
import re from mail_app.mail import Mail from mail_app.mail_processors.abstract_processor import AbstractProcessor from mail_app.processed_mail import ProcessedMail class PasswordProcessor(AbstractProcessor): general_keywords = ["password (reset|request|update|updated)", "(new|reset|change|updated|changed your) password", "address verification", "(confirm|confirm your|activate your) (registration|account)"] def __init__(self): super().__init__() self.category = "Password" def process(self, mail): if self.__general_conditions(mail): return ProcessedMail(mail.user_id, mail.message_id, mail.from_, self.category, mail.body, mail.time, mail.attachments) ############################################ Conditions ############################################ def __general_conditions(self, mail: Mail): return (any(re.search(keyword, mail.subject.lower()) for keyword in self.general_keywords) or any(re.search(keyword, mail.body.lower()) for keyword in self.general_keywords) or any(re.search(keyword, name.lower()) for name, _ in mail.attachments.items() for keyword in self.general_keywords))
[ { "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
mail_app/mail_processors/password_processor.py
teamsaucisse/Data-Mailing
import pytest def pytest_addoption(parser): parser.addoption( "--hide-torch", action='store_true', default=False, help="Run tests hiding torch." ) def pytest_configure(config): config.addinivalue_line("markers", "hide_torch: mark test as hiding torch") def pytest_collection_modifyitems(config, items): if config.getoption("--hide-torch"): # --hide-torch given in cli: do not skip the tests mocking torch return skip_torch = pytest.mark.skip(reason="needs --hide-torch option to run") for item in items: if "hide_torch" in item.keywords: item.add_marker(skip_torch)
[ { "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
deepnog/utils/tests/conftest.py
alepfu/deepnog
""" FieldOverride that forces Show Answer values that use Past Due logic to new Show Answer values that remove the Past Due check (keeping the rest intact) """ from lms.djangoapps.courseware.field_overrides import FieldOverrideProvider from openedx.features.course_experience import RELATIVE_DATES_FLAG from xmodule.capa_module import SHOWANSWER class ShowAnswerFieldOverride(FieldOverrideProvider): """ A concrete implementation of :class:`~courseware.field_overrides.FieldOverrideProvider` which forces Show Answer values that use Past Due logic to new Show Answer values that remove the Past Due check (keeping the rest intact) Once Courseware is able to use BlockTransformers, this override should be converted to a BlockTransformer to set the showanswer field. """ def get(self, block, name, default): """ Overwrites the 'showanswer' field on blocks in self-paced courses to remove any checks about due dates being in the past. """ if name != 'showanswer' or not self.fallback_field_data.has(block, 'showanswer'): return default mapping = { SHOWANSWER.ATTEMPTED: SHOWANSWER.ATTEMPTED_NO_PAST_DUE, SHOWANSWER.CLOSED: SHOWANSWER.AFTER_ALL_ATTEMPTS, SHOWANSWER.CORRECT_OR_PAST_DUE: SHOWANSWER.ANSWERED, SHOWANSWER.FINISHED: SHOWANSWER.AFTER_ALL_ATTEMPTS_OR_CORRECT, SHOWANSWER.PAST_DUE: SHOWANSWER.NEVER, } current_show_answer_value = self.fallback_field_data.get(block, 'showanswer') return mapping.get(current_show_answer_value, default) @classmethod def enabled_for(cls, course): """ Enabled only for Self-Paced courses using Personalized User Schedules. """ return course and course.self_paced and RELATIVE_DATES_FLAG.is_enabled(course.id)
[ { "point_num": 1, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "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
Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/openedx/features/personalized_learner_schedules/show_answer/show_answer_field_override.py
osoco/better-ways-of-thinking-about-software
from rcrs_core.commands.Command import Command from rcrs_core.worldmodel.entityID import EntityID from rcrs_core.connection import URN from rcrs_core.connection import RCRSProto_pb2 class AKTell(Command): def __init__(self, agent_id: EntityID, time: int, message: str) -> None: super().__init__() self.urn = URN.Command.AK_TELL self.agent_id = agent_id self.message = message.encode('utf-8') self.time = time def prepare_cmd(self): msg = RCRSProto_pb2.MessageProto() msg.urn = self.urn msg.components[URN.ComponentControlMSG.AgentID].entityID = self.agent_id.get_value() msg.components[URN.ComponentControlMSG.Time].intValue = self.time msg.components[URN.ComponentCommand.Message].rawData = self.message return msg
[ { "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
rcrs_core/commands/AKTell.py
roborescue/rcrs-core-python
""" With classes, we have a problem with heritage. Note that for standard functions (like sum_arrays), we actually also have the problem with monkey patching. We can just say that monkey patching of `sum_arrays` is not supported (so that `sum_arrays` can be treated as a Pythran function, and potentially inlined) but for class, we really want to support heritage (like in MyClassChild) so we would need to replace `compute` by a Python method calling Pythran functions and Python methods (which themselves call Pythran functions). The mechanism needed for `compute` is much more complicated than the simple case in `pythran_class.py` and more complicated than what is needed for `compute1` (which is actually similar to [issue #7](https://bitbucket.org/fluiddyn/fluidpythran/issues/7/support-kernels-with-function-calls)). """ from fluidpythran import Type, NDim, Array, boost import numpy as np T = Type(int, np.float64) N = NDim(1) A1 = Array[T, N] A2 = Array[float, N + 1] def sum_arrays(arr0, arr1): return arr0 + arr1 class MyClass: arr0: A1 arr1: A1 arr2: A2 def __init__(self, n, dtype=int): self.arr0 = np.zeros(n, dtype=dtype) self.arr1 = np.zeros(n, dtype=dtype) self.arr2 = np.zeros(n) @boost def compute(self, alpha: float): tmp = self.sum_arrays().mean() return tmp ** alpha * self.arr2 def sum_arrays(self): return self.arr0 + self.arr1 @boost def compute1(self, alpha: float): tmp = sum_arrays(self.arr0, self.arr1).mean() return tmp ** alpha * self.arr2 class MyClassChild(MyClass): def sum_arrays(self): return 2 * self.arr0 + self.arr1
[ { "point_num": 1, "id": "every_class_has_docstring", "question": "Does every class in this file have a docstring?", "answer": false }, { "point_num": 2, "id": "all_function_names_snake_case", "question": "Are all function names in this file written in snake_case?", "answer": true...
3
doc/examples/not_implemented/pythran_class_with_calls.py
fluiddyn/fluidpythran
from confd_gnmi_adapter import GnmiServerAdapter class GnmiNetconfServerAdapter(GnmiServerAdapter): @classmethod def get_adapter(cls): pass def set(self, prefix, path, val): pass def get_subscription_handler(self, subscription_list): pass def capabilities(self): return [] def get(self, prefix, paths, data_type, use_models): return []
[ { "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
confdgnmi/src/confd_gnmi_netconf_adapter.py
micnovak/ConfD-Demos
import sqlite3 class DB: def __init__(self, db, memory=False): if not db.endswith('.db'): db += '.db' self.conn = sqlite3.connect(db) if memory: memory_db = sqlite3.connect(':memory:') db_dump = "".join(line for line in self.conn.iterdump()) memory_db.executescript(db_dump) self.conn.close() self.cursor = memory_db.cursor() else: self.cursor = self.conn.cursor() def __len__(self): return len(self.query('SELECT DISTINCT sample FROM SVDB')) def query(self, query): self.cursor.execute(query) res = self.cursor.fetchall() return res def drop(self, query): try: self.cursor.execute(query) except Exception: pass def create(self, query): self.cursor.execute(query) self.conn.commit() def insert_many(self, data): self.cursor.executemany('INSERT INTO SVDB VALUES (?,?,?,?,?,?,?,?,?,?,?)', data) self.conn.commit() def create_index(self, name, columns): query = "CREATE INDEX {} ON SVDB {}".format(name, columns) self.cursor.execute(query) self.conn.commit() @property def tables(self): res = self.query("SELECT name FROM sqlite_master WHERE type=\'table\'") return [table[0] for table in res] @property def sample_ids(self): return [sample for sample in self.query('SELECT DISTINCT sample FROM SVDB')]
[ { "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
svdb/database.py
khurrammaqbool/SVDB
import os import sys from csv import reader class FileParser: def __init__(self, file_path): # Load file filename, extension = os.path.splitext(file_path) # Check for correct file format if extension != '.txt': print('Invalid file type, must be .txt with one query per line') sys.exit() # Get queries from file self.queries = self.parse_file(file_path) def parse_file(self, file_path): file = open(file_path, 'r') queries = [] # Read each line of file for line in file: queries.append(line.replace('\n', '')) # Close and return queries file.close() return queries
[ { "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
src/file_parser.py
gldgrnt/twitter-search-scraper
# -*- coding: utf-8 -*- from PyQt4 import QtCore class Module(QtCore.QObject): # User-readable name for this module moduleDisplayName = None # Override this class attribute to have this module appear # under different category sections in the manager window's module list moduleCategory = None def __init__(self, manager, name, config): QtCore.QObject.__init__(self) self.name = name self.manager = manager self.config = config manager.declareInterface(name, ['module'], self) ## deprecated. Use interfaces instead. #def hasInterface(self, interface): #"""Return True if this module implements the named interface. #Examples: 'DataSource', 'Canvas'""" #return False def window(self): """Return the Qt window for this module""" if hasattr(self, 'win'): return self.win return None def quit(self): """Must be called after modules exit.""" #print "inform quit", self.name self.manager.moduleHasQuit(self)
[ { "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
acq4/modules/Module.py
ablot/acq4
# -*- coding: utf-8 -*- # Copyright (c) 2013 Artem Glebov import sys import transmissionrpc __settings__ = sys.modules[ "__main__" ].__settings__ def get_settings(): params = { 'address': __settings__.getSetting('rpc_host'), 'port': __settings__.getSetting('rpc_port'), 'user': __settings__.getSetting('rpc_user'), 'password': __settings__.getSetting('rpc_password'), 'stop_all_on_playback': __settings__.getSetting('stop_all_on_playback') } return params def get_params(): params = { 'address': __settings__.getSetting('rpc_host'), 'port': __settings__.getSetting('rpc_port'), 'user': __settings__.getSetting('rpc_user'), 'password': __settings__.getSetting('rpc_password'), } return params def get_rpc_client(): params = get_params() return transmissionrpc.Client(**params)
[ { "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
resources/lib/common.py
torstehu/Transmission-XBMC
# -*- coding: UTF-8 -*- """ Author:wistn since:2020-06-11 LastEditors:Do not edit LastEditTime:2020-10-06 Description: """ class DbApi: @classmethod def isFaved(cls, book): return False @classmethod def logBID(cls, source, bookKey, bookUrl): # if ( # db.existsSQL('SELECT * from .books WHERE bkey=?', bookKey) == False # ) { # db.updateSQL( # 'INSERT INTO books(bkey,url,source) VALUES(?,?,?) ', # bookKey, # bookUrl, # source # ) pass @classmethod def getBID(cls, bookKey): # let bid = 0 # let dr = db.selectSQL('SELECT id from .books WHERE bkey=? ', bookKey) # if (dr.read()) { # bid = dr.getInt('id') # # dr.close() # return bid pass
[ { "point_num": 1, "id": "has_multiple_inheritance", "question": "Does any class in this file use multiple inheritance?", "answer": false }, { "point_num": 2, "id": "all_params_annotated", "question": "Does every function parameter in this file have a type annotation (excluding self/c...
3
sited_py/lib/org_noear_siteder_dao_db_DbApi.py
wistn/sited_py
#!/usr/bin/env python3 """ classification type (books.py) """ from enum import Enum from typing import Dict class BookType(Enum): """ Enum to store nlp types """ dostoyevsky = "dostoyevsky" doyle = "doyle" austen = "austen" class StartEnd: """ start and end lines for book """ def __init__(self, start: int, end: int): self.start = start self.end = end start_end_map: Dict[BookType, StartEnd] = { BookType.dostoyevsky: StartEnd(186, 35959), BookType.doyle: StartEnd(62, 12681), BookType.austen: StartEnd(94, 80104), } class_map: Dict[BookType, str] = { BookType.dostoyevsky: 'Fyodor Dostoyevsky', BookType.doyle: 'Arthur Conan Doyle', BookType.austen: 'Jane Austen', }
[ { "point_num": 1, "id": "every_class_has_docstring", "question": "Does every class in this file have a docstring?", "answer": true }, { "point_num": 2, "id": "more_functions_than_classes", "question": "Does this file define more functions than classes?", "answer": false }, { ...
3
assignment1/src/books.py
jschmidtnj/cs584
from datetime import datetime from api import utils from exchanges.exchange import Exchange from strategies.strategy import Strategy class Runner(Strategy): def __init__(self, exchange: Exchange, timeout=60, *args, **kwargs): super().__init__(exchange, timeout, *args, **kwargs) self.buy_price = 0 self.sell_price = 0 self.stop_loss = 0 self.market_delta = 0 self.advised = False self.waiting_order = False self.fulfilled_orders = [] self.last_price = 0 def run(self): print('*******************************') print('Exchange: ', self.exchange.name) print('Pair: ', self.exchange.get_symbol()) print('Available: ', self.exchange.get_asset_balance(self.exchange.currency) + ' ' + self.exchange.currency) print('Available: ', self.exchange.get_asset_balance(self.exchange.currency) + ' ' + self.exchange.asset) print('Price: ', self.price.current) # Persist price response = self.price.create() print(response)
[ { "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
strategies/runner.py
Guillerbr/cryptobot
import re import smtplib from email.message import EmailMessage from email.mime.text import MIMEText from typing import Union from pywhatkit.core.exceptions import UnsupportedEmailProvider def send_mail( email_sender: str, password: str, subject: str, message: Union[str, MIMEText], email_receiver: str, ) -> None: """Send an Email""" domain = re.search("(?<=@)[^.]+(?=\\.)", email_sender) hostnames = { "gmail": "smtp.gmail.com", "yahoo": "smtp.mail.yahoo.com", "outlook": "smtp.live.com", "aol": "smtp.aol.com", } hostname = None for x in hostnames: if x == domain.group(): hostname = hostnames[x] break if hostname is None: raise UnsupportedEmailProvider(f"{domain.group()} is not Supported Currently!") with smtplib.SMTP_SSL(hostname, 465) as smtp: smtp.login(email_sender, password) msg = EmailMessage() msg["Subject"] = subject msg["From"] = email_sender msg["To"] = email_receiver msg.set_content(message) smtp.send_message(msg) print("Email Sent Successfully!") def send_hmail( email_sender: str, password: str, subject: str, html_code: str, email_receiver: str ) -> None: """Send an Email with HTML Code""" message = MIMEText(html_code, "html") send_mail(email_sender, password, subject, message, email_receiver)
[ { "point_num": 1, "id": "all_return_types_annotated", "question": "Does every function in this file have a return type annotation?", "answer": true }, { "point_num": 2, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer...
3
pywhatkit/mail.py
Ankit404butfound/PyWhatK
# coding: utf-8 """ Cisco Intersight Cisco Intersight is a management platform delivered as a service with embedded analytics for your Cisco and 3rd party IT infrastructure. This platform offers an intelligent level of management that enables IT organizations to analyze, simplify, and automate their environments in more advanced ways than the prior generations of tools. Cisco Intersight provides an integrated and intuitive management experience for resources in the traditional data center as well as at the edge. With flexible deployment options to address complex security needs, getting started with Intersight is quick and easy. Cisco Intersight has deep integration with Cisco UCS and HyperFlex systems allowing for remote deployment, configuration, and ongoing maintenance. The model-based deployment works for a single system in a remote location or hundreds of systems in a data center and enables rapid, standardized configuration and deployment. It also streamlines maintaining those systems whether you are working with small or very large configurations. # noqa: E501 The version of the OpenAPI document: 1.0.9-1295 Contact: intersight@cisco.com Generated by: https://openapi-generator.tech """ from __future__ import absolute_import import unittest import intersight from intersight.models.firmware_cifs_server_all_of import FirmwareCifsServerAllOf # noqa: E501 from intersight.rest import ApiException class TestFirmwareCifsServerAllOf(unittest.TestCase): """FirmwareCifsServerAllOf unit test stubs""" def setUp(self): pass def tearDown(self): pass def testFirmwareCifsServerAllOf(self): """Test FirmwareCifsServerAllOf""" # FIXME: construct object with mandatory attributes with example values # model = intersight.models.firmware_cifs_server_all_of.FirmwareCifsServerAllOf() # noqa: E501 pass if __name__ == '__main__': unittest.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": "every_function_under_20_lines", "question": "Is every function in this file shorter than 20 lines?", "answer": tru...
3
test/test_firmware_cifs_server_all_of.py
sdnit-se/intersight-python
############################################################################### # # Tests for XlsxWriter. # # 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('cond_format06.xlsx') def test_create_file(self): """Test the creation of a simple XlsxWriter file with conditional formatting.""" workbook = Workbook(self.got_filename) worksheet = workbook.add_worksheet() format1 = workbook.add_format({ 'pattern': 15, 'fg_color': '#FF0000', 'bg_color': '#FFFF00' }) worksheet.write('A1', 10) worksheet.write('A2', 20) worksheet.write('A3', 30) worksheet.write('A4', 40) worksheet.conditional_format('A1', {'type': 'cell', 'format': format1, 'criteria': '>', 'value': 7, }) 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": "has_nested_function_def", "question": "Does this file contain any function defined inside another function?", "answe...
3
xlsxwriter/test/comparison/test_cond_format06.py
eddiechapman/XlsxWriter
"""An example of jinja2 templating""" from bareasgi import Application, HttpRequest, HttpResponse import jinja2 import pkg_resources import uvicorn from bareasgi_jinja2 import Jinja2TemplateProvider, add_jinja2 async def http_request_handler(request: HttpRequest) -> HttpResponse: """Handle the request""" return await Jinja2TemplateProvider.apply( request, 'example1.html', {'name': 'rob'} ) async def handle_no_template(request: HttpRequest) -> HttpResponse: """This is what happens if there is no template""" return await Jinja2TemplateProvider.apply( request, 'notemplate.html', {'name': 'rob'} ) if __name__ == '__main__': TEMPLATES = pkg_resources.resource_filename(__name__, "templates") env = jinja2.Environment( loader=jinja2.FileSystemLoader(TEMPLATES), autoescape=jinja2.select_autoescape(['html', 'xml']), enable_async=True ) app = Application() add_jinja2(app, env) app.http_router.add({'GET'}, '/example1', http_request_handler) app.http_router.add({'GET'}, '/notemplate', handle_no_template) uvicorn.run(app, port=9010)
[ { "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": true...
3
examples/example1.py
rob-blackbourn/bareasgi-jinja2
# -*- coding: utf-8 -*- from cms.plugin_pool import plugin_pool from cms.plugin_base import CMSPluginBase from .models import OembedVideoPlugin, OembedRichPlugin from django.utils.translation import ugettext_lazy as _ from django.conf import settings class CMSOembedVideoPlugin(CMSPluginBase): name = _('Video (embedded)') model = OembedVideoPlugin render_template = 'djangocms_oembed/plugins/video.html' admin_preview = False text_enabled = True fieldsets = ( (None, {'fields': ('oembed_url', ('width', 'height',), 'autoplay', 'loop', 'show_related',)}), ('advanced', {'fields': ('type', 'provider', 'html', 'data'), 'classes': ['collapse']}), ) readonly_fields = ('type', 'provider', 'html', 'data',) def icon_src(self, instance): return settings.STATIC_URL + u"cms/images/plugins/snippet.png" plugin_pool.register_plugin(CMSOembedVideoPlugin) class CMSOembedRichPlugin(CMSPluginBase): name = _('Rich Content (embedded)') model = OembedRichPlugin render_template = 'djangocms_oembed/plugins/rich.html' admin_preview = False text_enabled = True fieldsets = ( (None, {'fields': ('oembed_url',)}), ('advanced', {'fields': ('type', 'provider', 'html', 'data'), 'classes': ['collapse']}), ) readonly_fields = ('type', 'provider', 'html', 'data',) def icon_src(self, instance): return settings.STATIC_URL + u"cms/images/plugins/snippet.png" plugin_pool.register_plugin(CMSOembedRichPlugin)
[ { "point_num": 1, "id": "more_functions_than_classes", "question": "Does this file define more functions than classes?", "answer": false }, { "point_num": 2, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": false ...
3
djangocms_oembed/cms_plugins.py
MatthewWilkes/djangocms-oembed
import networkx as nx import numpy as np import torch from torch.utils.data import Dataset from dsloader.util import kron_graph, random_binary, make_fractional class KroneckerDataset (Dataset): def __init__(self, kron_iter=4, seed_size=4, fixed_seed=None, num_graphs=1, perms_per_graph=256, progress_bar=False): self.kron_iter = kron_iter self.seed_size = seed_size self.num_nodes = seed_size ** (kron_iter + 1) self.seeds = [] self.matrices = [] num_iter = range(num_graphs) if progress_bar: from tqdm import tqdm num_iter = tqdm(num_iter) for i in num_iter: seed = random_binary(seed_size, use_sparsity=False) self.seeds.append(seed) if fixed_seed is not None: k_g = kron_graph(fixed_seed, n=kron_iter).astype(np.float) else: k_g = kron_graph(seed, n=kron_iter).astype(np.float) for j in range(perms_per_graph): self.matrices.append(make_fractional(k_g, inplace=False)) def __len__(self): return len(self.matrices) def __getitem__(self, idx): return torch.tensor(self.matrices[idx])
[ { "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": false }, { "point_num": 2, "id": "all_params_annotated", "question": "Does every function parameter in this file have a t...
3
src/dsloader/kronecker.py
willshiao/brgan
"""Services module.""" class ConfigService: def __init__(self, config): self._config = config def build(self): self._config.from_dict({"default": {"db_path": "~/test"}})
[ { "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
examples/miniapps/application-multiple-containers-runtime-overriding/example/services.py
YelloFam/python-dependency-injector
class AppTestAtexit: def test_args(self): import atexit import io import sys stdout, stderr = sys.stdout, sys.stderr try: sys.stdout = sys.stderr = capture = io.StringIO() def h1(): print("h1") def h2(): print("h2") atexit.register(h1) atexit.register(h2) assert atexit._ncallbacks() == 2 atexit._run_exitfuncs() assert atexit._ncallbacks() == 0 assert capture.getvalue() == 'h2\nh1\n' finally: sys.stdout = stdout sys.stderr = stderr def test_badargs(self): import atexit atexit.register(lambda: 1, 0, 0, (x for x in (1,2)), 0, 0) raises(TypeError, atexit._run_exitfuncs)
[ { "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
pypy/module/atexit/test/test_atexit.py
yxzoro/pypy
# coding: utf-8 """ Kubernetes No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 OpenAPI spec version: v1.14.7 Generated by: https://openapi-generator.tech """ from __future__ import absolute_import import unittest import kubernetes_asyncio.client from kubernetes_asyncio.client.models.v1_persistent_volume_claim_list import V1PersistentVolumeClaimList # noqa: E501 from kubernetes_asyncio.client.rest import ApiException class TestV1PersistentVolumeClaimList(unittest.TestCase): """V1PersistentVolumeClaimList unit test stubs""" def setUp(self): pass def tearDown(self): pass def testV1PersistentVolumeClaimList(self): """Test V1PersistentVolumeClaimList""" # FIXME: construct object with mandatory attributes with example values # model = kubernetes_asyncio.client.models.v1_persistent_volume_claim_list.V1PersistentVolumeClaimList() # noqa: E501 pass if __name__ == '__main__': unittest.main()
[ { "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
kubernetes_asyncio/test/test_v1_persistent_volume_claim_list.py
aK0nshin/kubernetes_asyncio
# -*- coding: utf-8 -*- from mollusc.dist import Twine class TestTwine(object): def test_register_command(self): twine = Twine(username='registrar', password='reg1strar') assert twine.get_command('register', 'package.whl', {'-c': 'test register'}) == [ 'twine', 'register', '--repository-url', Twine.DEFAULT_REPO_URL, '-u', 'registrar', '-c', 'test register', 'package.whl' ] def test_upload_command(self): twine = Twine(username='uploader', password='upl0ader') assert twine.get_command('upload', ['package.whl', 'package.tar.gz'], {'-c': 'test upload'}) == [ 'twine', 'upload', '--repository-url', Twine.DEFAULT_REPO_URL, '-u', 'uploader', '-c', 'test upload', 'package.whl', 'package.tar.gz' ]
[ { "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
test/test_dist.py
bachew/mollusc
from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, \ PermissionsMixin class UserManager(BaseUserManager): def create_user(self, email, password=None, **extra_fields): """Creates and saves a new user""" if not email: raise ValueError('Users must have an email address') user = self.model(email=self.normalize_email(email), **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password): """Create and saves e new superuser""" user = self.create_user(email, password) user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class User(AbstractBaseUser, PermissionsMixin): """Custom user model that support using email instead of username""" email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'email'
[ { "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
app/core/models.py
hm289/recipe-app-api
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from habitat.core.registry import registry from habitat.core.simulator import Simulator def _try_register_igibson_socialnav(): try: import habitat_sim # noqa: F401 has_habitat_sim = True except ImportError as e: has_habitat_sim = False habitat_sim_import_error = e if has_habitat_sim: from habitat.sims.igibson_challenge.social_nav import ( iGibsonSocialNav ) # noqa: F401 from habitat.sims.igibson_challenge.interactive_nav import ( iGibsonInteractiveNav ) # noqa: F401 else: @registry.register_simulator(name="iGibsonSocialNav") class iGibsonSocialNavImportError(Simulator): def __init__(self, *args, **kwargs): raise habitat_sim_import_error @registry.register_simulator(name="iGibsonInteractiveNav") class iGibsonSocialNavImportError(Simulator): def __init__(self, *args, **kwargs): raise habitat_sim_import_error
[ { "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
habitat/sims/igibson_challenge/__init__.py
qianLyu/habitat-lab
class Graph: def __init__(self, vertexes: int) -> None: self.vertexes = vertexes self.graph = [] def connect(self, u: int, v: int, w: int) -> None: self.graph.append([u, v, w]) def show(self, distances: list) -> None: print(distances) def fordbellman(self, start: int) -> None: d = [float("inf") for _ in range(self.vertexes)] d[start] = 0 for _ in range(self.vertexes - 1): for u, v, w in self.graph: if d[v] > d[u] + w: d[v] = d[u] + w self.show(d) graph = Graph(5) graph.connect(0, 1, -1) graph.connect(0, 2, 4) graph.connect(1, 2, 3) graph.connect(1, 3, 2) graph.connect(1, 4, 2) graph.connect(3, 2, 5) graph.connect(3, 1, 1) graph.connect(4, 3, -3) graph.fordbellman(0)
[ { "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
2 semester/DM/Practics/2022-03-09/FordBellman.py
kurpenok/Labs
import celery import logging import prometheus_client from .monitor import ( TaskThread, WorkerMonitoringThread, EnableEventsThread, setup_metrics, ) __all__ = ("CeleryExporter",) class CeleryExporter: def __init__( self, broker_url, listen_address, max_tasks=10000, namespace="celery", transport_options=None, enable_events=False, ): self._listen_address = listen_address self._max_tasks = max_tasks self._namespace = namespace self._enable_events = enable_events self._app = celery.Celery(broker=broker_url) self._app.conf.broker_transport_options = transport_options or {} def start(self): setup_metrics(self._app, self._namespace) self._start_httpd() t = TaskThread( app=self._app, namespace=self._namespace, max_tasks_in_memory=self._max_tasks, ) t.daemon = True t.start() w = WorkerMonitoringThread(app=self._app, namespace=self._namespace) w.daemon = True w.start() if self._enable_events: e = EnableEventsThread(app=self._app) e.daemon = True e.start() def _start_httpd(self): # pragma: no cover """ Starts the exposing HTTPD using the addr provided in a separate thread. """ host, port = self._listen_address.split(":") logging.info("Starting HTTPD on {}:{}".format(host, port)) prometheus_client.start_http_server(int(port), host)
[ { "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": fal...
3
celery_exporter/core.py
itsx/celery-exporter-experiments
import numpy as np from lib.simulation import Simulation from lib.rule_function import conway_rule from Conway.lib.neighbourhood import moore_neighbourhood SIMULATION_SIZE = (100,100) NUMBER_OF_STEPS = 2 sim = Simulation( SIMULATION_SIZE, conway_rule) def time_numpy (): """ Times the numpy implementation. To run use command-line: python3 -m timeit -s 'from benchmark import time_numpy' 'time_numpy()' """ for i in range(NUMBER_OF_STEPS): next(sim) #time_numpy () neighbourhood_data = np.zeros(10000,dtype='uint8').reshape(100,100) neighbourhood_pos = (0,0) n_out = np.zeros(9, dtype='uint8') def time_neighbourhoods (): """ Times the numpy implementation. To run use command-line: python3 -m timeit -s 'from benchmark import time_neighbourhoods' 'time_neighbourhoods()' """ for _ in range(10000): moore_neighbourhood (neighbourhood_data, neighbourhood_pos[0], neighbourhood_pos[1], n_out)
[ { "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_nested_function_def", "question": "Does this file contain any function defined inside another function?", "answ...
3
autumn_ca/benchmark.py
goshdarngames/Autumn-CA
from . import * class HelloWorldController(AppDevController): def get_path(self): return "/hello/" def get_methods(self): return ["GET"] @authorize_user def content(self, **kwargs): return {"message": "Hello, 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/app/coursegrab/controllers/hello_world_controller.py
cuappdev/coursegrab-backend
# Copyright 2019 Canonical 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 ros2cli.node.strategy import NodeStrategy from ros2topic.api import get_topic_names_and_types from ros2topic.api import TopicNameCompleter from ros2topic.verb import VerbExtension class TypeVerb(VerbExtension): """Print a topic's type.""" def add_arguments(self, parser, cli_name): arg = parser.add_argument( 'topic_name', help="Name of the ROS topic to get type (e.g. '/chatter')") arg.completer = TopicNameCompleter( include_hidden_topics_key='include_hidden_topics') def main(self, *, args): with NodeStrategy(args) as node: topic_names_and_types = get_topic_names_and_types( node=node, include_hidden_topics=args.include_hidden_topics) for (topic_name, topic_types) in topic_names_and_types: if args.topic_name == topic_name: for topic_type in topic_types: print(topic_type) return 0 return 1
[ { "point_num": 1, "id": "more_functions_than_classes", "question": "Does this file define more functions than classes?", "answer": true }, { "point_num": 2, "id": "all_params_annotated", "question": "Does every function parameter in this file have a type annotation (excluding self/cl...
3
ros2topic/ros2topic/verb/type.py
sunbo57123/ros2cli_common_extension
from typing import * import torch.nn as nn import torch.optim as optim from models.LitBase import LitBase from .models import AlexNet class LitAlexNet(LitBase): def __init__(self, args: Dict[str, Any]): super().__init__() self.save_hyperparameters(args) self.model = AlexNet( image_channels=self.hparams.image_channels, num_classes=self.hparams.num_classes, dropout_rate=self.hparams.dropout_rate, ) self.loss = nn.CrossEntropyLoss() def configure_optimizers(self) -> optim.Optimizer: optimizer = optim.Adam( self.parameters(), lr=self.hparams.lr, weight_decay=self.hparams.weight_decay, ) scheduler_dict = { "scheduler": optim.lr_scheduler.ReduceLROnPlateau( optimizer, mode=self.hparams.scheduler_mode, factor=self.hparams.scheduler_factor, patience=self.hparams.scheduler_patience, verbose=True, ), "monitor": self.hparams.scheduler_monitor, } return {"optimizer": optimizer, "lr_scheduler": scheduler_dict}
[ { "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
models/AlexNet/lightning_model.py
zkdlfrlwl2/Classification-For-Everyone
"""Symbolic quaterion operations, dynamics and rotations.""" import numpy as np import sympy def derivative(quat, omega, renorm_gain=0): [q0, q1, q2, q3] = quat [p, q, r] = omega err = 1 - (q0**2 + q1**2 + q2**2 + q3**2) q0dot = -0.5 * (p*q1 + q*q2 + r*q3) + renorm_gain*err*q0 q1dot = -0.5 * (-p*q0 - r*q2 + q*q3) + renorm_gain*err*q1 q2dot = -0.5 * (-q*q0 + r*q1 - p*q3) + renorm_gain*err*q2 q3dot = -0.5 * (-r*q0 - q*q1 + p*q2) + renorm_gain*err*q3 return np.array([q0dot, q1dot, q2dot, q3dot]) def rotmat(quat): """Quaternion rotation matrix.""" q0, q1, q2, q3 = quat return np.array( [[q0**2 + q1**2 - q2**2 - q3**2, 2*(q1*q2 + q0*q3), 2*(q1*q3 - q0*q2)], [2*(q1*q2 - q0*q3), q0**2 - q1**2 + q2**2 - q3**2, 2*(q2*q3 + q0*q1)], [2*(q1*q3 + q0*q2), 2*(q2*q3 - q0*q1), q0**2 - q1**2 - q2**2 + q3**2]] ) def toeuler(quat): """Convert quaternion rotation to roll-pitch-yaw Euler angles.""" q0, q1, q2, q3 = quat roll = sympy.atan2(2*(q2*q3 + q0*q1), q0**2 - q1**2 - q2**2 + q3**2) pitch = -sympy.asin(2*(q1*q3 - q0*q2)) yaw = sympy.atan2(2*(q1*q2 + q0*q3), q0**2 + q1**2 - q2**2 - q3**2) return np.array([roll, pitch, yaw])
[ { "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
ceacoest/modelling/symquat.py
dimasad/ceacoest
import numpy as np def train_ml_squarer() -> None: print("Training!") def square() -> int: """Square a number...maybe""" return np.random.randint(1, 100) if __name__ == '__main__': train_ml_squarer()
[ { "point_num": 1, "id": "all_return_types_annotated", "question": "Does every function in this file have a return type annotation?", "answer": true }, { "point_num": 2, "id": "has_nested_function_def", "question": "Does this file contain any function defined inside another function?"...
3
packaging/squarer/ml_squarer.py
g-nightingale/tox_examples
# Copyright 2016 Citrix Systems # # 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 os_xenapi.client.i18n import _ class OsXenApiException(Exception): """Base OsXenapi Exception To correctly use this class, inherit from it and define a 'msg_fmt' property. That msg_fmt will get printf'd with the keyword arguments provided to the constructor. """ msg_fmt = _("An unknown exception occurred.") code = 500 def __init__(self, message=None, **kwargs): self.kwargs = kwargs if 'code' not in self.kwargs: try: self.kwargs['code'] = self.code except AttributeError: pass if not message: message = self.msg_fmt % kwargs self.message = message super(OsXenApiException, self).__init__(message) def format_message(self): # NOTE(mrodden): use the first argument to the python Exception object # which should be our full NovaException message, (see __init__) return self.args[0] class PluginRetriesExceeded(OsXenApiException): msg_fmt = _("Number of retries to plugin (%(num_retries)d) exceeded.") class SessionLoginTimeout(OsXenApiException): msg_fmt = _("Unable to log in to XenAPI (is the Dom0 disk full?)")
[ { "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_class_has_docstring", "question": "Does every class in this file have a docstring?", "answer": false }, ...
3
os_xenapi/client/exception.py
mail2nsrajesh/os-xenapi
import os from time import gmtime, strftime DEBUG=0 INFO=1 WARN=2 ERROR=3 LEVEL = DEBUG _idx2str = ['D', 'I', 'W', 'E'] get_logger = lambda x:Logger(x) class Logger(): def __init__(self, name='') -> None: self.name = name if self.name != '': self.name = '[' + self.name + ']' self.debug = self._generate_print_func(DEBUG) self.info = self._generate_print_func(INFO) self.warn = self._generate_print_func(WARN) self.error = self._generate_print_func(ERROR) def _generate_print_func(self, level=DEBUG): def prin(*args, end='\n'): if level >= LEVEL: strs = ' '.join([str(a) for a in args]) str_time = strftime("%Y-%m-%d %H:%M:%S", gmtime()) print('[' + _idx2str[level] + '][' + str_time + ']' + self.name, strs, end=end) open(os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../log.txt')), 'a').write( '[' + _idx2str[level] + '][' + str_time + ']' + self.name + strs + end ) return prin
[ { "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": "any_function_over_40_lines", "question": "Is any function in this file longer than 40 li...
3
src/utils/logger.py
Frozenmad/MetaDelta
''' Created on 15 Sep 2017 @author: gavin ''' from .basehandler import TcpHandler class netbios(TcpHandler): NAME = "NetBIOS Session" DESCRIPTION = '''Responds to NetBIOS session requests. To be used along side SMB handler.''' CONFIG = {} def __init__(self, *args): ''' Constructor ''' TcpHandler.__init__(self, *args) def base_handle(self): data = self.handle_request() if data[0] == "\x81": self.send_response(b"\x82\x00\x00\x00")
[ { "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
src/catcher/handlers/netbios.py
gavin-anders/callback-catcher
# Copyright 2019 Google LLC. 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. """TFT benchmark for Chicago Taxi dataset.""" from absl import flags from tfx.benchmarks import tft_benchmark_base from tfx.benchmarks.datasets.chicago_taxi import dataset from tensorflow.python.platform import test # pylint: disable=g-direct-tensorflow-import FLAGS = flags.FLAGS flags.DEFINE_integer("num_analyzers_wide", 10, "Number of analyzers in the TFT preprocessing function. " "Only used in `TFTBenchmarkChicagoTaxiWide`.") class TFTBenchmarkChicagoTaxi(tft_benchmark_base.TFTBenchmarkBase): def __init__(self, **kwargs): super().__init__(dataset=dataset.get_dataset(), **kwargs) class TFTBenchmarkChicagoTaxiWide(tft_benchmark_base.TFTBenchmarkBase): def __init__(self, **kwargs): super().__init__( dataset=dataset.get_wide_dataset(num_analyzers=self._num_analyzers()), **kwargs) def _num_analyzers(self): return (FLAGS.num_analyzers_wide if FLAGS.is_parsed() else FLAGS["num_analyzers_wide"].default) if __name__ == "__main__": test.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
tfx/benchmarks/tft_benchmark_chicago_taxi.py
avelez93/tfx
import requests from ebooks.provider.ebook import Ebook from ebooks.provider.ebook_provider import EbookProvider class WereadEbookProvider(EbookProvider): def __init__(self): self.url = 'https://weread.qq.com/web/search/global?' \ 'keyword={}&maxIdx={}&count=20' def get_ebooks(self, title, last_book_index, page_index): url = self.url.format(title, last_book_index) response = requests.get(url) if response.status_code != requests.codes.ok: raise Exception(response.text) body = response.json() books = body.get('books', []) ebooks = map(self.__convert_to_ebook, books) return list(filter(self.__is_valid_book, ebooks)) def __convert_to_ebook(self, book): book_info = book.get('bookInfo') if book_info.get('format') != 'epub' or book_info.get('soldout') == 1: return None ebook = Ebook() ebook.title = book_info.get('title', '') ebook.author = book_info.get('author', '') ebook.price = book_info.get('price', 0.0) ebook.cover = book_info.get('cover', '') ebook.abstract = book_info.get('intro', '') return ebook def __is_valid_book(self, book): return book is not None
[ { "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
ebooks/provider/weread.py
Frederick-S/ebooks-api
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. import asyncio import pytest import logging import json from utils import get_random_dict logger = logging.getLogger(__name__) logger.setLevel(level=logging.INFO) pytestmark = pytest.mark.asyncio # TODO: add tests for various application properties # TODO: is there a way to call send_c2d so it arrives as an object rather than a JSON string? @pytest.mark.describe("Device Client C2d") class TestSendMessage(object): @pytest.mark.it("Can receive C2D") async def test_send_message(self, client, service_helper, device_id, module_id, event_loop): message = json.dumps(get_random_dict()) received_message = None received = asyncio.Event() async def handle_on_message_received(message): nonlocal received_message, received logger.info("received {}".format(message)) received_message = message event_loop.call_soon_threadsafe(received.set) client.on_message_received = handle_on_message_received await service_helper.send_c2d(device_id, module_id, message, {}) await asyncio.wait_for(received.wait(), 10) assert received_message.data.decode("utf-8") == message
[ { "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
device_e2e/aio/test_c2d.py
anthonyvercolano/azure-iot-sdk-python
from typing import Match import cv2 as cv import numpy as np from numpy.core.fromnumeric import ndim ''' In this module, i will implement motion tracking with contour detection and contour drawing. ''' def histOfObjects(objects = []) : ''' Calculate the histograms of input objects. ''' objHists = [] for obj in objects: hsv_obj = cv.cvtColor(obj[0], cv.COLOR_BGR2HSV) objHist = cv.calcHist([hsv_obj], [0], None, [180], [0, 180]) cv.normalize(objHist, objHist, 0, 255, cv.NORM_MINMAX) objHists.append([objHist, obj[1]]) return objHists def track_motion2(frame, mask): ''' Frame is the original frame of the captured video. Mask is the mask from the backgoundsubtraction. ''' # Remove noice blur = cv.GaussianBlur(mask, (9,9), 0) # Remove false positives, with threshold _, thresh = cv.threshold(blur, 127, 255, cv.THRESH_BINARY) # Enhance moving object open = cv.morphologyEx(thresh, cv.MORPH_OPEN, None, iterations=3) close = cv.morphologyEx(open, cv.MORPH_CLOSE, None, iterations=6) dilate = cv.dilate(close, None, iterations=3) # Find objects with contour detection contours, hierarchy = cv.findContours(dilate, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE) # cv.drawContours(mask, contours, -1, (0,255,0), 50, hierarchy=hierarchy, maxLevel=1) # Iterate through objects, and draw rectangle around them for contour in contours: # get rectangle/object position (x,y,w,h) = cv.boundingRect(contour) # filter out noice if cv.contourArea(contour) > 300: # draw rectangle on original frame cv.rectangle(frame, (x,y), (x+w, y+h), (0,0,255), 2) # print out detected moving objects for debug purpouses # print(len(vectors)) # return finale mask image for debug purposes return dilate
[ { "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": "no_function_exceeds_5_params", "question": "Does every function in this file take 5 or fewer parameters (ex...
3
src_cam/track_object.py
Pecneb/RaspberryPI
class Spam: def eggs(self): assert False def eggs_and_ham(self): assert False
[ { "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
python/testData/create_tests/create_tst_class.expected_pytest_3k.py
tgodzik/intellij-community
from discord.ext import commands import discord class EphemeralCounterBot(commands.Bot): def __init__(self): super().__init__() async def on_ready(self): print(f'Logged in as {self.user} (ID: {self.user.id})') print('------') # Define a simple View that gives us a counter button class Counter(discord.ui.View): # Define the actual button # When pressed, this increments the number displayed until it hits 5. # When it hits 5, the counter button is disabled and it turns green. # note: The name of the function does not matter to the library @discord.ui.button(label='0', style=discord.ButtonStyle.red) async def count(self, button: discord.ui.Button, interaction: discord.Interaction): number = int(button.label) if button.label else 0 if number + 1 >= 5: button.style = discord.ButtonStyle.green button.disabled = True button.label = str(number + 1) # Make sure to update the message with our updated selves await interaction.response.edit_message(view=self) # Define a View that will give us our own personal counter button class EphemeralCounter(discord.ui.View): # When this button is pressed, it will respond with a Counter view that will # give the button presser their own personal button they can press 5 times. @discord.ui.button(label='Click', style=discord.ButtonStyle.blurple) async def receive(self, button: discord.ui.Button, interaction: discord.Interaction): # ephemeral=True makes the message hidden from everyone except the button presser await interaction.response.send_message('Enjoy!', view=Counter(), ephemeral=True) bot = EphemeralCounterBot() @bot.slash() async def counter(ctx: commands.Context): """Starts a counter for pressing.""" await ctx.send('Press!', view=EphemeralCounter()) bot.run('token')
[ { "point_num": 1, "id": "every_class_has_docstring", "question": "Does every class in this file have a docstring?", "answer": false }, { "point_num": 2, "id": "all_function_names_snake_case", "question": "Are all function names in this file written in snake_case?", "answer": true...
3
examples/views/ephemeral.py
NextChai/discord.py
from sys import stderr from time import sleep stderr.write("loading... ") def test__stderr__1(): sleep(0.25) stderr.write("Spoon!\n") def test__stderr__2(): sleep(0.25) stderr.write("Kilroy was here.\n") assert False stderr.write("done\n")
[ { "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
spikes/pytest/testdata/example/stderr_test.py
sjansen/mecha
"""Add ON DELETE CASCADE to task parents and owners Revision ID: d16c2ebe90cc Revises: 52729177a07c Create Date: 2017-05-21 14:11:15.173492 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'd16c2ebe90cc' down_revision = '52729177a07c' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_constraint('task_owner_id_fkey', 'task', type_='foreignkey') op.drop_constraint('task_parent_id_fkey', 'task', type_='foreignkey') op.create_foreign_key('task_parent_id_fkey', 'task', 'task', ['parent_id'], ['object_id'], ondelete='CASCADE') op.create_foreign_key('task_owner_id_fkey', 'task', 'user', ['owner_id'], ['object_id'], ondelete='CASCADE') # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_constraint('task_owner_id_fkey', 'task', type_='foreignkey') op.drop_constraint('task_parent_id_fkey', 'task', type_='foreignkey') op.create_foreign_key('task_parent_id_fkey', 'task', 'task', ['parent_id'], ['object_id']) op.create_foreign_key('task_owner_id_fkey', 'task', 'user', ['owner_id'], ['object_id']) # ### end Alembic commands ###
[ { "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
migrations/versions/d16c2ebe90cc_on_delete_cascade.py
toastwaffle/LiME
from __future__ import absolute_import, unicode_literals import os from django.core.exceptions import ImproperlyConfigured def get_env(name, default=None): """Get the environment variable or return exception""" if name in os.environ: return os.environ[name] if default is not None: return default error_msg = "Set the {} env variable".format(name) raise ImproperlyConfigured(error_msg) def get_env_bool(name, default=None): return get_env(name, default=default) == "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": "no_function_exceeds_5_params", "question": "Does every function in this file take 5 or fewer parameters (...
3
{{cookiecutter.project_name}}/src/core/settings/__init__.py
techquila/Wagtail-Boilerplate
from django.db import models from django.contrib.auth import get_user_model from django.urls import reverse # Create your models here. class Snack(models.Model): title = models.CharField(max_length=64) purchaser = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) description = models.TextField() def __str__(self) -> str: return self.title def get_absolute_url(self): return reverse("snack_detail", args=[str(self.pk)])
[ { "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
snacks/models.py
anas-abusaif/djangox
# Copyright (c) 2018 PaddlePaddle Authors. 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. from __future__ import print_function import unittest from test_dist_base import TestDistBase class TestDistMnist2x2Lars(TestDistBase): def _setup_config(self): self._sync_mode = True self._use_reduce = False def test_se_resnext(self): self.check_with_place("dist_mnist_lars.py", delta=1e-5) if __name__ == "__main__": unittest.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": "more_functions_than_classes", "question": "Does this file define more functions than classes?", "answer": true }...
3
python/paddle/fluid/tests/unittests/test_dist_mnist_lars.py
L-Net-1992/Paddle
from pathlib import Path import matplotlib import matplotlib.pyplot as plt import numpy as np import pytest import ctd matplotlib.use("Agg") data_path = Path(__file__).parent.joinpath("data") def _assert_is_valid_plot_return_object(objs): if isinstance(objs, np.ndarray): for el in objs.flat: assert isinstance(el, plt.Axes), ( "one of 'objs' is not a " "matplotlib Axes instance, " "type encountered {0!r}" "".format(el.__class__.__name__) ) else: assert isinstance(objs, (plt.Artist, tuple, dict)), ( "objs is neither an ndarray of Artist instances nor a " 'single Artist instance, tuple, or dict, "objs" is a {0!r} ' "".format(objs.__class__.__name__) ) def _check_plot_works(f, *args, **kwargs): ax = f(*args, **kwargs) _assert_is_valid_plot_return_object(ax) plt.close() # BasicPlotting. @pytest.fixture def xbt(): yield ctd.from_edf(data_path.joinpath("XBT.EDF.zip")) plt.close("all") @pytest.fixture def fsi(): yield ctd.from_fsi(data_path.joinpath("FSI.txt.gz"), skiprows=9) plt.close("all") @pytest.fixture def cnv(): yield ctd.from_cnv(data_path.joinpath("small.cnv.bz2")) plt.close("all") def test_xbt_plot(xbt): _check_plot_works(xbt["temperature"].plot_cast) def test_cnv_temperature(cnv): _check_plot_works(cnv["t090C"].plot_cast)
[ { "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
tests/test_plotting.py
CoastalHydrodynamicsLab/python-ctd
# -*- coding: utf-8 -*- #import sys import json class CinToJson(object): def __init__(self): pass def CinToJson(self): return self #def _file_get_contents(self,filename): # return open(filename).read() def _find_between(self, s, first, last ): start = s.index( first ) + len( first ) end = s.index( last, start ) return s[start:end] def run(self,outputfile_mainname,source_file,donothing): output = {} output["chardefs"] = {} data = open(source_file).read() char_default_data = self._find_between(data,"%chardef begin","%chardef end") char_default_data = str(char_default_data).strip() m = char_default_data.split("\n") for k in m: value = str(k).strip() if value =="": continue d = value.split(" ") if len(d)!=2: continue #print(d) #print(d[0]) d[0] = d[0].strip() d[1] = d[1].strip() if output["chardefs"].has_key(d[0])==False: output["chardefs"][d[0]] = [] output["chardefs"][d[0]].append(d[1]) #sys.exit() data = json.dumps(output,indent=4, sort_keys=True, ensure_ascii=False) #print(data) #sys.exit() #write file f = open(outputfile_mainname+".json", 'wb') f.write(data)
[ { "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
linux/cintojson.py
sqohapoe/CQOSJ_LIU
from .lib.symengine_wrapper import ( have_mpfr, have_mpc, have_flint, have_piranha, have_llvm, I, E, pi, oo, zoo, nan, Symbol, Dummy, S, sympify, SympifyError, Integer, Rational, Float, Number, RealNumber, RealDouble, ComplexDouble, add, Add, Mul, Pow, function_symbol, Max, Min, DenseMatrix, Matrix, ImmutableMatrix, ImmutableDenseMatrix, MutableDenseMatrix, MatrixBase, Basic, DictBasic, symarray, series, diff, zeros, eye, diag, ones, Derivative, Subs, expand, has_symbol, UndefFunction, Function, latex, have_numpy, true, false, Equality, Unequality, GreaterThan, LessThan, StrictGreaterThan, StrictLessThan, Eq, Ne, Ge, Le, Gt, Lt, And, Or, Not, Nand, Nor, Xor, Xnor, perfect_power, integer_nthroot, isprime, sqrt_mod, Expr, cse, count_ops, ccode, Piecewise, Contains, Interval, FiniteSet, FunctionSymbol as AppliedUndef, golden_ratio as GoldenRatio, catalan as Catalan, eulergamma as EulerGamma ) from .utilities import var, symbols from .functions import * from .printing import init_printing if have_mpfr: from .lib.symengine_wrapper import RealMPFR if have_mpc: from .lib.symengine_wrapper import ComplexMPC if have_numpy: from .lib.symengine_wrapper import (Lambdify, LambdifyCSE) def lambdify(args, exprs, **kwargs): return Lambdify(args, *exprs, **kwargs) __version__ = "0.4.0" def test(): import pytest import os return not pytest.cmdline.main( [os.path.dirname(os.path.abspath(__file__))])
[ { "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
symengine/__init__.py
Meldanya/symengine.py
from datetime import timedelta, date def req_date(local_date): if isinstance(local_date, str): d, m, y = local_date.split('.') return '{0}-{1}-{2}'.format(y, m, d) elif isinstance(local_date, date): return local_date.strftime('%Y-%m-%d') else: return local_date def req_timedelta(arg): if isinstance(arg, timedelta): return arg else: if isinstance(arg, str): parts = arg.split(':') try: res = timedelta(hours=int(parts[0]), minutes=int(parts[1])) except ValueError: res = timedelta(0) return res else: return timedelta(0) def yesterday_local(): return (date.today() - timedelta(days=1)).strftime("%d.%m.%Y") def stat_timedelta_for_report(time_delta, round_to_hour=True): if time_delta: sec = time_delta.total_seconds() hours, remainder = divmod(sec, 3600) if round_to_hour: if remainder >= 1800: hours += 1 return str(int(hours)) minutes, remainder = divmod(remainder, 60) return "{0:,d}:{1:02}".format(int(hours), int(minutes)).replace(',',' ') else: return '-' def custom_redirect(url_name, *args, **kwargs): from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect from django.utils.http import urlencode url = reverse(url_name, args=args) params = urlencode(kwargs) return HttpResponseRedirect(url + "?%s" % params)
[ { "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
etools/apps/uptime/utils.py
Igelinmist/etools
import pandas as pd import os from constants import LOCAL_PATH, APARTMENTS_FILENAME def basic_write(df): df.to_csv(os.path.join(LOCAL_PATH, APARTMENTS_FILENAME)) def basic_read(): return pd.read_csv(os.path.join(LOCAL_PATH, APARTMENTS_FILENAME))
[ { "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
code/handlers/local_handler.py
hfiuza/ApartmentFinder
import unittest from .serializers import TweetSerializer from tweeter.models import Tweet from django.contrib.auth.models import User from datetime import datetime from rest_framework import serializers class TestUsers(unittest.TestCase): def test_user_creation(self): user=User(username='���') self.assertEqual(user.username,'���') user2=User() self.assertEqual(user2.username,'') def test_user_permission(self): pass class TestTweets(unittest.TestCase): def test_tweet_creation(self): time = datetime.now() tweet = Tweet(text = "Hi! I'm Bob :)", user=User(username='bob'), timestamp = time) self.assertEqual(tweet.text, "Hi! I'm Bob :)") self.assertEqual(tweet.user.username, 'bob') self.assertEqual(tweet.timestamp, time) time = datetime(2010,10,10,10,10) tweet = Tweet(text = " ", user=User(username='amy'), timestamp = time) self.assertEqual(tweet.text, " ") self.assertEqual(tweet.user.username, 'amy') self.assertEqual(tweet.timestamp, time) def test_tweet_creation_notunicode(self): time = datetime(year=2010,month=10,day=10,hour=10,minute=10,second=10) tweet = Tweet(text = "Hi� Ý'm ßoß ձ", user=User(username='ßoß'), timestamp = time) self.assertEqual(tweet.text, "Hi� Ý'm ßoß ձ") self.assertEqual(tweet.user.username, 'ßoß') self.assertEqual(tweet.timestamp, time) def test_serializer_validation(self): ts = TweetSerializer() self.assertRaises(serializers.ValidationError,ts.validate_text,"hi!") self.assertRaises(serializers.ValidationError,ts.validate_text," ") self.assertRaises(serializers.ValidationError,ts.validate_text," " * 71) self.assertEqual(ts.validate_text(" " * 70)," "* 70)
[ { "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": true ...
3
tweeter/tests.py
luabud/tweeter3
#!/usr/bin/env python3 # # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Big number routines. This file is copied from python-bitcoinlib. """ import struct # generic big endian MPI format def bn_bytes(v, have_ext=False): ext = 0 if have_ext: ext = 1 return ((v.bit_length()+7)//8) + ext def bn2bin(v): s = bytearray() i = bn_bytes(v) while i > 0: s.append((v >> ((i-1) * 8)) & 0xff) i -= 1 return s def bin2bn(s): l = 0 for ch in s: l = (l << 8) | ch return l def bn2mpi(v): have_ext = False if v.bit_length() > 0: have_ext = (v.bit_length() & 0x07) == 0 neg = False if v < 0: neg = True v = -v s = struct.pack(b">I", bn_bytes(v, have_ext)) ext = bytearray() if have_ext: ext.append(0) v_bin = bn2bin(v) if neg: if have_ext: ext[0] |= 0x80 else: v_bin[0] |= 0x80 return s + ext + v_bin def mpi2bn(s): if len(s) < 4: return None s_size = bytes(s[:4]) v_len = struct.unpack(b">I", s_size)[0] if len(s) != (v_len + 4): return None if v_len == 0: return 0 v_str = bytearray(s[4:]) neg = False i = v_str[0] if i & 0x80: neg = True i &= ~0x80 v_str[0] = i v = bin2bn(v_str) if neg: return -v return v # groom-specific little endian format, with implicit size def mpi2vch(s): r = s[4:] # strip size r = r[::-1] # reverse string, converting BE->LE return r def bn2vch(v): return bytes(mpi2vch(bn2mpi(v))) def vch2mpi(s): r = struct.pack(b">I", len(s)) # size r += s[::-1] # reverse string, converting LE->BE return r def vch2bn(s): return mpi2bn(vch2mpi(s))
[ { "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
test/functional/test_framework/bignum.py
nhoussay/groom
from flask import render_template from app import app @app.errorhandler(404) def page_not_found(e): return render_template('http404.html'), 404 @app.errorhandler(403) def page_not_found(e): return render_template('http403.html'), 403 @app.errorhandler(500) def page_not_found(e): return render_template('http500.html'), 500
[ { "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
app/views/errorhandler_views.py
c1c1/network-config-generator
import vaex import vaex.ml import tempfile import vaex.ml.datasets features = ['petal_length', 'petal_width', 'sepal_length', 'sepal_width'] def test_pca(): ds = vaex.ml.datasets.load_iris() pca = vaex.ml.PCA(features=features, n_components=2) pca.fit(ds) ds1 = pca.transform(ds) path = tempfile.mktemp('.yaml') pipeline = vaex.ml.Pipeline([pca]) pipeline.save(path) pipeline = vaex.ml.Pipeline() pipeline.load(path) ds2 = pipeline.transform(ds) assert ds1.virtual_columns['PCA_1'] == ds2.virtual_columns['PCA_1'] path = tempfile.mktemp('.yaml') pipeline = vaex.ml.Pipeline([ds1.ml.state_transfer()]) pipeline.save(path) pipeline = vaex.ml.Pipeline() pipeline.load(path) ds3 = pipeline.transform(ds) assert ds1.virtual_columns['PCA_1'] == ds3.virtual_columns['PCA_1'] def test_selections(): ds = vaex.ml.datasets.load_iris() ds.select('class_ == 1') count1 = ds.count(selection=True) path = tempfile.mktemp('.yaml') pipeline = vaex.ml.Pipeline([ds.ml.state_transfer()]) pipeline.save(path) print(path) pipeline = vaex.ml.Pipeline() pipeline.load(path) ds2 = pipeline.transform(ds) assert ds2.count(selection=True) == count1 def test_state_transfer(): ds = vaex.ml.datasets.load_iris() ds['test'] = ds.petal_width * ds.petal_length test_values = ds.test.evaluate() state_transfer = ds.ml.state_transfer() # clean dataset ds = vaex.ml.datasets.load_iris() ds = state_transfer.transform(ds) assert test_values.tolist() == ds.test.evaluate().tolist() ds1, ds2 = ds.split(0.5) state_transfer = ds1.ml.state_transfer() path = tempfile.mktemp('.yaml') pipeline = vaex.ml.Pipeline([state_transfer]) pipeline.save(path)
[ { "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": fal...
3
tests/ml/pipeline_test.py
cyrusradfar/vaex
from django import template from django.utils.safestring import mark_safe register = template.Library() @register.filter(name='hoursmins') def hoursmins(value): if value == None or value == "": return "" s = int(value) * 60 hours, remainder = divmod(s, 3600) minutes, seconds = divmod(remainder, 60) return "%d:%02d" % (hours,minutes) @register.filter(name='river') def river(value): ret = "" parts = value.split("<") for part in parts: if ">" in part: ret += "".join(part.split(">")[1:]) else: ret += part if len(ret) > 500: ret = ret[:500] ret = ret[:ret.rfind(" ")] + "&hellip;" return mark_safe(ret) @register.filter(name='subscription_name') def subscription_name(post, subscription_map): return subscription_map[post.source.id] @register.filter(name='starstyle') def starstyle(post, user): if post.savedpost_set.filter(user=user).count() > 0: return "fas" else: return "far"
[ { "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
ft/templatetags/ft_tags.py
xurble/FeedThing
import logging BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8) #The background is set with 40 plus the number of the color, and the foreground with 30 #These are the sequences need to get colored ouput RESET_SEQ = "\033[0m" COLOR_SEQ = "\033[1;%dm" BOLD_SEQ = "\033[1m" def formatter_message(message, use_color = True): if use_color: message = message.replace("$RESET", RESET_SEQ).replace("$BOLD", BOLD_SEQ) else: message = message.replace("$RESET", "").replace("$BOLD", "") return message COLORS = { 'DEBUG': BLUE, 'INFO': GREEN, 'WARNING': YELLOW, 'ERROR': MAGENTA, 'CRITICAL': RED, } class ColoredFormatter(logging.Formatter): def __init__(self, msg, use_color = True): logging.Formatter.__init__(self, msg) self.use_color = use_color # https://docs.python.org/ja/3/library/logging.html#logging.LogRecord def format(self, record): levelname = record.levelname if self.use_color and levelname in COLORS: # levelname_color = COLOR_SEQ % (30 + COLORS[levelname]) + levelname + RESET_SEQ # record.levelname = levelname_color # record.msg = COLOR_SEQ % (30 + COLORS[levelname]) + record.msg + RESET_SEQ # for key in ['name', 'levelname', 'pathname', 'lineno', 'msg', 'args', 'exc_info', 'func', 'sinfo']: # for key in ['name', 'levelname', 'pathname', 'lineno', 'msg', 'args', 'exc_info']: for key in ['name', 'levelname', 'pathname', 'msg']: setattr(record, key, COLOR_SEQ % (30 + COLORS[levelname]) + str(getattr(record, key)) + RESET_SEQ) return logging.Formatter.format(self, record)
[ { "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
src/log/ColoredFormatter.py
ytyaru/Python.Tsv2HtmlTable.20201022074246
import yaml import os import pytest from ..greeter import greet def read_fixture(): with open(os.path.join(os.path.dirname(__file__), 'fixtures', 'samples.yaml')) as fixtures_file: fixtures = yaml.load(fixtures_file) return fixtures @pytest.mark.parametrize("fixture", read_fixture()) def test_greeter(fixture): answer = fixture.pop('answer') assert greet(**fixture) == answer
[ { "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
ch04packaging/greetings/greetings/test/test_greeter.py
ashnair1/rsd-engineeringcourse
""" source - defines and describes a source """ from domain.base import Base class RecursiveFragment(Base): title = None lead = None text = None fragments = None def __init__(self, identifier, title, lead=None, text=None, fragments=[]): super().__init__(identifier) self.title = title self.lead = lead self.text = text self.fragments = [] self.add(*fragments) def add(self, *fragments): self.fragments.extend(fragments) return self def get_title(self): return f"{self.identifier} - {self.title}"
[ { "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
python/domain/document/model/recursive_fragment.py
ICTU/document-as-code
import matplotlib.pyplot as plt import numpy as np light="#FFFCDC" light_highlight="#FEF590" mid="#FDED2A" mid_highlight="#f0dc05" dark="#EECA02" dark_highlight="#BB9700" green="#00FF00" light_grey="#DDDDDD" def is_sorted(a): '''Check if numpy 1d-array is sorted ''' return np.all(a[:-1] <= a[1:]) def ribbon_plot(x, fx, ax=None,zorder=0): '''Plot a ribbon plot for regression and similar. Plot consists of quantiles (by 10%) of a variate (fx) as a function of covariate (x). x has shape (n, ) fx has shape (N,n) ''' if ax is None: ax = plt.gca() if not is_sorted(x): print('Sorting') arr2D = np.concatenate([np.expand_dims(x,axis=0),fx],axis=0) sortedArr = arr2D [ :, arr2D[0].argsort()] x = sortedArr[0,:] fx = sortedArr[1:,:] probs = [10, 20, 30, 40, 50, 60, 70, 80, 90] perc_interv=np.percentile(fx, probs, axis=0) ax.fill_between(x,perc_interv[0,:],perc_interv[8,:],color=light,zorder=zorder) ax.fill_between(x,perc_interv[1,:],perc_interv[7,:],color=light_highlight,zorder=zorder) ax.fill_between(x,perc_interv[2,:],perc_interv[6,:],color=mid,zorder=zorder) ax.fill_between(x,perc_interv[3,:],perc_interv[5,:],color=mid_highlight,zorder=zorder) ax.plot(x,perc_interv[4,:],color=dark,zorder=zorder) return(ax)
[ { "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
Data Analytics/Utilities/DA_tools.py
rafalmularczyk/public_lectures
# -*- coding: utf-8 -*- # @Time : 2019/3/19 0019 16:25 # @Author : __Yanfeng # @Site : # @File : search_indexes.py # @Software: PyCharm from haystack import indexes from .models import Post class PostIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) def get_model(self): return Post def index_queryset(self, using=None): return self.get_model().latest_posts()
[ { "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
blog/search_indexes.py
GITliyanfeng/blog-django
def root(classes): """get all root classnames """ return [c for c in classes if c.startswith("h-")] def properties(classes): """get all property (p-*, u-*, e-*, dt-*) classnames """ return [c.partition("-")[2] for c in classes if c.startswith("p-") or c.startswith("u-") or c.startswith("e-") or c.startswith("dt-")] def text(classes): """get text property (p-*) names """ return [c.partition("-")[2] for c in classes if c.startswith("p-")] def url(classes): """get URL property (u-*) names """ return [c.partition("-")[2] for c in classes if c.startswith("u-")] def datetime(classes): """get datetime property (dt-*) names """ return [c.partition("-")[2] for c in classes if c.startswith("dt-")] def embedded(classes): """get embedded property (e-*) names """ return [c.partition("-")[2] for c in classes if c.startswith("e-")]
[ { "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
mf2py/mf2_classes.py
kevinmarks/mentiontech
from __future__ import unicode_literals import datetime from chatterbot.input import InputAdapter from chatterbot.conversation import Statement class Mailgun(InputAdapter): """ Get input from Mailgun. """ def __init__(self, **kwargs): super(Mailgun, self).__init__(**kwargs) # Use the bot's name for the name of the sender self.name = kwargs.get('name') self.from_address = kwargs.get('mailgun_from_address') self.api_key = kwargs.get('mailgun_api_key') self.endpoint = kwargs.get('mailgun_api_endpoint') def get_email_stored_events(self): import requests yesterday = datetime.datetime.now() - datetime.timedelta(1) return requests.get( '{}/events'.format(self.endpoint), auth=('api', self.api_key), params={ 'begin': yesterday.isoformat(), 'ascending': 'yes', 'limit': 1 } ) def get_stored_email_urls(self): response = self.get_email_stored_events() data = response.json() for item in data.get('items', []): if 'storage' in item: if 'url' in item['storage']: yield item['storage']['url'] def get_message(self, url): import requests return requests.get( url, auth=('api', self.api_key) ) def process_input(self, statement): urls = self.get_stored_email_urls() url = list(urls)[0] response = self.get_message(url) message = response.json() text = message.get('stripped-text') return Statement(text)
[ { "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
venv/lib/python3.6/site-packages/chatterbot/input/mailgun.py
HackBots1111/flask-server-bot
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # Copyright (c) Megvii, Inc. and its affiliates. import os import torch.nn as nn from yolox.exp import Exp as MyExp class Exp(MyExp): def __init__(self): super(Exp, self).__init__() self.depth = 0.33 self.width = 0.25 self.scale = (0.5, 1.5) self.random_size = (10, 20) self.test_size = (416, 416) self.exp_name = os.path.split(os.path.realpath(__file__))[1].split(".")[0] self.enable_mixup = False def get_model(self, sublinear=False): def init_yolo(M): for m in M.modules(): if isinstance(m, nn.BatchNorm2d): m.eps = 1e-3 m.momentum = 0.03 if "model" not in self.__dict__: from yolox.models import YOLOX, YOLOPAFPN, YOLOXHead in_channels = [256, 512, 1024] # NANO model use depthwise = True, which is main difference. backbone = YOLOPAFPN(self.depth, self.width, in_channels=in_channels, depthwise=True) head = YOLOXHead(self.num_classes, self.width, in_channels=in_channels, depthwise=True) self.model = YOLOX(backbone, head) self.model.apply(init_yolo) self.model.head.initialize_biases(1e-2) return self.model
[ { "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
exps/default/nano.py
itec-hust/MusicYOLO
class mystr(): def get_string(self): self.s=input("Enter the string") def pr_string(abc): val=abc.s print(val.upper()) p=mystr() p.get_string() p.pr_string()
[ { "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
pythonclass.py
bjoffficial/Python
import os import pickle import json import numpy as np import matplotlib.pyplot as plt import seaborn as sns sns.set() def scatterplot(attribute_idx, table, epsilons, label, ax): ys = [] xs = [] for eps in epsilons: row = table[eps] y = row[attribute_idx] ys.append(y) xs.append(float(eps)) ax.scatter(x=xs, y=ys, label=label) def main(): artifacts_dir = 'artifacts/attributes_experiment/' epsilons = ['0.001', '0.005', '0.01', '0.05'] attributes = ['Smiling', 'Male', 'Wearing_Lipstick', 'Young'] mean_table = {} std_table = {} for eps in epsilons: mean_table[eps] = [] std_table[eps] = [] for attr in attributes: gen_secret_accs = [] for i in range(5): results_path = os.path.join(artifacts_dir, '{}_eps_{}'.format(attr, eps), str(i), 'results.json') with open(results_path, 'r') as f: res = json.load(f) gen_secret_accs.append(res['gen_secret_acc'] * 100) mean_table[eps].append(np.mean(gen_secret_accs)) std_table[eps].append(np.std(gen_secret_accs)) plt.rcParams["mathtext.fontset"] = "cm" fig, ax = plt.subplots() for i, attr in enumerate(attributes): scatterplot(i, mean_table, epsilons, label=attr, ax=ax) plt.ylabel("Fool fixed classifier [%]") plt.xlabel("$\epsilon$") plt.legend(loc="lower right") plt.savefig("fool_fixed_classifier.pdf") if __name__ == '__main__': 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": "every_function_under_20_lines", "question": "Is every function in this file shorter than 20 lines?", "answer": fal...
3
vis/create_attributes_experiment_plot.py
johnmartinsson/adversarial-representation-learning
from invoke import task @task def clean(ctx): """Remove virtual environement""" ctx.run("pipenv --rm", warn=True) @task def init(ctx): """Install production dependencies""" ctx.run("pipenv install --deploy") @task def init_dev(ctx): """Install development dependencies""" ctx.run("pipenv install --dev")
[ { "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": "all_function_names_snake_case", "question": "Are all function names in this file written in snake_case?",...
3
tasks/env.py
Lee-W/pycontw-postevent-report-generator
import os from subliminal import download_best_subtitles, save_subtitles from subliminal.video import Episode from subliminal.core import search_external_subtitles from babelfish.language import Language class Subtitler: def __init__(self, languages, providers): self.languages = languages self.providers = providers def subtitle(self, episodes): # Parse babelfish languages bb_lang = {Language.fromietf(l) for l in self.languages} # Create subliminal episode set sub_episodes = set() for episode in episodes: ep_path = os.path.join(episode['dir'], episode['filename']) sub_episode = Episode.fromguess(ep_path, episode) # Look for external subtitles (not done automatically, apparently) sub_episode.subtitle_languages |= set(search_external_subtitles(sub_episode.name).values()) sub_episodes.add(sub_episode) # download subtitles in the specified language subl_subtitles = download_best_subtitles(sub_episodes, bb_lang, providers=self.providers) for video, subtitles in subl_subtitles.items(): save_subtitles(video, subtitles) # save subtitle languages in episode dict
[ { "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
back/fs/subtitler.py
rkohser/gustaf2
import unittest """ 1.5 One Away There are three types of edits that can be performed on strings: insert a character, remove a character, or replace a character. Given two strings, write a function to check if they are one edit (or zero edits) away. EXAMPLE pale, ple -> true pales, pale -> true pale, bale -> true pale, bae -> false """ def is_one_away(str1, str2): len1 = len(str1) len2 = len(str2) if len1 == len2: return is_one_char_replaceable(str1, str2) elif len1 + 1 == len2: return is_one_char_insertable(str1, str2) elif len2 + 1 == len1: return is_one_char_insertable(str2, str1) else: return False def is_one_char_replaceable(str1, str2): found_diff = False for c1, c2 in zip(str1, str2): if c1 != c2: if found_diff: return False found_diff = True return True def is_one_char_insertable(str1, str2): # assume length of str1 < str2 index1 = 0 index2 = 0 found_diff = False while index1 < len(str1) and index2 < len(str2): if str1[index1] != str2[index2]: if found_diff: return False found_diff = True index2 += 1 else: index1 += 1 index2 += 1 return True class Test(unittest.TestCase): test_cases = [ # add test cases here, ("test-case", True) ("pale", "ple", True), ("pales" ,"pale", True), ("pale" ,"pales", True), ("pale", "bale", True), ("pale", "bae", False), ("pale", "palesd", False), ("pale", "btle", False), ] test_functions = [ # add testing functions here is_one_away, ] def test(self): for text1, text2, expected in self.test_cases: for test_func in self.test_functions: try: assert (test_func(text1, text2) == expected), "Failed!" except AssertionError as e: e.args += (test_func.__name__, text1, text2, "should be " + str(expected)) raise 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": "all_params_annotated", "question": "Does every function parameter in this file have a type annotation (excluding self/c...
3
ch01_arrays_and_strings/1.5_one-away.py
appletreeisyellow/cracking-the-coding-interview
import numpy from chainer import cuda from chainer import function from chainer.utils import type_check class Concat(function.Function): """Concatenate multiple tensors towards specified axis.""" # concat along the channel dimension by default def __init__(self, axis=1): self.axis = axis def check_type_forward(self, in_types): type_check.expect(in_types.size() > 0) type_check.expect(in_types[0].ndim > type_check.Variable(self.axis, 'axis')) ndim = in_types[0].ndim.eval() for i in range(1, in_types.size().eval()): type_check.expect( in_types[0].dtype == in_types[i].dtype, in_types[0].ndim == in_types[i].ndim, ) for d in range(0, ndim): if d == self.axis: continue type_check.expect(in_types[0].shape[d] == in_types[i].shape[d]) def forward(self, xs): xp = cuda.get_array_module(*xs) return xp.concatenate(xs, axis=self.axis), def backward(self, xs, gy): xp = cuda.get_array_module(*xs) sizes = numpy.array([x.shape[self.axis] for x in xs[:-1]]).cumsum() return xp.split(gy[0], sizes, axis=self.axis) def concat(xs, axis=1): """Concatenates given variables along an axis. Args: xs (tuple of Variables): Variables to be concatenated. axis (int): Axis that the input arrays are concatenated along. Returns: ~chainer.Variable: Output variable. """ return Concat(axis=axis)(*xs)
[ { "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_params_annotated", "question": "Does every function parameter in this file have a type annotation (excluding se...
3
chainer/functions/array/concat.py
ytoyama/yans_chainer_hackathon
from NewDeclarationInQueue.processfiles.customprocess.text_with_special_ch import TextWithSpecialCharacters class SearchTextLineParameter: """ Defines the parameters to search a line of text in the JSON returned by the Azure service """ start_with_text: TextWithSpecialCharacters contains_words: list all_words: bool def __init__(self, start_with_text: TextWithSpecialCharacters, contains_words: list, all_words: bool): """ Initialize the class Args: start_with_text (str): text with which the line starts contains_words (list): list of words that are contained in the line all_words (bool): if the two previous condition (start and contains) must be both true or only one """ self.start_with_text = start_with_text self.contains_words = contains_words self.all_words = all_words def check_start(self, scompare: str) -> bool: return self.start_with_text.startswith(scompare) def check_contains(self, scompare: str) -> bool: return self.start_with_text.contains(scompare) def check_contains(self, scompare: str) -> bool: bresult = True for word in self.contains_words: bok = word.contains(scompare) bresult = (bresult or bok) if self.all_words == False else (bresult and bok) return bresult def to_string(self): return self.start_with_text.main_string + ' - ' + \ (",".join([x.main_string for x in self.contains_words]) if self.contains_words is not None else '') + \ ' - ' + str(self.all_words)
[ { "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
NewDeclarationInQueue/processfiles/customprocess/search_text_line_parameter.py
it-pebune/ani-research-data-extraction
from pymoo.model.problem import Problem class MyProblem(Problem): def __init__(self): super().__init__(n_var=1, n_obj=2, n_constr=0, elementwise_evaluation=True) def _evaluate(self, x, out, *args, **kwargs): # print("Evaluation") s = x[0] s.eval_fitness() # print(s.fitness) # print("Eval %s fitness %f" %(str(s.states), s.fitness)) # print("novelty", s.novelty) out["F"] = [s.fitness, s.novelty] # out["G"] = 4-s.fitness*(-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": "more_functions_than_classes", "question": "Does this file define more functions than classes?", "answ...
3
RQ3/Autonomous_robot/AmbieGen_ran/MyProblem.py
dgumenyuk/Environment_generation
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from authentication.socialaccount.tests import OAuth2TestsMixin from authentication.tests import MockedResponse, TestCase from .provider import MailRuProvider class MailRuTests(OAuth2TestsMixin, TestCase): provider_id = MailRuProvider.id def get_mocked_response(self, verified_email=True): return MockedResponse(200, """ [ { "uid": "15410773191172635989", "first_name": "Евгений", "last_name": "Маслов", "nick": "maslov", "email": "emaslov@mail.ru", "sex": 0, "birthday": "15.02.1980", "has_pic": 1, "pic": "http://avt.appsmail.ru/mail/emaslov/_avatar", "pic_small": "http://avt.appsmail.ru/mail/emaslov/_avatarsmall", "pic_big": "http://avt.appsmail.ru/mail/emaslov/_avatarbig", "link": "http://my.mail.ru/mail/emaslov/", "referer_type": "", "referer_id": "", "is_online": 1, "friends_count": 145, "is_verified": 1, "vip" : 0, "app_installed": 1, "location": { "country": { "name": "Россия", "id": "24" }, "city": { "name": "Москва", "id": "25" }, "region": { "name": "Москва", "id": "999999" } } }]""") # noqa def get_login_response_json(self, with_refresh_token=True): # FIXME: This is not an actual response. I added this in order # to get the test suite going but did not verify to check the # exact response being returned. return '{"access_token": "testac", "uid": "weibo", "refresh_token": "testrf", "x_mailru_vid": "1"}' # noqa
[ { "point_num": 1, "id": "any_function_over_40_lines", "question": "Is any function in this file longer than 40 lines?", "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
authentication/socialaccount/providers/mailru/tests.py
vo0doO/pydj-persweb