source
string
points
list
n_points
int64
path
string
repo
string
import heapq class PriorityQueue: """ Defines a pq. """ class Node: """ A node for the priority queue. """ def __init__(self, priority, obj): self.priority = priority self.obj = obj def __lt__(self, other): return self.priority < other.priority def __init__(self): self.pq = [] def queue(self, priority, node): heapq.heappush(self.pq, PriorityQueue.Node(priority, node)) def pop(self): return heapq.heappop(self.pq).obj def is_empty(self): return len(self.pq) == 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": "has_multiple_inheritance", "question": "Does any class in this file use multiple inheritance?", "answer": ...
3
chess/utils.py
thkim1011/chess-ai
from numpy import array from retry import retry from litai import ArticleScorer def test_scoring(): @retry(tries=10) def score_fun(): scorer = ArticleScorer(database='data/example.db') scorer.score( scores_table='mouse', pos_keywords='mouse', neg_keywords='fish', min_score=None, rand_factor=0, ) df = scorer.search(scores_table='mouse', min_score=0.5) term_freq = [ array([ df[field].str.contains(term).to_numpy() for field in ['Title', 'Abstract', 'Keywords'] ]).any(axis=0).mean() for term in ['mouse', 'fish', 'mice', 'water'] ] assert(term_freq[0] >= 0.5) assert(term_freq[1] <= 0.1) assert(term_freq[2] >= 0.25) assert(term_freq[3] <= 0.1) score_fun()
[ { "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/score_test.py
lakes-legendaries/litai
#! /usr/bin/env python # Copyright (c) 2021 Uber Technologies, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== from ludwig.datasets.base_dataset import BaseDataset, DEFAULT_CACHE_LOCATION from ludwig.datasets.mixins.kaggle import KaggleDownloadMixin from ludwig.datasets.mixins.load import CSVLoadMixin from ludwig.datasets.mixins.process import IdentityProcessMixin from ludwig.datasets.registry import register_dataset def load(cache_dir=DEFAULT_CACHE_LOCATION, split=False, kaggle_username=None, kaggle_key=None): dataset = WalmartRecruiting(cache_dir=cache_dir, kaggle_username=kaggle_username, kaggle_key=kaggle_key) return dataset.load(split=split) @register_dataset(name="walmart_recruiting") class WalmartRecruiting(CSVLoadMixin, IdentityProcessMixin, KaggleDownloadMixin, BaseDataset): """The Walmart Recruiting: Trip Type Classification https://www.kaggle.com/c/walmart-recruiting-trip-type- classification.""" def __init__(self, cache_dir=DEFAULT_CACHE_LOCATION, kaggle_username=None, kaggle_key=None): self.kaggle_username = kaggle_username self.kaggle_key = kaggle_key self.is_kaggle_competition = True super().__init__(dataset_name="walmart_recruiting", cache_dir=cache_dir)
[ { "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
ludwig/datasets/walmart_recruiting/__init__.py
dantreiman/ludwig
from django.test import TestCase from django.utils import timezone from data_refinery_common.models import ( SurveyJob, DownloaderJob, ProcessorJob, ) class SanityTestJobsTestCase(TestCase): def test_jobs_sanity(self): """Just makes sure creating Jobs doesn't fail""" s_job = SurveyJob() s_job.save() processor_job = ProcessorJob() processor_job.pipeline_applied = "test0" processor_job.save() dl_job = DownloaderJob() dl_job.downloader_task = "XYZ" dl_job.accession_code = "123" dl_job.save() def test_time_tracking_works(self): """created_at and last_modified are initialized upon creation""" job = SurveyJob.objects.create(source_type="ARRAY_EXPRESS") timedelta = timezone.now() - job.created_at self.assertLess(timedelta.total_seconds(), 1) self.assertEqual(job.created_at, job.last_modified) # When the job is updated and saved, last_modified changes job.success = False job.save() self.assertNotEqual(job.created_at, job.last_modified)
[ { "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
common/data_refinery_common/models/test_jobs.py
cgreene/refinebio
# Create a function called get_format_name with first and last name def get_formatted_name(first_name, last_name): # Describe the function """Return a full name, neatly formatted.""" # The names are joined into full name formatted_name = first_name + ' ' + last_name # return the value, don't do anything with it yet return formatted_name.title() def get_full_name(first_name, middle_name, last_name): if middle_name: full_name = first_name + ' ' + middle_name + ' ' + last_name else: full_name = first_name + ' ' + last_name return full_name.title() # Take function and assign it to musician musician1 = get_formatted_name('jimi', 'hendrix') musician2 = get_full_name('john', 'lee', 'hooker') # I still have to specify a middle name, ?? It's not truly optional this way. musician3 = get_full_name('jimi', '', 'hendrix') print(musician1) print(musician2) print(musician3)
[ { "point_num": 1, "id": "no_function_exceeds_5_params", "question": "Does every function in this file take 5 or fewer parameters (excluding self/cls)?", "answer": true }, { "point_num": 2, "id": "every_function_under_20_lines", "question": "Is every function in this file shorter than...
3
ch08/08_05-formatted_name.py
remotephone/pythoncrashcourse
## ********Day 55 Start********** ## Advanced Python Decorator Functions class User: def __init__(self, name): self.name = name self.is_logged_in = False def is_authenticated_decorator(function): def wrapper(*args, **kwargs): if args[0].is_logged_in == True: function(args[0]) return wrapper @is_authenticated_decorator def create_blog_post(user): print(f"This is {user.name}'s new blog post.") new_user = User("Edgar") new_user.is_logged_in = True create_blog_post(new_user)
[ { "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
Day_55/sandbox.py
ecanro/100DaysOfCode_Python
import pytest from esu.base import NotFoundEx from esu.client import Client from esu.project import Project from esu.tests import load_fixtures @load_fixtures def test_not_found_by_id(rsps): client_id = '10000000-1000-1000-1000-100000000000' with pytest.raises(NotFoundEx): Client.get_object(client_id) @load_fixtures def test_get_by_id(rsps): client_id = 'd5cd2cdc-b5b0-4d2e-8bc6-ea3f019745f9' client = Client.get_object(client_id) assert isinstance(client, Client) assert client.id == client_id assert client.name == 'default' assert client.balance == 2550.63 assert client.payment_model == 'postpay' assert len(client.allowed_hypervisors) == 2 @load_fixtures def test_get_projects(rsps): client_id = 'd5cd2cdc-b5b0-4d2e-8bc6-ea3f019745f9' client = Client.get_object(client_id) projects = client.get_projects() assert len(projects) == 2 assert isinstance(projects[0], Project) assert projects[0].name == 'Project 2'
[ { "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
esu/tests/test_client.py
pilat/rustack-esu
from __future__ import division, absolute_import, print_function import numpy as np import numpy.ma as ma from numpy.testing import * from numpy.compat import sixu rlevel = 1 class TestRegression(TestCase): def test_masked_array_create(self,level=rlevel): """Ticket #17""" x = np.ma.masked_array([0,1,2,3,0,4,5,6],mask=[0,0,0,1,1,1,0,0]) assert_array_equal(np.ma.nonzero(x),[[1,2,6,7]]) def test_masked_array(self,level=rlevel): """Ticket #61""" x = np.ma.array(1,mask=[1]) def test_mem_masked_where(self,level=rlevel): """Ticket #62""" from numpy.ma import masked_where, MaskType a = np.zeros((1,1)) b = np.zeros(a.shape, MaskType) c = masked_where(b,a) a-c def test_masked_array_multiply(self,level=rlevel): """Ticket #254""" a = np.ma.zeros((4,1)) a[2,0] = np.ma.masked b = np.zeros((4,2)) a*b b*a def test_masked_array_repeat(self, level=rlevel): """Ticket #271""" np.ma.array([1],mask=False).repeat(10) def test_masked_array_repr_unicode(self): """Ticket #1256""" repr(np.ma.array(sixu("Unicode"))) def test_atleast_2d(self): """Ticket #1559""" a = np.ma.masked_array([0.0, 1.2, 3.5], mask=[False, True, False]) b = np.atleast_2d(a) assert_(a.mask.ndim == 1) assert_(b.mask.ndim == 2) def test_set_fill_value_unicode_py3(self): """Ticket #2733""" a = np.ma.masked_array(['a', 'b', 'c'], mask=[1, 0, 0]) a.fill_value = 'X' assert_(a.fill_value == 'X') def test_var_sets_maskedarray_scalar(self): """Issue gh-2757""" a = np.ma.array(np.arange(5), mask=True) mout = np.ma.array(-1, dtype=float) a.var(out=mout) assert_(mout._data == 0) if __name__ == "__main__": run_module_suite()
[ { "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
numpy/ma/tests/test_regression.py
WeatherGod/numpy
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import math def get_factorials(n): f = lambda x: x * f(x - 1) if x else 1 return [f(i) for i in range(n)] def sum_factorial_digits(limit): factorial = get_factorials(10) total = 0 digit_sum = 0 order = int(math.log10(limit)) for n in range(3, int(limit)): digit = n % 10 if digit == 0: digit_sum = 0 value = n for i in range(order): digit_sum += factorial[value % 10] value //= 10 if value == 0: break else: digit_sum += factorial[digit] if digit_sum == n: total += n digit_sum -= factorial[digit] return total def main(): print(sum_factorial_digits(1e4)) if __name__ == '__main__': main()
[ { "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_function_names_snake_case", "question": "Are all function names in this file written in snake_case?", "ans...
3
34.py
goldsborough/euler
import os from conans import ConanFile, CMake, tools class XsimdTestConan(ConanFile): settings = "os", "compiler", "build_type", "arch" generators = "cmake" def build(self): cmake = CMake(self) cmake.configure() cmake.build() def test(self): self.run(os.path.join("bin", "test_package"), run_environment=True)
[ { "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
recipes/xsimd/all/test_package/conanfile.py
hoxnox/conan-center-index
from abc import ABCMeta, abstractmethod class PathFinder(object): __metaclass__ = ABCMeta def __init__(self, G, P): self.G = G self.P = P @abstractmethod def heuristic(self, v, src, dest): pass @abstractmethod def calc(self, src, dest): pass
[ { "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
path_finders/path_finder.py
dulek/alt-tester
# Write a function called unique_english_letters that takes the string word as a parameter. The function should return the total number of unique letters in the string. # Uppercase and lowercase letters should be counted as different letters. # We’ve given you a list of every uppercase and lower case letter in the English alphabet. It will be helpful to include that list in your function. letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" def unique_english_letters(word): new_lst = [] for character in word: if character not in new_lst: new_lst.append(character) return len(new_lst) def unique_english_letters(word): uniques = 0 for letter in letters: if letter in word: uniques += 1 return uniques print(unique_english_letters("mississippi")) print(unique_english_letters("Apple")) print(unique_english_letters("MangoMango"))
[ { "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
exercises/play_ground/pg_041.py
EngineerToBe/python-labs
from rest_framework import serializers from rest_framework_gis import serializers as gis_serializers from .models import Tree class TreeSerializer(gis_serializers.GeoFeatureModelSerializer): location = gis_serializers.GeometrySerializerMethodField() class Meta: model = Tree fields = ('id', 'location') geo_field = 'location' def get_location(self, obj): location = obj.location location.transform(4326) return location def get_properties(self, instance, fields): return instance.properties class SpeciesSerializer(serializers.Serializer): species = serializers.CharField() count = serializers.IntegerField() class GenusSerializer(serializers.Serializer): genus = serializers.CharField() count = serializers.IntegerField() class BoroughSerializer(serializers.Serializer): borough = serializers.CharField() count = serializers.IntegerField()
[ { "point_num": 1, "id": "more_functions_than_classes", "question": "Does this file define more functions than classes?", "answer": false }, { "point_num": 2, "id": "has_multiple_inheritance", "question": "Does any class in this file use multiple inheritance?", "answer": false }...
3
trees_api/serializers.py
scrambldchannel/trees-api-v2
def main(): a, b, c = list(map(int, input().split())) print(solve(a, b, c)) def solve(a, b, c): if a + b == c: return "{0}+{1}={2}".format(a, b, c) elif a - b == c: return "{0}-{1}={2}".format(a, b, c) elif a / b == c: return "{0}/{1}={2}".format(a, b, c) elif a * b == c: return "{0}*{1}={2}".format(a, b, c) if b + c == a: return "{0}={1}+{2}".format(a, b, c) elif b - c == a: return "{0}={1}-{2}".format(a, b, c) elif b / c == a: return "{0}={1}/{2}".format(a, b, c) elif b * a == c: return "{0}={1}*{2}".format(a, b, c) main()
[ { "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
kattis/tri.py
terror/Solutions
from __future__ import unicode_literals from django.conf import settings from django.db.models.signals import post_save from django.dispatch import receiver from django_auth_ldap.backend import populate_user from .models import UserProfile try: USER_ATTR_IMAGE_URL = settings.AUTH_LDAP_USER_ATTR_IMAGE_URL except AttributeError: USER_ATTR_IMAGE_URL = None @receiver(post_save, sender = settings.AUTH_USER_MODEL) def create_profile(sender, instance, created, **kwargs): if created: UserProfile.objects.create(user = instance) @receiver(populate_user) def populate_profile(sender, user, ldap_user, **kwargs): if USER_ATTR_IMAGE_URL is None: return (user.profile.image_url, ) = ldap_user.attrs.get(USER_ATTR_IMAGE_URL, ('', )) user.profile.save()
[ { "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
profiles/signals.py
nivbend/memoir
# Copyright (c) 2003-2005 Maxim Sobolev. All rights reserved. # Copyright (c) 2006-2007 Sippy Software, Inc. All rights reserved. # # This file is part of SIPPY, a free RFC3261 SIP stack and B2BUA. # # SIPPY is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # For a license to use the SIPPY software under conditions # other than those described here, or to purchase support for this # software, please contact Sippy Software, Inc. by e-mail at the # following addresses: sales@sippysoft.com. # # SIPPY is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. from .Timeout import Timeout from .UaStateGeneric import UaStateGeneric class UaStateDisconnected(UaStateGeneric): sname = 'Disconnected' def __init__(self, ua): UaStateGeneric.__init__(self, ua) ua.on_local_sdp_change = None ua.on_remote_sdp_change = None Timeout(self.goDead, 32.0) def recvRequest(self, req): if req.getMethod() == 'BYE': #print 'BYE received in the Disconnected state' self.ua.global_config['_sip_tm'].sendResponse(req.genResponse(200, 'OK')) else: self.ua.global_config['_sip_tm'].sendResponse(req.genResponse(500, 'Disconnected')) return None def goDead(self): #print 'Time in Disconnected state expired, going to the Dead state' self.ua.changeState((UaStateDead,)) if 'UaStateDead' not in globals(): from .UaStateDead import UaStateDead
[ { "point_num": 1, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "answer": false }, { "point_num": 2, "id": "has_multiple_inheritance", "question": "Does any class in this file use multiple inheritance?", "answer": false ...
3
pulsar/core/sippy/UaStateDisconnected.py
N0nent1ty/pulsar
from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, SubmitField from wtforms.validators import DataRequired, Length, ValidationError from app.models.user import User class SignupForm(FlaskForm): username = StringField('Username', validators=[DataRequired(), Length(min=4, max=32)]) displayname = StringField('Display Name', validators=[DataRequired(), Length(min=1, max=32)]) password = PasswordField('Password', validators=[DataRequired()]) def validate_username(self, username): if not username.data: raise ValidationError('Please enter a username.') if User.query.filter_by(username=username.data).first(): raise ValidationError('That username is taken. Please choose another.') if len(username.data) > 32: raise ValidationError('That username is too long. Please enter another.') class SigninForm(FlaskForm): username = StringField('Username', validators=[DataRequired(), Length(min=4, max=32)]) password = PasswordField('Password', validators=[DataRequired()]) def validate_username(self, username): if not username.data: raise ValidationError('Please enter a username.') if len(username.data) > 32: raise ValidationError('That username is too long. Please try again.')
[ { "point_num": 1, "id": "has_multiple_inheritance", "question": "Does any class in this file use multiple inheritance?", "answer": false }, { "point_num": 2, "id": "more_functions_than_classes", "question": "Does this file define more functions than classes?", "answer": false }...
3
app/forms/auth.py
poiley/take-note
# 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. import logging from typing import List, Optional import torch.nn as nn import torch.nn.functional as F logger = logging.getLogger(__name__) class FairseqDropout(nn.Module): def __init__(self, p, module_name=None): super().__init__() self.p = p self.module_name = module_name self.apply_during_inference = False def forward(self, x, inplace: bool = False): if self.training or self.apply_during_inference: return F.dropout(x, p=self.p, training=True, inplace=inplace) else: return x def extra_repr(self) -> str: return 'p={}'.format(self.p) def make_generation_fast_( self, name: str, retain_dropout: bool = False, retain_dropout_modules: Optional[List[str]] = None, **kwargs ): if retain_dropout: if retain_dropout_modules is not None and self.module_name is None: logger.warning( 'Cannot enable dropout during inference for module {} ' 'because module_name was not set'.format(name) ) elif ( retain_dropout_modules is None # if None, apply to all modules or self.module_name in retain_dropout_modules ): logger.info( 'Enabling dropout during inference for module: {}'.format(name) ) self.apply_during_inference = True else: logger.info('Disabling dropout for module: {}'.format(name))
[ { "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": "more_functions_than_classes", "question": "Does this file define more functions than clas...
3
fairseq/modules/fairseq_dropout.py
zhengzx-nlp/REDER
# Markov chain comparison class # create multiple Markov_learning classes, and conduct comparison import numpy as np import Markov_learning as ml import copy class Markov_comp(object): # attributes # it may have multiple Markov_learning objects # maximum, 10 ML=[] # how many MLs? for comparison between different evolution schedules. num_ML = 0 # testmode? test_mode = 0 # how many conditions? conditions = 0 # status matrix size size = 0 # current status matrix status_t0 = 0 # total time length length = 0 # matrix for comparison-regression. comp_matrix = [] def __init__(self, conditions, size, length, schedules): #initialize # test mode, if all -1s if conditions == -1 & size == -1 & length == -1 & schedules == -1: # test mode, as published self.conditions = 3 self.size = 2 self.num_ML = 2 # x = ml.Markov_learning(-1,-1,-1) # self.ML.append(x) # y = ml.Markov_learning(-2,-2,-2) # self.ML.append(y) self.ML_test1=copy.copy(ml.Markov_learning(-1,-1,-1)) self.ML_test2=copy.copy(ml.Markov_learning(-2,-2,-2)) # self.ML = [ml.Markov_learning(-1,-1,-1),ml.Markov_learning(-2,-2,-2)] # self.ML = [ml.Markov_learning() for i in range(2)] # self.ML[0] = ml.Markov_learning(-1,-1,-1) # self.ML[1] = ml.Markov_learning(-2,-2,-2) self.test_mode = 1 self.length = 100 self.status_t0 = np.zeros((self.size)) # testmode def test1(self): if self.test_mode < 1: return -1 self.ML[0].test1()
[ { "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
Markov_comp.py
xxelloss/Markov-Learning
import sys sys.setrecursionlimit(10**6) def fibonacci(term_num): if(term_num == 1 or term_num == 2): return 1 else: return (fibonacci(term_num-1)+fibonacci(term_num-2)) def check_first_fib_term_over(limit): third_last_term = 1 second_last_term = 1 last_term = 2 term_index = 3 while(last_term < limit): temp = last_term last_term += second_last_term third_last_term = second_last_term second_last_term = temp term_index += 1 return term_index if __name__ == "__main__": print(check_first_fib_term_over(10**999))
[ { "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
project_euler/Problem25/p25.py
bernardosequeir/CTFfiles
import io from dagster_aws.s3 import S3FakeSession, S3FileCache, S3FileHandle def test_s3_file_cache_file_not_present(): session_fake = S3FakeSession() file_store = S3FileCache( s3_bucket='some-bucket', s3_key='some-key', s3_session=session_fake, overwrite=False ) assert not file_store.has_file_object('foo') def test_s3_file_cache_file_present(): session_fake = S3FakeSession() file_store = S3FileCache( s3_bucket='some-bucket', s3_key='some-key', s3_session=session_fake, overwrite=False ) assert not file_store.has_file_object('foo') file_store.write_binary_data('foo', 'bar'.encode()) assert file_store.has_file_object('foo') def test_s3_file_cache_correct_handle(): session_fake = S3FakeSession() file_store = S3FileCache( s3_bucket='some-bucket', s3_key='some-key', s3_session=session_fake, overwrite=False ) assert isinstance(file_store.get_file_handle('foo'), S3FileHandle) def test_s3_file_cache_write_file_object(): session_fake = S3FakeSession() file_store = S3FileCache( s3_bucket='some-bucket', s3_key='some-key', s3_session=session_fake, overwrite=False ) stream = io.BytesIO('content'.encode()) file_store.write_file_object('foo', stream)
[ { "point_num": 1, "id": "every_function_under_20_lines", "question": "Is every function in this file shorter than 20 lines?", "answer": true }, { "point_num": 2, "id": "has_nested_function_def", "question": "Does this file contain any function defined inside another function?", "...
3
python_modules/libraries/dagster-aws/dagster_aws_tests/s3_tests/test_s3_file_cache.py
flowersw/dagster
from flask import render_template,redirect,url_for, flash,request from flask_login import login_user,logout_user,login_required from . import auth from ..models import User from .forms import LoginForm,RegistrationForm from .. import db from ..email import mail_message @auth.route('/login',methods=['GET','POST']) def login(): login_form = LoginForm() if login_form.validate_on_submit(): user = User.query.filter_by(email = login_form.email.data).first() if user is not None and user.verify_password(login_form.password.data): login_user(user,login_form.remember.data) return redirect(request.args.get('next') or url_for('main.index')) flash('Invalid username or Password') title = "One Minute Pitch login" return render_template('auth/login.html',login_form = login_form,title=title) @auth.route('/register',methods = ["GET","POST"]) def register(): form = RegistrationForm() if form.validate_on_submit(): user = User(email = form.email.data, username = form.username.data,firstname= form.firstname.data,lastname= form.lastname.data,password = form.password.data) db.session.add(user) db.session.commit() mail_message("Welcome to One Minute Pitch",user.email,user=user) return redirect(url_for('auth.login')) title = "New Account" return render_template('auth/register.html',registration_form = form) @auth.route('/logout') @login_required def logout(): logout_user() return redirect(url_for("main.index"))
[ { "point_num": 1, "id": "every_function_under_20_lines", "question": "Is every function in this file shorter than 20 lines?", "answer": true }, { "point_num": 2, "id": "all_function_names_snake_case", "question": "Are all function names in this file written in snake_case?", "answ...
3
app/auth/views.py
Kihara-tony/one-minute-pitch
import graphene from graphene import Node from graphene_django.filter import DjangoFilterConnectionField from graphene_django.rest_framework.mutation import SerializerMutation from graphene_django.types import DjangoObjectType from rest_framework.generics import get_object_or_404 from contact.models import Contact from contact.serializers import ContactSerializer class ContactModelMutation(SerializerMutation): class Meta: serializer_class = ContactSerializer convert_choices_to_enum = False class ContactNode(DjangoObjectType): class Meta: model = Contact interfaces = (Node,) fields = "__all__" filter_fields = ["first_name"] class ContactType(DjangoObjectType): class Meta: model = Contact fields = "__all__" class Query(graphene.ObjectType): contact_node = Node.Field(ContactNode) contacts_node = DjangoFilterConnectionField(ContactNode) contact = graphene.Field(ContactType, id=graphene.Int()) contacts = graphene.List(ContactType) def resolve_contacts(self, info, **kwargs): return Contact.objects.all() def resolve_contact(self, info, id): return get_object_or_404(Contact, pk=id) class DeleteMutation(graphene.Mutation): class Arguments: # The input arguments for this mutation id = graphene.Int(required=True) # The class attributes define the response of the mutation id = graphene.ID() message = graphene.String() @classmethod def mutate(cls, root, info, id): contact = get_object_or_404(Contact, pk=id) contact.delete() return cls(id=id, message='deleted') class Mutation(graphene.ObjectType): create_contact = ContactModelMutation.Field() update_contact = ContactModelMutation.Field() delete_contact = DeleteMutation.Field() schema = graphene.Schema(query=Query, mutation=Mutation)
[ { "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
src/contact/schema.py
mesherinovivan/graphql-django
import gc import pprint class Graph: def __init__(self, name): self.name = name self.next = None def set_next(self, next): print('Linking nodes {}.next = {}'.format(self, next)) self.next = next def __repr__(self): return '{}({})'.format( self.__class__.__name__, self.name) # Construct a graph cycle one = Graph('one') two = Graph('two') three = Graph('three') one.set_next(two) two.set_next(three) three.set_next(one) # Remove references to the graph nodes in this module's namespace one = two = three = None # Show the effect of garbage collection for i in range(2): print('\nCollecting {} ...'.format(i)) n = gc.collect() print('Unreachable objects:', n) print('Remaining Garbage:', end=' ') pprint.pprint(gc.garbage)
[ { "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
src/lesson_runtime_features/gc_collect.py
jasonwee/asus-rt-n14uhp-mrtg
import os import unittest import ansiblelint from ansiblelint import RulesCollection class TestTaskIncludes(unittest.TestCase): def setUp(self): rulesdir = os.path.join('lib', 'ansiblelint', 'rules') self.rules = RulesCollection.create_from_directory(rulesdir) def test_included_tasks(self): filename = 'test/taskincludes.txt' runner = ansiblelint.Runner(self.rules, {filename}, [], []) runner.run() self.assertEqual(len(runner.playbooks), 3)
[ { "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
test/TestTaskIncludes.py
eemz/ansible-lint
from openeo_udf.api.datacube import DataCube from openeo_udf.api.udf_data import UdfData from typing import Dict, Callable import xarray import numpy import pandas from pandas import Series def apply_timeseries(series: Series, context:Dict)->Series: """ Do something with the timeseries :param series: :param context: :return: """ return series def apply_timeseries_generic(udf_data: UdfData, callback: Callable = apply_timeseries): """ Implements the UDF contract by calling a user provided time series transformation function (apply_timeseries). Multiple bands are currently handled separately, another approach could provide a dataframe with a timeseries for each band. :param udf_data: :return: """ # The list of tiles that were created tile_results = [] # Iterate over each cube for cube in udf_data.get_datacube_list(): array3d = [] #use rollaxis to make the time dimension the last one for time_x_slice in numpy.rollaxis(cube.array.values, 1): time_x_result = [] for time_slice in time_x_slice: series = pandas.Series(time_slice) transformed_series = callback(series,udf_data.user_context) time_x_result.append(transformed_series) array3d.append(time_x_result) # We need to create a new 3D array with the correct shape for the computed aggregate result_tile = numpy.rollaxis(numpy.asarray(array3d),1) assert result_tile.shape == cube.array.shape # Create the new raster collection cube rct = DataCube(xarray.DataArray(result_tile)) tile_results.append(rct) # Insert the new tiles as list of raster collection tiles in the input object. The new tiles will # replace the original input tiles. udf_data.set_datacube_list(tile_results) return udf_data
[ { "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
src/openeo_udf/api/udf_wrapper.py
Open-EO/openeo-udf
# coding:utf-8 # TODO: We should pass a read-only view of the cgroup instead to ensure # thread-safety. class RestartRequestedMessage(object): def __init__(self, cg): self.cg = cg class RestartCompleteMessage(object): def __init__(self, cg): self.cg = cg
[ { "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": false ...
3
captain_comeback/restart/messages.py
zharben/captain-comeback
# -*- coding: ISO-8859-1 -*- ############################################# ## (C)opyright by Dirk Holtwick, 2002-2007 ## ## All rights reserved ## ############################################# __reversion__ = "$Revision: 20 $" __author__ = "$Author: holtwick $" __date__ = "$Date: 2007-10-09 12:58:24 +0200 (Di, 09 Okt 2007) $" from pisa_util import pisaTempFile, getFile import logging log = logging.getLogger("ho.pisa") class pisaPDF: def __init__(self, capacity=-1): self.capacity = capacity self.files = [] def addFromURI(self, url, basepath=None): obj = getFile(url, basepath) if obj and (not obj.notFound()): self.files.append(obj.getFile()) addFromFileName = addFromURI def addFromFile(self, f): if hasattr(f, "read"): self.files.append(f) self.addFromURI(f) def addFromString(self, data): self.files.append(pisaTempFile(data, capacity=self.capacity)) def addDocument(self, doc): if hasattr(doc.dest, "read"): self.files.append(doc.dest) def join(self, file=None): import pyPdf if pyPdf: output = pyPdf.PdfFileWriter() for pdffile in self.files: input = pyPdf.PdfFileReader(pdffile) for pageNumber in range(0, input.getNumPages()): output.addPage(input.getPage(pageNumber)) if file is not None: output.write(file) return file out = pisaTempFile(capacity=self.capacity) output.write(out) return out.getvalue() getvalue = join __str__ = join
[ { "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
sx/pisa3/pisa_pdf.py
gustavohenrique/wms
from __future__ import absolute_import from collections import OrderedDict from uuid import uuid4 from django.utils.translation import ugettext_lazy as _ from vishap import render_video from nonefield.fields import NoneField from fobi.base import FormElementPlugin from . import UID from .forms import ContentVideoForm __title__ = 'fobi.contrib.plugins.form_elements.content.content_video.base' __author__ = 'Artur Barseghyan <artur.barseghyan@gmail.com>' __copyright__ = '2014-2017 Artur Barseghyan' __license__ = 'GPL 2.0/LGPL 2.1' __all__ = ('ContentVideoPlugin',) class ContentVideoPlugin(FormElementPlugin): """Content video plugin.""" uid = UID name = _("Content video") group = _("Content") form = ContentVideoForm def post_processor(self): """Process plugin data. Always the same. """ self.data.name = "{0}_{1}".format(self.uid, uuid4()) def get_raw_data(self): """Get raw data. Might be used in integration plugins. """ return OrderedDict( ( ('title', self.data.title), ('url', self.data.url), ('size', self.data.size), ) ) def get_rendered_video(self): """Get rendered video. Might be used in integration plugins. """ width, height = self.data.size.split('x') return render_video(self.data.url, width, height) def get_form_field_instances(self, request=None, form_entry=None, form_element_entries=None, **kwargs): """Get form field instances.""" field_kwargs = { 'initial': '<div class="video-wrapper">{0}</div>'.format( self.get_rendered_video() ), 'required': False, 'label': '', } return [(self.data.name, NoneField, field_kwargs)]
[ { "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
events/contrib/plugins/form_elements/content/content_video/base.py
mansonul/events
lista = enumerate('zero um dois três quatro cinco seis sete oito nove'.split()) numero_string=dict(lista) string_numero={valor:chave for chave,valor in numero_string.items()} print (numero_string) print(string_numero) def para_numeral(n): numeros=[] for digito in str(n): numeros.append(numero_string[int(digito)]) return ", ".join(numeros) assert "um" == para_numeral(1) assert "um, dois" == para_numeral(12) assert "um, um" == para_numeral(11) def para_inteiro(string_n): string="" lista=string_n.split(", ") for digito in lista: string+=str(string_numero[digito]) return int(string) assert 1== para_inteiro('um') assert 12== para_inteiro('um, dois')
[ { "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
Tarefa03/Tarefa03.py
igorlimasan/poo-python
class Article: ''' Class that instantiates objects of the news article objects of the news sources ''' def __init__(self,author,description,time,url,image,title): self.author = author self.description = description self.time = time self.url = url self.image = image self.title = title class Category: ''' Class that instantiates objects of the news categories objects of the news sources ''' def __init__(self,author,description,time,url,image,title): self.author = author self.description = description self.time = time self.url = url self.image = image self.title = title class Source: ''' Source class to define source objects ''' def __init__(self,id,name,description,url): self.id = id self.name = name self.description = description self.url = url class Headlines: ''' Class that instantiates objects of the headlines categories objects of the news sources ''' def __init__(self,author,description,time,url,image,title): self.author = author self.description = description self.time = time self.url = url self.image = image self.title = title
[ { "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/models.py
Kabu1/flashnews
def setup(): size (600,600) noLoop() def drawMyScene(myColor,x): rotate(PI/4*x) fill(myColor) rect(0,50,150,50) rect(50,0,50,150) def draw(): background(20) smooth() noStroke() pushMatrix() translate(100,0) drawMyScene(180,1) popMatrix() pushMatrix() translate(420,150) scale(2) drawMyScene(220,2) popMatrix() pushMatrix() translate(480,330) scale(1.4) drawMyScene(80,1) popMatrix()
[ { "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
processing/chapter4/sketch_4_2_Z3/sketch_4_2_Z3.pyde
brickdonut/2019-fall-polytech-cs
import sys from sys import stdin, stdout import time import gtk import __builtin__, gettext, gtk.glade gettext.install("pychess", unicode=1) t = gettext.translation("pychess", fallback=True) __builtin__.__dict__["ngettext"] = t.ungettext #evilness copy-paste from pychess startup script import pychess.Main from pychess.System.Log import log import pychess.widgets.ionest as i #current hack to get access to GameModel import parsemove #the own thing here for parsing move data from pychess import msg #talking to the parent process, called directly from parsemove too def initchess(): p = pychess.Main.PyChess(None) log.log("Started from Naali\n") #print "PyChess in Naali" g = None prev_board = None prev_arBoard = None def updatechess(): #print ".", global g, prev_board, prev_arBoard for _ in range(100): gtk.main_iteration(block=False) #gtk.gdk.threads_enter() if g is None and i.globalgamemodel is not None: g = i.globalgamemodel board = g.boards[-1] msg.send("BEGIN:%s" % board.board.arBoard.tostring()) if g is not None: #print g.players, id(g.boards[-1]), g.boards[-1] board = g.boards[-1] if board is not prev_board: #print "BOARD:", board if len(board.board.history) > 0: prevmove = board.board.history[-1][0] parsemove.parsemove(board, prev_arBoard, prevmove) prev_board = board prev_arBoard = board.board.arBoard[:] def main(): initchess() gtk.gdk.threads_init() while 1: updatechess() time.sleep(0.001) """in parsemove.py now def removePiece(tcord, tpiece, opcolor): print "REMOVE:", tcord, tpiece, opcolor def addPiece(tcord, piece, color): print "ADD:", tcord, piece, opcolor def move(fcord, tcord, piece, color): print "REMOVE:", tcord, tpiece, opcolor """ if __name__ == '__main__': main()
[ { "point_num": 1, "id": "all_function_names_snake_case", "question": "Are all function names in this file written in snake_case?", "answer": true }, { "point_num": 2, "id": "every_function_under_20_lines", "question": "Is every function in this file shorter than 20 lines?", "answ...
3
src/Application/PythonScriptModule/pymodules_old/apitest/chessview/pychessview.py
antont/tundra
class solution: def oneEditAwayInsert(self,input1,input2): index1 = 0 index2 = 0 while((index2 < len(input2)) and (index1 < len(input1))): if(input1[index1] != input2[index2]): if(index1 != index2): return False index2+=1 else: index1+=1 index2+=1 return True def oneEditAwayReplace(self,input1,input2): flag = False for i in range(len(input1)): if(input2[i]!=input1[i]): if(flag): return False flag = True return True def oneEditAway(self,input1,input2): if(len(input1)==len(input2)): return self.oneEditAwayReplace(input1,input2) elif(len(input1)+1==len(input2)): return self.oneEditAwayInsert(input1,input2) elif(len(input1)-1==len(input2)): return self.oneEditAwayInsert(input2,input1) return False input1 = input() input2 = input() sol = solution() print(sol.oneEditAway(input1,input2))
[ { "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
String-Algorithms/String-Algorithms-master/One Edit Away/oneEditAway.py
SrijaniSom/dsa-code-store
from logging import basicConfig, getLogger, DEBUG logger = getLogger(__name__) OBJECT = 'DFW section' MODULE = 'Services' def get_list(client): """ """ request = client.__getattr__(MODULE).ListSections() response, _ = request.result() return response['results'] def get_id(client, data): if data.has_key('id'): return data['id'] elif data.has_key('display_name'): objects = get_list(client) for obj in objects: if obj['display_name'] == data['display_name']: return obj['id'] return None def create(client, data): """ """ param = {'FirewallSection': data} request = client.__getattr__(MODULE).AddSection(**param) response, _ = request.result() return response def delete(client, data): """ """ param = {'section-id': get_id(client, data), 'cascade': True} request = client.__getattr__(MODULE).DeleteSection(**param) response = request.result() return response def exist(client, data): if get_id(client, data): return True else: return False def run(client, action, data, config=None): if action == 'create': if exist(client, data): logger.error('Already exist') else: return create(client, data) elif action == 'update': logger.error('Not implemented') return None elif action == 'delete': if exist(client, data): return delete(client, data) else: logger.error('Not exist')
[ { "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
pynsxt/nsx_dfw_section.py
yktsubo/pynsxt
from dataclasses import dataclass from mint.consensus.constants import ConsensusConstants from mint.types.blockchain_format.sized_bytes import bytes100 from mint.util.streamable import Streamable, streamable @dataclass(frozen=True) @streamable class ClassgroupElement(Streamable): """ Represents a classgroup element (a,b,c) where a, b, and c are 512 bit signed integers. However this is using a compressed representation. VDF outputs are a single classgroup element. VDF proofs can also be one classgroup element (or multiple). """ data: bytes100 @staticmethod def from_bytes(data) -> "ClassgroupElement": if len(data) < 100: data += b"\x00" * (100 - len(data)) return ClassgroupElement(bytes100(data)) @staticmethod def get_default_element() -> "ClassgroupElement": # Bit 3 in the first byte of serialized compressed form indicates if # it's the default generator element. return ClassgroupElement.from_bytes(b"\x08") @staticmethod def get_size(constants: ConsensusConstants): return 100
[ { "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
mint/types/blockchain_format/classgroup.py
sai-genesis/rc1-test
from torch.nn.functional import one_hot from operations.base import Operator class OneHot(Operator): def __init__(self, dim=-1, non_zero_values_only=False): self.dim = dim self.non_zero_values_only = non_zero_values_only super().__init__() def forward(self, indices, depth, values): if self.non_zero_values_only: off_value, on_value = -1, 1 else: off_value, on_value = values out = one_hot(indices.to(int), depth.to(int).item()) out = out * (on_value - off_value) + off_value rank = len(indices.shape) if self.dim < 0: self.dim += rank + 1 if not rank == self.dim: # permute only if dim not last dimension order = list(range(len(indices.shape))) order.insert(self.dim, -1) out = out.permute(order) return out
[ { "point_num": 1, "id": "has_nested_function_def", "question": "Does this file contain any function defined inside another function?", "answer": false }, { "point_num": 2, "id": "has_multiple_inheritance", "question": "Does any class in this file use multiple inheritance?", "answ...
3
private/TrainingHelperServices/operations/onehot.py
microsoft/MaskedLARk
import zlib from io import BytesIO import pytest from df_raw_decoder import ( decode_data, DecodingException, encode_to_int32, encode_to_int16, encode_data, encode_decode_index_file_line ) def test_invalid_file(): file = BytesIO() file.write(100 .to_bytes(4, 'little')) file.write(b'\0') file.seek(0) with pytest.raises(DecodingException): next(decode_data(file)) def test_encode_decode(): lines = [b'test'] assert list(decode_data(BytesIO(encode_data(lines)))) == lines assert list(decode_data(BytesIO(encode_data(lines, True)), True)) == lines def test_invalid_line_length(): buf = BytesIO() buf.write(1 .to_bytes(4, 'little')) line = b'test' buf.write(encode_to_int32(len(line))) buf.write(encode_to_int16(len(line) + 1)) deflate = zlib.compress(buf.getvalue()) file = encode_to_int32(len(deflate)) + deflate with pytest.raises(DecodingException): next(decode_data(BytesIO(file))) @pytest.mark.parametrize("encoded,decoded", [ (b'\x96\x90\x99\x97\x83', b'index'), ( b'\xcd\xce\x7f\xac\x89\x90\x97\x8b\x9b\x8e\x92\x99\x99\xdc\x99\x86\xde\xa9\x9b\x89\x91\xde\xbc\x98\x9a\x92\x8b', b'20~Programmed by Tarn Adams' ), (b'\xcd\xca\x7f\xb8\x84\x9e\x8c\x97\xdc\xb5\x90\x8c\x89\x8a\x96\x8c\x8b', b'24~Dwarf Fortress'), ]) def test_decode_encode_index_file_line(encoded, decoded): assert encode_decode_index_file_line(encoded) == decoded assert encode_decode_index_file_line(encode_decode_index_file_line(encoded)) == encoded
[ { "point_num": 1, "id": "every_function_under_20_lines", "question": "Is every function in this file shorter than 20 lines?", "answer": true }, { "point_num": 2, "id": "all_function_names_snake_case", "question": "Are all function names in this file written in snake_case?", "answ...
3
test_df_raw_decoder.py
dfint/df_raw_decoder
''' app.forms ~~~~~~~~~ Forms we need to use when posting datas in our website. flask_wtf.Form is still useable, but FlaskForm is suggested. ''' from flask_wtf import FlaskForm from wtforms import StringField, BooleanField, TextAreaField from wtforms.validators import DataRequired, Length from flask_babel import gettext from .models import User class LoginForm(FlaskForm): # the DataRequired import is a validator, a function that # can be attached to a field to perform validation on the # data submitted by the user. The DataRequired validator # simply checks that the field is not submitted empty. openid = StringField('openid', validators=[DataRequired()]) remember_me = BooleanField('remember_me', default=False) class EditForm(FlaskForm): nickname = StringField('nickname', validators=[DataRequired()]) about_me = TextAreaField('about_me', validators=[Length(min=0, max=140)]) def __init__(self, original_nickname, *args, **kwargs): FlaskForm.__init__(self, *args, **kwargs) self.original_nickname = original_nickname def validate(self): if not FlaskForm.validate(self): return False if self.nickname.data == self.original_nickname: return True if self.nickname.data != User.make_valid_nickname(self.nickname.data): self.nickname.errors.append( gettext('This nickname has invalid characters. Please use letter, numbers, dots and underscores only.') ) user = User.query.filter_by(nickname=self.nickname.data).first() if user is not None: self.nickname.errors.append(gettext('This nickname is already in use. Please choose another one.')) return False return True class PostForm(FlaskForm): post = StringField('post', validators=[DataRequired()]) class SearchForm(FlaskForm): search = StringField('search', validators=[DataRequired()])
[ { "point_num": 1, "id": "more_functions_than_classes", "question": "Does this file define more functions than classes?", "answer": false }, { "point_num": 2, "id": "every_class_has_docstring", "question": "Does every class in this file have a docstring?", "answer": false }, {...
3
app/forms.py
Napchat/microblog
from unittest import TestCase from littlelambocoin.types.blockchain_format.program import Program, SerializedProgram, INFINITE_COST from littlelambocoin.wallet.puzzles.load_clvm import load_clvm SHA256TREE_MOD = load_clvm("sha256tree_module.clvm") # TODO: test multiple args class TestSerializedProgram(TestCase): def test_tree_hash(self): p = SHA256TREE_MOD s = SerializedProgram.from_bytes(bytes(SHA256TREE_MOD)) self.assertEqual(s.get_tree_hash(), p.get_tree_hash()) def test_program_execution(self): p_result = SHA256TREE_MOD.run(SHA256TREE_MOD) sp = SerializedProgram.from_bytes(bytes(SHA256TREE_MOD)) cost, sp_result = sp.run_with_cost(INFINITE_COST, sp) self.assertEqual(p_result, sp_result) def test_serialization(self): s0 = SerializedProgram.from_bytes(b"\x00") p0 = Program.from_bytes(b"\x00") print(s0, p0) # TODO: enable when clvm updated for minimal encoding of zero # self.assertEqual(bytes(p0), bytes(s0))
[ { "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
tests/clvm/test_serialized_program.py
Tony4467/littlelambocoin-blockchain
import numpy as np def load_csv_test_data(filename): with open(filename, 'r') as input_file: return [[item for item in line.strip().split(',')] for line in input_file] def load_csv_data(filename:str) -> np.ndarray: if not filename.endswith('.csv'): filename += '.csv' with open(filename, 'r') as input_file: return [[int(item) for item in line.strip().split(',')] for line in input_file] def load_set_data(filename: str) -> np.ndarray: with open(filename, 'r') as input_file: loaded_set = [] for line in input_file: if line.strip() != '': tokens = line.strip().split(',') set_items = np.array(list(map(int, tokens))) else: set_items = [] loaded_set.append(set_items) return np.array(loaded_set)
[ { "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/utils/file.py
dballesteros7/master-thesis-2015
from flask import Flask from flask import request from flask import make_response import base64 import pickle app = Flask(__name__) @app.route('/') def index(): cookie = {'type': 'pickles', 'user_name': 'user'} encoded_cookie = base64.b64encode(pickle.dumps(cookie)) green_pickle = request.cookies.get('greenPickle') if green_pickle is not None: green_pickle = pickle.loads(base64.b64decode(green_pickle)) user_name = green_pickle.get('user_name') if user_name.lower() == 'admin': return "Flag{pickles_are_great}" resp = make_response("Welcome to my site," " sorry it's still under construction..." " admins only") resp.set_cookie('greenPickle', encoded_cookie) return resp @app.route('/admin') def admin(): return "No flag here" if __name__ == "__main__": app.run(port=8888) #app.run()
[ { "point_num": 1, "id": "has_nested_function_def", "question": "Does this file contain any function defined inside another function?", "answer": false }, { "point_num": 2, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "ans...
3
web_challenges/pickle/ctf_pickle.py
code4days/BsidesCincyCTF
import torch import torchvision.transforms as transforms import model from PIL import Image import sys DIR="data/models/" MODEL="model-100-epochs-adam-0003-lr-cpu.pth" def get_model(PATH, model): device = torch.device('cpu') model.load_state_dict(torch.load(PATH, map_location=device)) model.eval() return model def load_img(PATH): img = Image.open(PATH) img.load() return img def load_apply_preprocessing(PATH): test_transforms = transforms.Compose([ transforms.Resize((224,224)), transforms.ToTensor(), transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])]) img = load_img(PATH) img = test_transforms(img) img = torch.unsqueeze(img, 0) return img def predict(model, img): with torch.no_grad(): pred = model(img) idx = pred.argmax() prob = torch.nn.functional.softmax(pred, dim=1)[0][idx].item() res = (f"Cat {prob}%") if pred.argmax()==0 else (f"Dog {prob}%") return res if __name__ == "__main__": sample_img = sys.argv[1] #"data/cat.jpg" model = model.Classifier() model = get_model(DIR+MODEL, model) img = load_apply_preprocessing(sample_img) result = predict(model, img) print("Image:",sample_img," ---> ",result)
[ { "point_num": 1, "id": "all_function_names_snake_case", "question": "Are all function names in this file written in snake_case?", "answer": true }, { "point_num": 2, "id": "no_function_exceeds_5_params", "question": "Does every function in this file take 5 or fewer parameters (exclu...
3
app.py
arunbonagiri190/Cat-Dog-Classifier
import pytest from temporal import DEFAULT_VERSION from temporal.workflow import workflow_method, WorkflowClient, Workflow TASK_QUEUE = "test_workflow_get_version_single_tq" NAMESPACE = "default" version_found_in_step_1_0 = None version_found_in_step_1_1 = None version_found_in_step_2_0 = None version_found_in_step_2_1 = None class GreetingWorkflow: @workflow_method(task_queue=TASK_QUEUE) async def get_greeting(self) -> None: raise NotImplementedError class GreetingWorkflowImpl(GreetingWorkflow): async def get_greeting(self): global version_found_in_step_1_0, version_found_in_step_1_1 global version_found_in_step_2_0, version_found_in_step_2_1 version_found_in_step_1_0 = Workflow.get_version( "first-item", DEFAULT_VERSION, 2 ) version_found_in_step_1_1 = Workflow.get_version( "first-item", DEFAULT_VERSION, 2 ) await Workflow.sleep(60) version_found_in_step_2_0 = Workflow.get_version( "first-item", DEFAULT_VERSION, 2 ) version_found_in_step_2_1 = Workflow.get_version( "first-item", DEFAULT_VERSION, 2 ) @pytest.mark.asyncio @pytest.mark.worker_config( NAMESPACE, TASK_QUEUE, activities=[], workflows=[GreetingWorkflowImpl] ) async def test(worker): client = WorkflowClient.new_client(namespace=NAMESPACE) greeting_workflow: GreetingWorkflow = client.new_workflow_stub(GreetingWorkflow) await greeting_workflow.get_greeting() assert version_found_in_step_1_0 == 2 assert version_found_in_step_1_1 == 2 assert version_found_in_step_2_0 == 2 assert version_found_in_step_2_1 == 2
[ { "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
tests/test_workflow_get_version_single.py
Optimally-com/temporal-python-sdk
# Tencent is pleased to support the open source community by making ncnn available. # # Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. # # Licensed under the BSD 3-Clause License (the "License"); you may not use this file except # in compliance with the License. You may obtain a copy of the License at # # https://opensource.org/licenses/BSD-3-Clause # # Unless required by applicable law or agreed to in writing, software distributed # under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR # CONDITIONS OF ANY KIND, either express or implied. See the License for the # specific language governing permissions and limitations under the License. import torch import torch.nn as nn import torch.nn.functional as F class Model(nn.Module): def __init__(self): super(Model, self).__init__() def forward(self, x, y, z): x = F.softmax(x, 0) y = F.softmax(y, 1) z = F.softmax(z, 2) return x, y, z def test(): net = Model() net.eval() torch.manual_seed(0) x = torch.rand(16) y = torch.rand(2, 16) z = torch.rand(3, 12, 16) a = net(x, y, z) # export torchscript mod = torch.jit.trace(net, (x, y, z)) mod.save("test_F_softmax.pt") # torchscript to pnnx import os os.system("../../src/pnnx test_F_softmax.pt inputshape=[16],[2,16],[3,12,16]") # ncnn inference import test_F_softmax_ncnn b = test_F_softmax_ncnn.test_inference() for a0, b0 in zip(a, b): if not torch.allclose(a0, b0, 1e-4, 1e-4): return False return True if __name__ == "__main__": if test(): exit(0) else: exit(1)
[ { "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
tools/pnnx/tests/ncnn/test_F_softmax.py
fzyzcjy/ncnn
import numpy as np from lmfit import Parameters, minimize, report_fit from lmfit.models import LinearModel, GaussianModel from lmfit.lineshapes import gaussian def per_iteration(pars, iter, resid, *args, **kws): """iteration callback, will abort at iteration 23 """ # print( iter, ', '.join(["%s=%.4f" % (p.name, p.value) for p in pars.values()])) return iter == 23 def test_itercb(): x = np.linspace(0, 20, 401) y = gaussian(x, amplitude=24.56, center=7.6543, sigma=1.23) y = y - .20*x + 3.333 + np.random.normal(scale=0.23, size=len(x)) mod = GaussianModel(prefix='peak_') + LinearModel(prefix='bkg_') pars = mod.make_params(peak_amplitude=21.0, peak_center=7.0, peak_sigma=2.0, bkg_intercept=2, bkg_slope=0.0) out = mod.fit(y, pars, x=x, iter_cb=per_iteration) assert(out.nfev == 23) assert(out.aborted) assert(not out.errorbars) assert(not out.success)
[ { "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
tests/test_itercb.py
FaustinCarter/lmfit-py
from machine import Pin, PWM import pycom import time class Rotate: # Servo to fixed position def __init__(self, pwm): # Assum 50ms timer already set up and going to reuse self.pwm = pwm self.is_active = False self.at_position = 50 def run(self): pass def state_text(self): return 'Rotate position = {}'.format(self.at_position) def activate(self, start_dc=0.15): # May not be switched on if not self.is_active: self.is_active = True self.pwm_c = self.pwm.channel(2, pin='G13', duty_cycle=start_dc) def set_position(self, position): # Converts to 1 -2 ms pulses self.at_position = position # speed in % dc = (position / 100.0) * (1/20) + (1/20) self.activate(start_dc=dc) self.pwm_c.duty_cycle(dc) return dc def wait_set_position(self, position): """Rotates and waits until rotate gets there. Guess time from assuming a constant rotation speed""" full_rotate_time = 3000 # ms # Estiamte on rotation at full speed time_estimate = full_rotate_time * abs(self.at_position - position) / 100 # Allow for creep which can take a minimum time if self.at_position - position != 0: time_estimate = min(int(time_estimate), 1500) self.set_position(position) time.sleep_ms(int(time_estimate)) def shutdown(self): # Ideally won't move servo self.pwm_off = Pin('G13', mode=Pin.IN, pull=Pin.PULL_UP) self.is_active = False def in_bin(self): self.wait_set_position(86) def out_bin(self): self.wait_set_position(12) # min diff seems to be 2 self.wait_set_position(14) def dvd(self): self.wait_set_position(50)
[ { "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
controller/test5_hw_test/rotate_axis.py
drummonds/od-robot
""" Week 6 - Paddle Class --------- AUTHOR: Edward Camp """ from cs1lib import * class Paddle: def __init__(self, x, y, width, height, r, g, b, paddleName, game): self.game = game self.x = x self.y = y self.width = width self.height = height self.r = r self.g = g self.b = b self.paddleName = paddleName self.vy = 0 self.velocity = 10 def checkCollision(self, ball): # The collision detection is geometrically incorrect, but simple enough for it to be functional # ANSWER STARTS HERE if(self.x < ball.x < self.x + self.width and self.y < ball.y < self.y + self.height): ball.paddleBounce(self.paddleName) # ANSWER ENDS HERE def movePaddleUp(self): self.vy = -self.velocity # ANSWER IS ONE LINE def movePaddleDown(self): self.vy = self.velocity # ANSWER IS ONE LINE def stopPaddle(self): self.vy = 0 # ANSWER IS ONE LINE def calculatePosition(self): # ANSWER STARTS HERE if(self.y < 0): self.y = 0 elif(self.y + self.height > self.game.HEIGHT): self.y = self.game.HEIGHT - self.height else: self.y += self.vy # ANSWER ENDS HERE def draw(self): # ANSWER STARTS HERE set_fill_color(self.r, self.g, self.b) draw_rectangle(self.x, self.y, self.width, self.height) # ANSWER ENDS HERE
[ { "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
Week6/Paddle.py
johnlev/coderdojo-curriculum
""" db.py """ from pymongo import MongoClient class Db: # pylint: disable=too-few-public-methods """ Database. Singleton pattern, from Bruce Eckel """ class __Db: # pylint: disable=invalid-name def __init__(self, dbname): self.val = dbname self.client = MongoClient('mongodb://localhost:27017/') self.conn = self.client['leadreader_' + dbname] def __str__(self): return repr(self) + self.val instance = None def __init__(self, dbname='prod'): if not Db.instance: Db.instance = Db.__Db(dbname) else: Db.instance.val = dbname def __getattr__(self, name): return getattr(self.instance, name)
[ { "point_num": 1, "id": "all_function_names_snake_case", "question": "Are all function names in this file written in snake_case?", "answer": true }, { "point_num": 2, "id": "more_functions_than_classes", "question": "Does this file define more functions than classes?", "answer": ...
3
leadreader/db.py
raindrift/leadreader
import os import sys sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__)))) import torch.nn as nn import torch.nn.functional as F #from layers.graph_convolution_layer import GraphConvolutionLayer from layers.graph_unet_layer import GraphUNetLayer from readouts.basic_readout import readout_function """ Base paper: https://arxiv.org/pdf/1905.05178.pdf """ class GraphUNet(nn.Module): def __init__(self, n_feat, n_class, n_layer, agg_hidden, fc_hidden, dropout, readout, device): super(GraphUNet, self).__init__() self.n_layer = n_layer self.readout = readout # Pooling_rate pooling_rations = [0.8 - (i * 0.1) if i < 3 else 0.5 for i in range(n_layer)] # Graph unet layer self.graph_unet_layers = [] for i in range(n_layer): if i == 0: self.graph_unet_layers.append(GraphUNetLayer(n_feat, agg_hidden, pooling_rations[i], device)) else: self.graph_unet_layers.append(GraphUNetLayer(agg_hidden, agg_hidden, pooling_rations[i], device)) # Fully-connected layer self.fc1 = nn.Linear(agg_hidden, fc_hidden) self.fc2 = nn.Linear(fc_hidden, n_class) def forward(self, data): for i in range(self.n_layer): # Graph unet layer data = self.graph_unet_layers[i](data) x = data[0] # Dropout if i != self.n_layer - 1: x = F.dropout(x, p=self.dropout, training=self.training) # Readout x = readout_function(x, self.readout) # Fully-connected layer x = F.relu(self.fc1(x)) x = F.softmax(self.fc2(x)) return x def __repr__(self): layers = '' for i in range(self.n_layer): layers += str(self.graph_unet_layers[i]) + '\n' layers += str(self.fc1) + '\n' layers += str(self.fc2) + '\n' return layers
[ { "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
models/GraphUNet.py
qbxlvnf11/graph-neural-networks-for-graph-classification
"""rising Sphinx theme. """ from os import path __version__ = '0.0.25' __version_full__ = __version__ def get_html_theme_path(): """Return list of HTML theme paths.""" cur_dir = path.abspath(path.dirname(path.dirname(__file__))) return cur_dir # See http://www.sphinx-doc.org/en/stable/theming.html#distribute-your-theme-as-a-python-package def setup(app): app.add_html_theme('rising_sphinx_theme', path.abspath(path.dirname(__file__)))
[ { "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
rising_sphinx_theme/__init__.py
PhoenixDL/rising_sphinx_theme
from django.db import models from accounts.models import Profile from django.contrib.auth.models import User class Shop(models.Model): name = models.CharField(max_length=100) desc = models.TextField() address = models.CharField(max_length=100) admin = models.ForeignKey( Profile, on_delete=models.CASCADE, ) # image = models.ImageField() # Here ForeignKey isn't working! Check Out # admin = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.name class Item(models.Model): name = models.CharField(max_length=100) avail = models.BooleanField(default= False) shopProfile = models.ForeignKey(Shop, on_delete=models.CASCADE) desc = models.TextField() # image = models.ImageField() def __str__(self): return self.name
[ { "point_num": 1, "id": "has_nested_function_def", "question": "Does this file contain any function defined inside another function?", "answer": false }, { "point_num": 2, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "ans...
3
ShopkeeperUI/models.py
imsubhams/ProdCheck
class Node: def __init__(self, key, value): self.key, self.value = key, value self.prev = None self.next = None class LRUCache: def __init__(self, capacity: int): self.capacity = capacity self.cache = {} self.left = Node(0, 0) self.right = Node(0, 0) self.left.next, self.right.prev = self.right, self.left def insert(self, node): prev, nxt = self.right.prev, self.right prev.next = nxt.prev = node node.next, node.prev = nxt, prev def remove(self, node): prev, nxt = node.prev, node.next prev.next, next.prev = nxt, prev def get(self, key: int) -> int: if key in self.cache: self.remove(self.cache[key]) self.insert(self.cache[key]) return self.cache[key].val return -1 def put(self, key: int, value: int) -> None: if key in self.cache: self.remove(self.cache[key]) self.cache[key] = Node(key, value) self.insert(self.cache[key]) if len(self.cache) > self.capacity: lru = self.left.next self.remove(lru) del self.cache[lru.key]
[ { "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
lru_cache.py
tejeshreddy/python-oops
from test.vim_test_case import VimTestCase as _VimTest from test.constant import * # Anonymous Expansion {{{# class _AnonBase(_VimTest): args = '' def _extra_vim_config(self, vim_config): vim_config.append('inoremap <silent> %s <C-R>=UltiSnips#Anon(%s)<cr>' % (EA, self.args)) class Anon_NoTrigger_Simple(_AnonBase): args = '"simple expand"' keys = 'abc' + EA wanted = 'abcsimple expand' class Anon_NoTrigger_AfterSpace(_AnonBase): args = '"simple expand"' keys = 'abc ' + EA wanted = 'abc simple expand' class Anon_NoTrigger_BeginningOfLine(_AnonBase): args = r"':latex:\`$1\`$0'" keys = EA + 'Hello' + JF + 'World' wanted = ':latex:`Hello`World' class Anon_NoTrigger_FirstCharOfLine(_AnonBase): args = r"':latex:\`$1\`$0'" keys = ' ' + EA + 'Hello' + JF + 'World' wanted = ' :latex:`Hello`World' class Anon_NoTrigger_Multi(_AnonBase): args = '"simple $1 expand $1 $0"' keys = 'abc' + EA + '123' + JF + '456' wanted = 'abcsimple 123 expand 123 456' class Anon_Trigger_Multi(_AnonBase): args = '"simple $1 expand $1 $0", "abc"' keys = '123 abc' + EA + '123' + JF + '456' wanted = '123 simple 123 expand 123 456' class Anon_Trigger_Simple(_AnonBase): args = '"simple expand", "abc"' keys = 'abc' + EA wanted = 'simple expand' class Anon_Trigger_Twice(_AnonBase): args = '"simple expand", "abc"' keys = 'abc' + EA + '\nabc' + EX wanted = 'simple expand\nabc' + EX class Anon_Trigger_Opts(_AnonBase): args = '"simple expand", ".*abc", "desc", "r"' keys = 'blah blah abc' + EA wanted = 'simple expand' # End: Anonymous Expansion #}}}
[ { "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
ultisnips/test/test_AnonymousExpansion.py
adrewasa/asavim
# Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html # For details: https://github.com/PyCQA/pylint/blob/main/LICENSE # Copyright (c) https://github.com/PyCQA/pylint/blob/main/CONTRIBUTORS.txt """JSON reporter.""" import json from typing import TYPE_CHECKING, Optional from pylint.interfaces import IReporter from pylint.reporters.base_reporter import BaseReporter if TYPE_CHECKING: from pylint.lint.pylinter import PyLinter from pylint.reporters.ureports.nodes import Section class JSONReporter(BaseReporter): """Report messages and layouts in JSON.""" __implements__ = IReporter name = "json" extension = "json" def display_messages(self, layout: Optional["Section"]) -> None: """Launch layouts display.""" json_dumpable = [ { "type": msg.category, "module": msg.module, "obj": msg.obj, "line": msg.line, "column": msg.column, "endLine": msg.end_line, "endColumn": msg.end_column, "path": msg.path, "symbol": msg.symbol, "message": msg.msg or "", "message-id": msg.msg_id, } for msg in self.messages ] print(json.dumps(json_dumpable, indent=4), file=self.out) def display_reports(self, layout: "Section") -> None: """Don't do anything in this reporter.""" def _display(self, layout: "Section") -> None: """Do nothing.""" def register(linter: "PyLinter") -> None: linter.register_reporter(JSONReporter)
[ { "point_num": 1, "id": "all_params_annotated", "question": "Does every function parameter in this file have a type annotation (excluding self/cls)?", "answer": true }, { "point_num": 2, "id": "every_function_under_20_lines", "question": "Is every function in this file shorter than 2...
3
venv/Lib/site-packages/pylint/reporters/json_reporter.py
AnxhelaMehmetaj/is219_flask
import abc import typing class BaseInputFeed(abc.ABC): """ """ def __init__(self, model, batch_size): self.model = model self.batch_size = batch_size @abc.abstractmethod def get_train_batch(self): """Defien a batch feed dictionary the model needs for training, each sub class should implement this method.""" @abc.abstractmethod def get_test_batch(self): """Defien a batch feed dictionary the model needs for testing, each sub class should implement this method."""
[ { "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
esrt/engine/base_input_feed.py
PTYin/ESRT
from django.core.exceptions import PermissionDenied from rules.rulesets import RuleSet from .rules import has_site_access site_permissions = RuleSet() site_permissions.add_rule("site_perm", has_site_access) class SitePermissionBackend(object): """Authentication backend that checks row-level permissions granted on site-level. """ def authenticate(self, request, **credentials): """Pass authentication process to the next authentication backend. """ return None def has_perm(self, user, perm, obj=None): """Checks if ``user` belongs to a site associated with ``obj``. Denies access if ``obj`` is registered for site-level permissions and ``user`` does not belong to the same site as ``obj``. In any other case (``user`` passed the test or ``obj`` is not registered for site-level permissions, no ``obj`` is passed), permission checking continues to the next authentication backend. :param user: User instance :param perm: Permission codename :param obj: Object checked against """ if not site_permissions.test_rule("site_perm", user, obj): raise PermissionDenied() return None def has_module_perms(self, user, app_label): """Pass module permission checking process to the next authentication backend. """ return None
[ { "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
djangocms_fil_permissions/permissions.py
FidelityInternational/djangocms-fil-permissions
import datetime from flask import Blueprint, request, abort from app.auth.helper import token_required from app.programs.helper import response, response_for_program, get_programs_json_list, response_for_programs_list, get_programs, get_single_program from app.models.user import User from app.models.program import Program from neomodel import DoesNotExist # Initialize blueprint programs = Blueprint('programs', __name__) @programs.route('/programs', methods=['GET']) def programlist(): """ Return all the programs. Return an empty programs object if no programs :return: """ items = get_programs() if items: return response_for_programs_list(get_programs_json_list(items)) return response_for_programs_list([]) @programs.route('/programs/<program_id>', methods=['GET']) def get_program(program_id): """ Return a program. :param program_id: Program Id :return: """ try: str(program_id) except ValueError: return response('failed', 'Please provide a valid program Id', 400) else: program = get_single_program(program_id) if program: return response_for_program(program.json()) else: return response('failed', "Program not found", 404) @programs.route('/user/programs', methods=['GET']) @token_required def get_user_program(current_user): """ Return a program. :param program_id: Program Id :return: """ user_program = User.get_by_username(current_user.username).program if user_program: return response_for_program(user_program.json()) else: return response('failed', "User program not found", 404)
[ { "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
app/programs/views.py
rukaury/vsrpapi
# coding: utf-8 """ LogicMonitor REST API LogicMonitor is a SaaS-based performance monitoring platform that provides full visibility into complex, hybrid infrastructures, offering granular performance monitoring and actionable data and insights. logicmonitor_sdk enables you to manage your LogicMonitor account programmatically. # noqa: E501 OpenAPI spec version: 1.0.0 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import unittest import logicmonitor_sdk from logicmonitor_sdk.models.auto_discovery_filter import AutoDiscoveryFilter # noqa: E501 from logicmonitor_sdk.rest import ApiException class TestAutoDiscoveryFilter(unittest.TestCase): """AutoDiscoveryFilter unit test stubs""" def setUp(self): pass def tearDown(self): pass def testAutoDiscoveryFilter(self): """Test AutoDiscoveryFilter""" # FIXME: construct object with mandatory attributes with example values # model = logicmonitor_sdk.models.auto_discovery_filter.AutoDiscoveryFilter() # 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
test/test_auto_discovery_filter.py
JeremyTangCD/lm-sdk-python
import os def mkdirs(paths): if isinstance(paths, list) and not isinstance(paths, str): for path in paths: mkdir(path) else: mkdir(paths) def mkdir(path): if not os.path.exists(path): os.makedirs(path)
[ { "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
utils/util.py
SimonTreu/sdvae
from credoscript import adaptors, models from tests import CredoAdaptorTestCase class InterfaceAdaptorTestCase(CredoAdaptorTestCase): def setUp(self): self.adaptor = adaptors.InterfaceAdaptor() self.expected_entity = models.Interface def test_fetch_by_interface_id(self): """Fetch a single Interface by interface_id""" self.assertSingleResult('fetch_by_interface_id', 1) def test_fetch_all_by_chain_id(self): """Fetch all interfaces by chain_id""" interface = models.Interface.query.limit(1).first() self.assertPaginatedResult('fetch_all_by_chain_id', interface.chain_bgn_id) def test_fetch_all_by_biomolecule_id(self): """Fetch all interfaces by biomolecule_id""" interface = models.Interface.query.limit(1).first() self.assertPaginatedResult('fetch_all_by_biomolecule_id', interface.biomolecule_id) def test_fetch_all_by_uniprot(self): """Fetch all interfaces by UniProt accession""" self.assertPaginatedResult('fetch_all_by_uniprot', 'P09211') def test_fetch_all_cath_dmn(self): """Fetch all interfaces by UniProt accession""" self.assertPaginatedResult('fetch_all_by_cath_dmn', '10gsA01') def test_fetch_all_by_phenotype_id(self): """Fetch all interfaces by variation phenotype_id""" self.assertPaginatedResult('fetch_all_by_phenotype_id', 13) def test_fetch_all_by_path_match(self): """retrieve interfaces through ptree path match""" self.assertPaginatedResult('fetch_all_by_path_match', '11GS/*') def test_fetch_all_path_descendants(self): """retrieve interfaces through ptree path descendants""" self.assertPaginatedResult('fetch_all_path_descendants', '11GS/1')
[ { "point_num": 1, "id": "every_function_under_20_lines", "question": "Is every function in this file shorter than 20 lines?", "answer": true }, { "point_num": 2, "id": "all_function_names_snake_case", "question": "Are all function names in this file written in snake_case?", "answ...
3
tests/adaptors/interfaceadaptortestcase.py
tlb-lab/credoscript
# -*- coding: utf-8 -*- # Copyright 2018-2022 the orix developers # # This file is part of orix. # # orix is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # orix is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with orix. If not, see <http://www.gnu.org/licenses/>. import abc from orix.vector import Vector3d class IPFColorKey(abc.ABC): """Assign colors to crystal directions rotated by crystal orientations and projected into an inverse pole figure. This is an abstract class defining properties and methods required in derived classes. """ def __init__(self, symmetry, direction=None): self.symmetry = symmetry if direction is None: direction = Vector3d.zvector() self.direction = direction def __repr__(self): return ( f"{self.__class__.__name__}, symmetry: {self.symmetry.name}, " f"direction: {self.direction.data.squeeze()}" ) @property @abc.abstractmethod def direction_color_key(self): return NotImplemented # pragma: no cover @abc.abstractmethod def orientation2color(self, *args, **kwargs): return NotImplemented # pragma: no cover @abc.abstractmethod def plot(self, *args, **kwargs): return NotImplemented # pragma: no cover
[ { "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
orix/plot/orientation_color_keys/ipf_color_key.py
bm424/texpy
import pytest from app.models.user import User from datetime import date @pytest.fixture(scope='module') def new_user(): user = User('test', date(day=1, month=12, year=1989)) return user def test_new_user(new_user): """ GIVEN a User model WHEN a new User is created THEN check the username and birthday fields are defined correctly """ assert new_user.name == 'test' assert new_user.birthday == date(day=1, month=12, year=1989)
[ { "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
tests/unit/test_app.py
atsikham/flask-test-app
from typing import Tuple import numpy as np from ...core import ContinuousParameter, InformationSourceParameter, ParameterSpace from ...core.loop.user_function import MultiSourceFunctionWrapper def multi_fidelity_currin_function() -> Tuple[MultiSourceFunctionWrapper, ParameterSpace]: r""" High fidelity function is given by: .. math:: f_{high}(\mathbf{x}) = \left[ 1 - \exp \left(-\frac{1}{2x_2}\right) \right] \frac{2300x_1^3 + 1900x_1^2 + 2092x_1 + 60}{100x_1^3+500x_1^2 + 4x_1 + 20} Low fidelity function given by: .. math:: f_{low}(\mathbf{x}) = \frac{1}{4} \left[ f_{high}(x_1 + 0.05, x_2 + 0.05) + f_{high}(x_1 + 0.05, \max (0, x_2 - 0.05)) \\ + f_{high}(x_1 - 0.05, x_2 + 0.05) + f_{high}\left(x_1 - 0.05, \max \left(0, x_2 - 0.05\right)\right) \right] Input domain: .. math:: \mathbf{x}_i \in [0, 1] Reference: https://www.sfu.ca/~ssurjano/curretal88exp.html """ def high(x): x1 = x[:, 0] x2 = x[:, 1] return ( 1 - np.exp(-0.5 / x2) * ((2300 * x1 ** 3 + 1900 * x1 ** 2 + 2092 * x1 + 60) / (100 * x1 ** 3 + 500 * x1 ** 2 + 4 * x1 + 20)) )[:, None] def low(x): return ( 0.25 * high(np.stack([x[:, 0] + 0.05, x[:, 1] + 0.05], axis=1)) + 0.25 * high(np.stack([x[:, 0] + 0.05, np.maximum(0, x[:, 1] - 0.05)], axis=1)) + 0.25 * high(np.stack([x[:, 0] - 0.05, x[:, 1] + 0.05], axis=1)) + 0.25 * high(np.stack([x[:, 0] - 0.05, np.maximum(0, x[:, 1] - 0.05)], axis=1)) ) space = ParameterSpace( [ContinuousParameter("x1", 0, 1), ContinuousParameter("x2", 0, 1), InformationSourceParameter(2)] ) return MultiSourceFunctionWrapper([low, high]), space
[ { "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": "all_function_names_snake_case", "question": "Are all function names in this file written in snake_case?", ...
3
emukit/test_functions/multi_fidelity/currin.py
lfabris-mhpc/emukit
# -*- coding: utf-8 -*- # Copyright 2019 Bruno Toshio Sugano <brunotoshio@gmail.com> import os import pytest from monogatari.dict_handler import DictHandler @pytest.fixture def handler(): test_dir = os.path.dirname(__file__) return DictHandler(f'{test_dir}/testdic.dic') def test_parse_categories(handler): assert all(k in handler._categories for k in ['01', '02']) assert all(v in handler._categories.values() for v in ['HarmVirtue', 'HarmVice']) def test_parse_normal_keys(handler): assert all(k in handler._normal_dict for k in ['守る', '親善', '害']) assert all(k not in handler._normal_dict for k in ['安全*', '友情*', '損害*']) def test_parse_wildcard_keys(handler): assert all(k in handler._wildcard_dict for k in ['安全*', '友情*', '損害*']) assert all(k not in handler._wildcard_dict for k in ['守る', '親善', '害']) def test_wildcard_search_found(handler): assert handler._wildcard_search('友情') == ['HarmVirtue', 'HarmVice'] def test_wildcard_search_not_found(handler): assert handler._wildcard_search('友') == [] def test_search_found(handler): assert handler.search('守る') == ['HarmVirtue'] assert handler.search('友情') == ['HarmVirtue', 'HarmVice'] def test_search_not_found(handler): assert handler.search('友') == [] assert handler.search('守るら') == [] def test_categories(handler): assert handler.categories() == ['HarmVirtue', 'HarmVice']
[ { "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
tests/dict_handler_test.py
brunotoshio/monogatari
# coding: utf-8 """ Seldon Deploy API API to interact and manage the lifecycle of your machine learning models deployed through Seldon Deploy. # noqa: E501 OpenAPI spec version: v1alpha1 Contact: hello@seldon.io Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import unittest import seldon_deploy_sdk from seldon_deploy_sdk.models.downward_api_volume_source import DownwardAPIVolumeSource # noqa: E501 from seldon_deploy_sdk.rest import ApiException class TestDownwardAPIVolumeSource(unittest.TestCase): """DownwardAPIVolumeSource unit test stubs""" def setUp(self): pass def tearDown(self): pass def testDownwardAPIVolumeSource(self): """Test DownwardAPIVolumeSource""" # FIXME: construct object with mandatory attributes with example values # model = seldon_deploy_sdk.models.downward_api_volume_source.DownwardAPIVolumeSource() # 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
python/test/test_downward_api_volume_source.py
adriangonz/seldon-deploy-sdk
from actions.action import AbstractAction, CombinedAction, WrappedAction, SequenceAction def COMBINE(*actions: list[AbstractAction]): return CombinedAction(actions) def WRAP(outer_action: AbstractAction, inner_action: AbstractAction): return WrappedAction(outer_action, inner_action) def SEQUENCE(*actions: list[AbstractAction]): return SequenceAction(actions)
[ { "point_num": 1, "id": "has_nested_function_def", "question": "Does this file contain any function defined inside another function?", "answer": false }, { "point_num": 2, "id": "every_function_has_docstring", "question": "Does every function in this file have a docstring?", "ans...
3
keypad/driver/actions/utils.py
lnixdo2s/saiga
import pandas as pd import numpy as np import csv import pickle Jobs_path = "TestDescriptions.csv" Jobs = pd.read_csv(Jobs_path, delimiter=',') def get_JobID(): IDs = np.array(Jobs.index.values.tolist()) IDs = np.unique(IDs) IDs = IDs.tolist() return(IDs) def get_Info(ID): return Jobs[Jobs.index == ID] pickle.dump(Jobs, open('data.pkl','wb'))
[ { "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
khc_home_edited/method.py
eitrheim/Resume-Screening-and-Selection
class BinTree: def __init__(self): '''Container for structuring and handling all nodes used in an option-like asset. Creates a generic binomial option tree whose by planting an option. Ha, what? ''' class Binodes: def __init__(self, u_node, d_node): pass
[ { "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": false ...
3
atop/options/tree.py
MouseAndKeyboard/All_Things_Options_Notebooks
import sys from pymunk import Body, Circle, ShapeFilter from configsingleton import ConfigSingleton from common import * from common.drawing import draw_circle class Landmark(object): def __init__(self, mask, radius): self.body = Body(0, 0, Body.STATIC) self.body.position = 0, 0 self.body.angle = 0 self.body.velocity = 0, 0 self.body.angular_velocity = 0 self.shape = Circle(self.body, radius) self.mask = mask self.shape.filter = ShapeFilter(categories = mask) if mask == ARC_LANDMARK_MASK: self.shape.color = 0, 255, 0 elif mask == POLE_LANDMARK_MASK: self.shape.color = 0, 0, 255 elif mask == BLAST_LANDMARK_MASK: self.shape.color = 255, 0, 0 else: sys.exit("Unknown landmark mask: " + str(mask)) # The following is just to set the appropriate params to visualize below config = ConfigSingleton.get_instance() self.vis_range_max = \ config.getfloat("RangeScan:landmarks", "range_max") \ + radius self.vis_inside_radius = \ config.getfloat("LandmarkCircleController", "inside_radius") \ + radius self.vis_outside_radius = \ config.getfloat("LandmarkCircleController", "outside_radius") \ + radius def visualize_params(self): centre = (self.body.position.x, self.body.position.y) draw_circle(centre, self.vis_range_max, (255, 255, 255)) if self.mask == ARC_LANDMARK_MASK: draw_circle(centre, self.vis_inside_radius, (0, 255, 0)) draw_circle(centre, self.vis_outside_radius, (255, 0, 0))
[ { "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": "has_multiple_inheritance", "question": "Does any class in this file use multiple inheritance?", "answer": fals...
3
landmark.py
gavincangan/alvin
from FSMSIM.expr.arr_expr import ArrayExpr from FSMSIM.expr.expr import Expr class ArrayAccessExpr(Expr): def __init__(self, arr: "ArrayExpr", field: str) -> None: self.arr = arr self.field = field def evaluate(self) -> str: return self.arr.evaluate(self.field) def __len__(self) -> int: return self.arr.len(self.field) def fieldlen(self) -> int: return self.arr.fieldlen(self.field)
[ { "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
FSMSIM/expr/arr_access_expr.py
FSMSIM/FSMSIM
import torch import torch.nn as nn import math from torch.autograd import Variable class Embedder(nn.Module): def __init__(self, vocab_size, d_model): super().__init__() self.d_model = d_model self.embed = nn.Embedding(vocab_size, d_model) def forward(self, x): return self.embed(x) class PositionalEncoder(nn.Module): def __init__(self, d_model, max_seq_len=200, dropout=0.1): super().__init__() self.d_model = d_model self.dropout = nn.Dropout(dropout) # create constant 'pe' matrix with values dependant on # pos and i pe = torch.zeros(max_seq_len, d_model) for pos in range(max_seq_len): for i in range(0, d_model, 2): pe[pos, i] = \ math.sin(pos / (10000 ** ((2 * i)/d_model))) pe[pos, i + 1] = \ math.cos(pos / (10000 ** ((2 * (i + 1))/d_model))) pe = pe.unsqueeze(0) self.register_buffer('pe', pe) def forward(self, x): # make embeddings relatively larger x = x * math.sqrt(self.d_model) # add constant to embedding seq_len = x.size(1) pe = Variable(self.pe[:, :seq_len], requires_grad=False) if x.is_cuda: pe.cuda() x = x + pe return self.dropout(x)
[ { "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
Embed.py
zhengxiawu/Transformer
import pypro.core import os class CreateConfig(pypro.core.Recipe): def __init__(self, source, destination): self.source = source self.destination = destination def run(self, runner, arguments=None): # Read the template file content = '' with open(self.source, 'r') as f: content = f.read(os.path.getsize(self.source)) # Replace notations with actual values content = pypro.core.Variables.replace(content) # Write the config file with open(self.destination, 'w') as f: f.write(content)
[ { "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
examples/vagrant_todo/provision/recipes/project.py
avladev/pypro
import datetime from app import db class BucketList(db.Model): id = db.Column(db.Integer, primary_key=True, autoincrement=True) name = db.Column(db.String(100), unique=True) description = db.Column(db.Text, nullable=True) interests = db.Column(db.String(120), nullable=True) date_created = db.Column(db.DateTime, default=datetime.datetime.utcnow()) date_modified = db.Column(db.DateTime) created_by = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False) items = db.relationship('Item', backref='bucket_list_items', lazy='dynamic') def __repr__(self): return "<Bucketlist {}>".format(self.name) class Item(db.Model): id = db.Column(db.Integer, primary_key=True, autoincrement=True) name = db.Column(db.String(100), unique=True) description = db.Column(db.Text) status = db.Column(db.Text) date_accomplished = db.Column(db.DateTime) date_created = db.Column(db.DateTime, default=datetime.datetime.utcnow()) date_modified = db.Column(db.DateTime) bucketlists = db.Column(db.Integer, db.ForeignKey('bucket_list.id'), nullable=False) def __repr__(self): return "<Items {}>".format(self.name)
[ { "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
app/api/v1/models/bucketlist.py
johnseremba/bucket-list
# Given a linked list, rotate the list to the right by k places, where k is non-negative. # Example 1: # Input: 1->2->3->4->5->NULL, k = 2 # Output: 4->5->1->2->3->NULL # Explanation: # rotate 1 steps to the right: 5->1->2->3->4->NULL # rotate 2 steps to the right: 4->5->1->2->3->NULL # Example 2: # Input: 0->1->2->NULL, k = 4 # Output: 2->0->1->NULL # Explanation: # rotate 1 steps to the right: 2->0->1->NULL # rotate 2 steps to the right: 1->2->0->NULL # rotate 3 steps to the right: 0->1->2->NULL # rotate 4 steps to the right: 2->0->1->NULL class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def rotateRight(self, head: ListNode, k: int) -> ListNode: if head is None: return None if k == 0: return head tail = None cur = head listLen = 1 while cur.next: listLen += 1 cur = cur.next tail = cur prev, cur = None, head if k > listLen: k = k % listLen # if k = 4 and len = 3, rotate by 1 i = listLen - k if listLen == 1 or i == listLen or i == 0: # edge cases return head for _ in range(i): prev = cur cur = cur.next if prev: prev.next = None tail.next = head head = cur return head
[ { "point_num": 1, "id": "more_functions_than_classes", "question": "Does this file define more functions than classes?", "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
leetcode/medium/Linked Lists/RotateList.py
cheshtaaagarrwal/DS-Algos
# Copyright 2014 Confluent Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from ducktape.cluster.cluster_spec import ClusterSpec from ducktape.cluster.node_container import NodeContainer from .cluster import Cluster, ClusterNode from .linux_remoteaccount import LinuxRemoteAccount from .remoteaccount import RemoteAccountSSHConfig class LocalhostCluster(Cluster): """ A "cluster" that runs entirely on localhost using default credentials. This doesn't require any user configuration and is equivalent to the old defaults in cluster_config.json. There are no constraints on the resources available. """ def __init__(self, *args, **kwargs): num_nodes = kwargs.get("num_nodes", 1000) self._available_nodes = NodeContainer() for i in range(num_nodes): ssh_config = RemoteAccountSSHConfig("localhost%d" % i, hostname="localhost", port=22) self._available_nodes.add_node(ClusterNode(LinuxRemoteAccount(ssh_config))) self._in_use_nodes = NodeContainer() def alloc(self, cluster_spec): allocated = self._available_nodes.remove_spec(cluster_spec) self._in_use_nodes.add_nodes(allocated) return allocated def free_single(self, node): self._in_use_nodes.remove_node(node) self._available_nodes.add_node(node) node.account.close() def available(self): return ClusterSpec.from_nodes(self._available_nodes) def used(self): return ClusterSpec.from_nodes(self._in_use_nodes)
[ { "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
ducktape/cluster/localhost.py
stan-confluent/ducktape
import pandas as pd import itertools from functools import partial from fastai.callbacks import CSVLogger def get_config_df(config): df = pd.DataFrame(list(itertools.product(*config.values())), columns=config.keys()) df.index = [f'model_{i+1}' for i in range(len(df))] return df def create_experiment(nm, path, folder='results'): exp_path = (path/folder/nm) exp_path.mkdir(exist_ok=True) return nm, exp_path def record_experiment(learn, fn, exp_path): learn.callback_fns.append(partial(CSVLogger, filename=exp_path/fn)) def load_results(exp_path): config_df = pd.read_csv(exp_path/'config.csv', index_col=0) param_names = config_df.columns.values recorder_df=[] for p in exp_path.ls(): if p.name.startswith(tuple(config_df.index.values)): df = pd.read_csv(p) ind_name, fold_name = p.stem.split('-') df['index']=ind_name df['fold']=int(fold_name.split('_')[-1].split('.')[0]) recorder_df.append(df) recorder_df = pd.concat(recorder_df) metric_names = list(set(recorder_df.columns).symmetric_difference(['index', 'epoch', 'train_loss', 'fold'])) recorder_df = recorder_df.merge(config_df.reset_index()) return config_df, recorder_df, param_names, metric_names def summarise_results(recorder_df, param_names, metric_names): return (recorder_df.groupby(['index', *param_names, 'epoch'], as_index=False) .agg({k:['mean', 'std'] for k in metric_names}))
[ { "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
code/fastai_ext/fastai_ext/hyperparameter.py
jandremarais/TabularLearner
# -*- coding: utf-8 -*- # # Copyright (c) 2016, the cclib development team # # This file is part of cclib (http://cclib.github.io) and is distributed under # the terms of the BSD 3-Clause License. """Unit tests for writer xyzwriter module.""" import os import unittest import cclib __filedir__ = os.path.dirname(__file__) __filepath__ = os.path.realpath(__filedir__) __datadir__ = os.path.join(__filepath__, "..", "..") class XYZTest(unittest.TestCase): def setUp(self): self.XYZ = cclib.io.XYZ def test_init(self): """Does the class initialize correctly?""" fpath = os.path.join(__datadir__, "data/ADF/basicADF2007.01/dvb_gopt.adfout") data = cclib.io.ccopen(fpath).parse() xyz = cclib.io.xyzwriter.XYZ(data) # The object should keep the ccData instance passed to its constructor. self.assertEqual(xyz.ccdata, data) 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
test/io/testxyzwriter.py
alvarovm/cclib
class response: codes = {"Bad request": 1, "Success": 2, "Internal error":3, "Denied":4, "Accepted":5} def __init__(self, Response, Data=None, _bool=None): """Possible Responses: Bad request, Success, Internal error """ self.Response = Response self.Data = Data self.Code = response.codes[Response] self.bool = _bool def create_altered(self, Response = None, Data = None): return response(Response or self.Response, Data or self.Data) def __bool__(self): return self.bool
[ { "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
modules/response.py
NightKey/Server-monitoring-discord-bot
# -*- coding: utf-8 -*- # # Scimitar: Ye Distributed Debugger # # Copyright (c) 2016 Parsa Amini # Copyright (c) 2016 Hartmut Kaiser # Copyright (c) 2016 Thomas Heller # # Distributed under the Boost Software License, Version 1.0. (See accompanying # file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) # import readline import select import os.path history_file_path = os.path.join(os.path.expanduser('~'), '.scimitar_history') def load_history(): readline.set_history_length(10000) try: if os.path.exists(history_file_path): readline.read_history_file(history_file_path) except IOError: pass def save_history(): try: open(history_file_path, 'a').close() readline.write_history_file(history_file_path) except IOError: pass # vim: :ai:sw=4:ts=4:sts=4:et:ft=python:fo=corqj2:sm:tw=79:
[ { "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
util/history.py
parsa/scmitar
#!/usr/bin/env python from os import walk from os.path import join, splitext from ntpath import basename def get_images_labels_list(images_dir_path): """ Recursively iterates through a directory and its subdirectories to list the info all the images found in it. Returns a list of dictionary where each dictionary contains `image_path` and `image_label`. """ images_labels_list = [] for (dirpath, dirnames, filenames) in walk(images_dir_path): for filename in filenames: image_path = join(dirpath, filename) image_label = splitext(basename(dirpath))[0] image_info = {} image_info['image_path'] = image_path image_info['image_label'] = image_label images_labels_list.append(image_info) return images_labels_list def write_images_labels_to_file(images_labels_list, output_file_path): """ Writes the list of images-labels to a file. """ with open(output_file_path, "w") as output_file: for image_info in images_labels_list: image_path = image_info['image_path'] image_label = image_info['image_label'] line = image_path + "\t" + image_label + '\n' output_file.write(line)
[ { "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": "no_function_exceeds_5_params", "question": "Does every function in this file take 5 or fewer parameters (excluding ...
3
ML/Minor/code/common/generate_images_labels.py
SIgnlngX/Minor-Project
from django.test import SimpleTestCase from django.utils.safestring import mark_safe from ..utils import render, setup class DefaultTests(SimpleTestCase): """ Literal string arguments to the default filter are always treated as safe strings, regardless of the auto-escaping state. Note: we have to use {"a": ""} here, otherwise the invalid template variable string interferes with the test result. """ @setup({'default01': '{{ a|default:"x<" }}'}) def test_default01(self): output = render('default01', {"a": ""}) self.assertEqual(output, "x<") @setup({'default02': '{% autoescape off %}{{ a|default:"x<" }}{% endautoescape %}'}) def test_default02(self): output = render('default02', {"a": ""}) self.assertEqual(output, "x<") @setup({'default03': '{{ a|default:"x<" }}'}) def test_default03(self): output = render('default03', {"a": mark_safe("x>")}) self.assertEqual(output, "x>") @setup({'default04': '{% autoescape off %}{{ a|default:"x<" }}{% endautoescape %}'}) def test_default04(self): output = render('default04', {"a": mark_safe("x>")}) self.assertEqual(output, "x>") class DefaultIfNoneTests(SimpleTestCase): @setup({'default_if_none01': '{{ a|default:"x<" }}'}) def test_default_if_none01(self): output = render('default_if_none01', {"a": None}) self.assertEqual(output, "x<") @setup({'default_if_none02': '{% autoescape off %}{{ a|default:"x<" }}{% endautoescape %}'}) def test_default_if_none02(self): output = render('default_if_none02', {"a": None}) self.assertEqual(output, "x<")
[ { "point_num": 1, "id": "more_functions_than_classes", "question": "Does this file define more functions than classes?", "answer": true }, { "point_num": 2, "id": "every_class_has_docstring", "question": "Does every class in this file have a docstring?", "answer": false }, { ...
3
tests/template_tests/filter_tests/test_default.py
DasAllFolks/django
#!/usr/bin/python # -*- coding: utf-8 -*- from flask import Blueprint, render_template from flask_login import login_required, current_user from vhoops.modules.home.forms.user_profile import General, ChangePassword from vhoops.modules.alerts.api.controllers import get_alerts_func from vhoops.modules.teams.api.controllers import get_all_teams_func from vhoops.modules.users.api.controllers import get_all_users_func home_router = Blueprint("home_router", __name__) @home_router.route("/home", methods=["GET"]) @login_required def user_home_page(): return render_template( "home/home-page.html", alerts=get_alerts_func(filters="status:open"), teams=get_all_teams_func(), users=get_all_users_func() ) @home_router.route("/profile", methods=["GET"]) @login_required def user_profile_page(): # General section form form_general = General() form_general.first_name.render_kw["value"] = current_user.first_name form_general.last_name.render_kw["value"] = current_user.last_name form_general.email.render_kw["value"] = current_user.email form_general.phone.render_kw["value"] = current_user.phone_number # Change password section form change_password_form = ChangePassword() return render_template( "home/user-profile.html", form_general=form_general, change_password_form=change_password_form )
[ { "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
vhoops/modules/home/ui/routes.py
yigitbasalma/vhoops
from django.contrib.auth.models import User def get_anonymous_user(): """ Get the user called "anonymous" if it exist. Create the user if it doesn't exist This is the default concordia user if someone is working on the site without logging in first. """ try: return User.objects.get(username="anonymous") except User.DoesNotExist: return User.objects.create_user(username="anonymous") def request_accepts_json(request): accept_header = request.META.get("HTTP_ACCEPT", "*/*") return "application/json" in accept_header
[ { "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
concordia/utils.py
ptrourke/concordia
# -*- coding: utf-8 -*- """ Created on Tue Apr 7 17:58:09 2020 @author: Leonardo Saccotelli """ import numpy as np """ FORMULA DEI TRAPEZI Al metodo vengono passati: - la funzione integranda - l'estremo inferiore di integrazione - l'estremo superiore di integrazione """ def Trapezoid(f_x, a, b): #Calcolo l'integrale T = (b-a)*(f_x(a)+f_x(b))/2 return T """ FORMULA DEI TRAPEZI COMPOSTI Al metodo vengono passati: - la funzione integranda - l'estremo inferiore di integrazione - l'estremo superiore di integrazione - il numero di intervallini """ def CompositeTrapezoid(f_x, a, b, N): #Estrpolo N+1 intervalli equidistanti da [a,b] z = np.linspace(a,b,N+1) #Calcolo f_x() in ogni punto di z fz = f_x(z) S = 0 #Calcolo del trapezio composto for i in range(1,N): S = S + fz[i] TC = (fz[0] + 2*S + fz[N])*(b-a)/2/N return TC """ FORMULA DI SIMPSON Al metodo vengono passati: - la funzione integranda - l'estremo inferiore di integrazione - l'estremo superiore di integrazione """ def Simpson(f_x, a, b): #Calcolo l'integrale T = ((b-a)/6) * (f_x(a) +4 * f_x((b+a)/2) + f_x(b)) return T """ FORMULA DI SIMPSON COMPOSTA Al metodo vengono passati: - la funzione integranda - l'estremo inferiore di integrazione - l'estremo superiore di integrazione - il numero di intervalli """ def CompositeSimpson(f, a, b, N): #Genero n+1 intervallini in [a,b] z = np.linspace(a,b,N+1) #Calcolo f negli intervalli z fz = f(z) #Definisco le somme dispari e le somme pari S_d = 0 S_p = 0 #Definisco l'ampiezza dei singoli intervalli h = (b-a)/N #Calcolo le somme dispari for i in range(1,N,2): S_d = S_d + fz[i] #Calcolo le somme pari for i in range(2,N-1,2): S_p = S_p + fz[i] Tsc = (fz[0] + 4*S_d + 2*S_p + fz[N])*h/3 return Tsc
[ { "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
5_Quadrature Formulas/Algoritmi_Quadratura.py
LeonardoSaccotelli/Numerical-Calculus-Project
import pathlib import os import invoke TOP_LEVEL = [ 'shim', 'snafu', ] CURDIR = pathlib.Path(__file__, '..') def _run_for_each(ctx, cmd): for p in TOP_LEVEL: # Can't use Path.resolve() because it can return a UNC path, which # ctx.cd() does not accept. with ctx.cd(os.path.abspath(CURDIR.joinpath(p))): ctx.run(cmd) @invoke.task() def build(ctx, release=False, verbose=False): build_params = [ '--release' * release, '--verbose' * verbose, ] _run_for_each(ctx, 'cargo build {}'.format(' '.join(build_params))) @invoke.task() def clean(ctx): _run_for_each(ctx, 'cargo clean') @invoke.task() def test(ctx): _run_for_each(ctx, 'cargo test')
[ { "point_num": 1, "id": "all_params_annotated", "question": "Does every function parameter in this file have a type annotation (excluding self/cls)?", "answer": false }, { "point_num": 2, "id": "has_nested_function_def", "question": "Does this file contain any function defined inside...
3
shims/__init__.py
uranusjr/snafu
# coding: utf-8 from __future__ import absolute_import from datetime import date, datetime # noqa: F401 from typing import List, Dict # noqa: F401 from jobbing.models.base_model_ import Model from jobbing import util class WorkingArea(Model): def __init__(self, working_area_id:int = None, working_area_municipality:int = None): # noqa: E501 self.swagger_types = { 'working_area_id': int, 'working_area_municipality': int } self.attribute_map = { 'working_area_id': 'working_area_id', 'working_area_municipality': 'working_area_municipality' } self._working_area_id = working_area_id self._working_area_municipality = working_area_municipality @classmethod def from_dict(cls, dikt) -> 'WorkingArea': return util.deserialize_model(dikt, cls) @property def working_area_id(self) -> int: return self._working_area_id @working_area_id.setter def working_area_id(self, param): if param is None: raise ValueError("Invalid value for `working_area_id`, must not be `None`") # noqa: E501 self._working_area_id = param @property def working_area_municipality(self) -> int: return self._working_area_municipality @working_area_municipality.setter def working_area_municipality(self, param): if param is None: raise ValueError("Invalid value for `working_area_municipality`, must not be `None`") # noqa: E501 self._working_area_municipality = param
[ { "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
jobbing/models_remote/working_area.py
davidall-amdocs/jobbing
#!/usr/bin/env python3 # coding: utf-8 from slackclient import SlackClient from .config import SLACK_TOKEN class SlackPoster: def __init__(self, token, channels): self.client = SlackClient(token) self.channels = channels def post(self, message): for ch in self.channels: self.client.api_call( 'chat.postMessage', channel=ch, text=message, as_user=False, username='scholarbot' ) _poster = None def post_to_slack(message, channels): global _poster if _poster is None: _poster = SlackPoster(SLACK_TOKEN, channels) _poster.post(message)
[ { "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
scholar_bot/post_slack.py
finsberg/scholar_bot
#Definir exceptions class UsernameDuplicado(Exception): pass class IdadeMenor(Exception): pass class IdadeInvalida(Exception): pass class EmailInvalido(Exception): pass class User: def __init__(self, username, idade, email): self.__username = username self.__idade = idade self.__email = email def getUserName(self): return self.__username def getIdade(self): return self.__idade def getEmail(self): return self.__email if __name__ == "__main__": listaExemplo = [ ("paulo", "paulo@gmail.com", 21), ("maria", "maria@gmail.com", 19), ("antonio", "antonio@gmail.com", 25), ("pedro", "pedro@gmai.com", 15), ("marisa", "marisa", 23), ("ana", "ana@gmail.com", -22), ("maria", "maria@gmail.com", 27) ] cadastro = {} for username, email, idade in listaExemplo: try: if username in cadastro: raise UsernameDuplicado() if idade < 0: raise IdadeInvalida() if idade < 18: raise IdadeMenor() emailpartes = email.split('@') if len(emailpartes) != 2 or not emailpartes[0] or not emailpartes[1]: raise EmailInvalido() else: cadastro[username] = User(username, idade, email) except UsernameDuplicado: print("Username %s ja está em uso" % username) except IdadeInvalida: print("Idade inválida: %d" % idade) except IdadeMenor: print("Usuario %s tem idade inferior a permitida" % username) except EmailInvalido: print("%s não é um endereço de email válido" % 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": "all_return_types_annotated", "question": "Does every function in this file have a return ...
3
Aulas/Aula11/exercicio.py
matheusmenezs/com220
import os import pickle import torch SPECIAL_WORDS = {'PADDING': '<PAD>'} def load_data(path): """ Load Dataset from File """ input_file = os.path.join(path) with open(input_file, "r") as f: data = f.read() return data def preprocess_and_save_data(dataset_path, token_lookup, create_lookup_tables): """ Preprocess Text Data """ text = load_data(dataset_path) # Ignore notice, since we don't use it for analysing the data text = text[81:] token_dict = token_lookup() for key, token in token_dict.items(): text = text.replace(key, ' {} '.format(token)) text = text.lower() text = text.split() vocab_to_int, int_to_vocab = create_lookup_tables(text + list(SPECIAL_WORDS.values())) int_text = [vocab_to_int[word] for word in text] pickle.dump((int_text, vocab_to_int, int_to_vocab, token_dict), open('preprocess.p', 'wb')) def load_preprocess(): """ Load the Preprocessed Training data and return them in batches of <batch_size> or less """ return pickle.load(open('preprocess.p', mode='rb')) def save_model(filename, decoder): save_filename = os.path.splitext(os.path.basename(filename))[0] + '.pt' torch.save(decoder, save_filename) def load_model(filename): save_filename = os.path.splitext(os.path.basename(filename))[0] + '.pt' print(save_filename) return torch.load(save_filename)
[ { "point_num": 1, "id": "every_function_under_20_lines", "question": "Is every function in this file shorter than 20 lines?", "answer": true }, { "point_num": 2, "id": "all_function_names_snake_case", "question": "Are all function names in this file written in snake_case?", "answ...
3
3. Generate TV scripts/helper.py
mihir135/deep_learning_nanodegree
from probs import Binomial class TestBinomial: @staticmethod def test_binomial() -> None: d = Binomial() assert d.expectation() == 0 assert d.variance() == 0 # TODO: Python 3.7 implementation differs from 3.8+ # assert P(d == 0) == 1 # assert P(d == 1) == 0 # assert P(d == 2) == 0 # d = Binomial(n=6, p=0.7) # assert P(d == 0) == 0.000729 # assert P(d == 1) == 0.010206 # assert P(d == 2) == 0.059535 # assert P(d == 3) == 0.18522 # assert P(d == 4) == 0.324135 # assert P(d == 5) == 0.302526 # assert P(d == 6) == 0.117649 # assert P(d == 7) == 0 @staticmethod def test_sum() -> None: d = Binomial() + Binomial() assert d.expectation() == 0 assert d.variance() == 0 # TODO assert d.pmf == {} # assert P(d == 2) == 1 / 36 # assert P(d == 8) == 5 / 36 # assert P(d == 60) == 0 @staticmethod def test_repr() -> None: d = Binomial() + Binomial() assert str(d) == "Binomial(pmf={}, n=0, p=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_function_names_snake_case", "question": "Are all function names in this file written in snake_case?", "answer": ...
3
tests/discrete/binomial_test.py
TylerYep/probs
""" .. module: lemur.plugins.bases.source :platform: Unix :copyright: (c) 2015 by Netflix Inc., see AUTHORS for more :license: Apache, see LICENSE for more details. .. moduleauthor:: Kevin Glisson <kglisson@netflix.com> """ from lemur.plugins.base import Plugin class SourcePlugin(Plugin): type = 'source' default_options = [ { 'name': 'pollRate', 'type': 'int', 'required': False, 'helpMessage': 'Rate in seconds to poll source for new information.', 'default': '60', } ] def get_certificates(self, options, **kwargs): raise NotImplementedError def get_endpoints(self, options, **kwargs): raise NotImplementedError def clean(self, certificate, options, **kwargs): raise NotImplementedError @property def options(self): return self.default_options + self.additional_options
[ { "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
lemur/plugins/bases/source.py
prdonahue/lemur
import sys import pytest from organizer.util.arguments import is_option @pytest.mark.parametrize("arg", ['verbose', 'silent', 'dry-run', 'ignored', 'exists']) def test_have_arguments(arg: str): sys.argv = ['--' + arg] assert is_option(arg) @pytest.mark.parametrize("arg", ['verbose', 'silent', 'dry-run', 'ignored', 'exists']) def test_no_have_arguments(arg: str): sys.argv = [] assert not is_option(arg)
[ { "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/utils/arguments_test.py
darkanakin41/media-organizer
import logging from pathlib import Path import numpy as np import simulacra as si import simulacra.units as u import matplotlib.pyplot as plt FILE_NAME = Path(__file__).stem OUT_DIR = Path(__file__).parent / "out" / FILE_NAME def w(z, w_0, z_0): return w_0 * np.sqrt(1 + ((z / z_0) ** 2)) def R(z, z_0): return z * (1 + ((z_0 / z) ** 2)) def guoy_phase(z, z_0): return np.arctan(z / z_0) def field(x, z, w_0, wavelength): z_0 = u.pi * (w_0 ** 2) / wavelength k = u.twopi / wavelength w_z = w(z, w_0, z_0) amplitude = (w_0 / w_z) * np.exp(-((x / w_z) ** 2)) phase = np.exp(1j * k * (x ** 2) / (2 * R(z, z_0))) * np.exp( -1j * guoy_phase(z, z_0) ) return amplitude * phase if __name__ == "__main__": with si.utils.LogManager( "simulacra", stdout_logs=True, stdout_level=logging.DEBUG ) as logger: w_0 = 1 * u.um wavelength = 500 * u.nm x_lim = 10 * u.um z_lim = 50 * u.um pnts = 500 x = np.linspace(-x_lim, x_lim, pnts) z = np.linspace(-z_lim, z_lim, pnts) x_mesh, z_mesh = np.meshgrid(x, z, indexing="ij") field_mesh = field(x_mesh, z_mesh, w_0=w_0, wavelength=wavelength) si.vis.xyz_plot( f"gaussian_beam", z_mesh, x_mesh, field_mesh, title=rf"Gaussian Beam w/ $\lambda = {wavelength / u.nm:.1f} \, \mathrm{{nm}}, \, w_0 = {w_0 / u.um:.1f} \, \mathrm{{\mu m}}$", x_label="z", y_label="x", x_unit="um", y_unit="um", colormap=plt.get_cmap("richardson"), richardson_equator_magnitude=0.1, target_dir=OUT_DIR, )
[ { "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_params_annotated", "question": "Does every function parameter in this file have a type annotation (excluding self/...
3
dev/gaussian_beam.py
JoshKarpel/simulacra
import math from collections import Counter # Collect BLEU-relevant statistics for a single hypothesis/reference pair. # Return value is a generator yielding: # (c, r, numerator1, denominator1, ... numerator4, denominator4) # Summing the columns across calls to this function on an entire corpus will # produce a vector of statistics that can be used to compute BLEU (below) def bleu_stats(hypothesis, reference): yield len(hypothesis) yield len(reference) for n in xrange(1,5): s_ngrams = Counter([tuple(hypothesis[i:i+n]) for i in xrange(len(hypothesis)+1-n)]) r_ngrams = Counter([tuple(reference[i:i+n]) for i in xrange(len(reference)+1-n)]) yield max([sum((s_ngrams & r_ngrams).values()), 0]) yield max([len(hypothesis)+1-n, 0]) # Compute BLEU from collected statistics obtained by call(s) to bleu_stats def bleu(stats): if len(filter(lambda x: x==0, stats)) > 0: return 0 (c, r) = stats[:2] log_bleu_prec = sum([math.log(float(x)/y) for x,y in zip(stats[2::2],stats[3::2])]) / 4. return math.exp(min([0, 1-float(r)/c]) + log_bleu_prec)
[ { "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
reranker/bleu.py
wangka11/wordAlignment
# coding: utf-8 """ Isilon SDK Isilon SDK - Language bindings for the OneFS API # noqa: E501 OpenAPI spec version: 2 Contact: sdk@isilon.com Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import unittest import isi_sdk_7_2 from isi_sdk_7_2.models.worm_settings_extended import WormSettingsExtended # noqa: E501 from isi_sdk_7_2.rest import ApiException class TestWormSettingsExtended(unittest.TestCase): """WormSettingsExtended unit test stubs""" def setUp(self): pass def tearDown(self): pass def testWormSettingsExtended(self): """Test WormSettingsExtended""" # FIXME: construct object with mandatory attributes with example values # model = isi_sdk_7_2.models.worm_settings_extended.WormSettingsExtended() # 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
isi_sdk_7_2/test/test_worm_settings_extended.py
mohitjain97/isilon_sdk_python
# -*- coding: utf-8 -*- """ :author: Grey Li (李辉) :url: http://greyli.com :copyright: © 2018 Grey Li :license: MIT, see LICENSE for more details. """ import click from flask import Flask app = Flask(__name__) # the minimal Flask application # app.route()装饰器把根地址(/)和函数index()绑定起来,当用户访问该URL(/)时就触发此函数index() @app.route('/') def index(): return '<h1>Hello, World!</h1>' # bind multiple URL for one view function @app.route('/hi') @app.route('/hello') def say_hello(): return '<h1>Hello, Flask!</h1>' # dynamic route, URL variable default # 绑定动态URL,即URL除了写死的基本部分(/greet),用户还可手动写入(<name>) @app.route('/greet', defaults={'name': 'Programmer'}) @app.route('/greet/<name>') def greet(name): return '<h1>Hello, %s!</h1>' % name # custom flask cli command @app.cli.command() def hello(): """Just say hello.""" click.echo('Hello, Human!') # 执行flask run时,该命令运行的开发服务器默认会监听http://127.0.0.1:5000, # http://127.0.0.1即localhost,是指向本地机的IP地址,而5000端口是Flask默认使用的端口。
[ { "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
demos/hello/app.py
yunlinzi/helloflask
class AuthError(ValueError): def __init__(self, message, code=None): if code: self.code = code super().__init__(message) class PermissionDenied(AuthError): def __init__(self, message, code=None): if code: self.code = code super().__init__(message)
[ { "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
chowkidar/utils/exceptions.py
aswinshenoy/chowkidar-ariadne
from ncssl_api_client.config.api.api_client_production_config import ApiProductionClientConfig from ncssl_api_client.config.crypto.crypto_config import CryptoConfig from ncssl_api_client.config.api.api_client_sandbox_config import ApiSandboxClientConfig from ncssl_api_client.config.api.api_command_config import ApiCommandConfig class ConfigManager: @staticmethod def get_api_sandbox_client_config(): return ApiSandboxClientConfig() @staticmethod def get_api_production_client_config(): return ApiProductionClientConfig() @staticmethod def get_api_command_config(): return ApiCommandConfig() @staticmethod def get_crypto_config(): return CryptoConfig()
[ { "point_num": 1, "id": "has_nested_function_def", "question": "Does this file contain any function defined inside another function?", "answer": false }, { "point_num": 2, "id": "has_multiple_inheritance", "question": "Does any class in this file use multiple inheritance?", "answ...
3
ncssl_api_client/config/manager.py
antonku/ncssl_api_client
from __future__ import annotations import abc from alocacao.adapters import repository from alocacao.config import DEFAULT_SESSION_FACTORY class AbstractUOW(abc.ABC): produtos: repository.AbstractRepository def __enter__(self) -> AbstractUOW: return self def __exit__(self, *args): self.rollback() def commit(self): self._commit() def collect_new_messages(self): for produto in self.produtos.seen: while produto.eventos: yield produto.eventos.pop(0) @abc.abstractmethod def _commit(self): pass @abc.abstractmethod def rollback(self): pass class SQLAlchemyUOW(AbstractUOW): def __init__(self, session_factory=DEFAULT_SESSION_FACTORY): self.session_factory = session_factory def __enter__(self): self.session = self.session_factory() self.produtos = repository.TrackingRepository( repository.SQLAlchemyRepository(self.session) ) return super().__enter__() def __exit__(self, *args): super().__exit__(*args) self.session.close() def _commit(self): self.session.commit() def rollback(self): self.session.rollback()
[ { "point_num": 1, "id": "every_class_has_docstring", "question": "Does every class in this file have a docstring?", "answer": false }, { "point_num": 2, "id": "more_functions_than_classes", "question": "Does this file define more functions than classes?", "answer": true }, { ...
3
src/alocacao/camada_servicos/unit_of_work.py
ralphribeiro/APWP-T2