max_stars_repo_path stringlengths 3 269 | max_stars_repo_name stringlengths 4 119 | max_stars_count int64 0 191k | id stringlengths 1 7 | content stringlengths 6 1.05M | score float64 0.23 5.13 | int_score int64 0 5 |
|---|---|---|---|---|---|---|
jdb2/__init__.py | spdir/jsonDB2 | 1 | 12795151 | # -*- coding: utf-8 -*-
__author = 'Musker.Chao'
__version = '0.2.2'
from .jdb import NoSql
| 1.070313 | 1 |
SchemaCollaboration/core/migrations/0007_add_defaults.py | Swiss-Polar-Institute/schema-collaboration-arctic-century | 15 | 12795152 | # Generated by Django 3.1.4 on 2020-12-01 15:25
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0006_suggestions_from_django_doctor'),
]
operations = [
migrations.AlterField(
model_name='datapackage',
nam... | 1.515625 | 2 |
src/exts/automod.py | vcokltfre/hbot-rewrite | 2 | 12795153 | <gh_stars>1-10
from os import environ
from disnake import AllowedMentions, Message, TextChannel
from disnake.ext.commands import Cog
from disnake.http import Route
from src.impl.bot import Bot
CHANNELS = [int(c) for c in environ["CHANNELS"].split(";")]
LOGS = int(environ["LOGS"])
class AutoMod(Cog):
def __init... | 2.3125 | 2 |
tenet/simulation.py | ferrouswheel/tenet | 7 | 12795154 | import random
import logging
import networkx as nx
from tenet.message import (
Message,
DictTransport, MessageSerializer, MessageTypes
)
from tenet.peer import Peer, Friend
from tenet.utils import weighted_choice
log = logging.getLogger(__name__)
class SimulatedPeer(object):
def __init... | 2.828125 | 3 |
protostar/commands/test/test_collector.py | software-mansion/protostar | 11 | 12795155 | <filename>protostar/commands/test/test_collector.py
# pylint: disable=no-self-use
import re
from collections import defaultdict
from dataclasses import dataclass
from fnmatch import fnmatch
from glob import glob
from logging import Logger
from pathlib import Path
from time import time
from typing import Dict, List, Op... | 1.851563 | 2 |
loopchain/container/tx_service.py | extendjh/loopchain | 2 | 12795156 | <reponame>extendjh/loopchain
# Copyright 2017 theloop, 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 applicabl... | 2.109375 | 2 |
openGaussBase/testcase/SQL/DCL/Set_Session_Authorization/Opengauss_Function_Set_Session_Authorization_Case0007.py | opengauss-mirror/Yat | 0 | 12795157 | """
Copyright (c) 2022 Huawei Technologies Co.,Ltd.
openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:
http://license.coscl.org.cn/MulanPSL2
THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, W... | 1.632813 | 2 |
Software/RMSDReducer.py | hrch3n/cNMA | 3 | 12795158 | <gh_stars>1-10
'''
Created on Jan 24, 2014
@author: oliwa
'''
from prody.measure.measure import calcDeformVector
import numpy as np
from prody.dynamics.compare import calcOverlap
from prody.dynamics.mode import Vector
from prody.measure.transform import calcRMSD
from scipy.sparse.linalg import cg
from timeout import t... | 1.820313 | 2 |
migrations/versions/002fd410a290_002_owner_id_type.py | LandRegistry/digital-street-title-api | 0 | 12795159 | <reponame>LandRegistry/digital-street-title-api<filename>migrations/versions/002fd410a290_002_owner_id_type.py<gh_stars>0
"""empty message
Revision ID: 002fd410a290
Revises: <KEY>
Create Date: 2019-02-05 13:40:59.112652
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revi... | 1.3125 | 1 |
skelpy/makers/license.py | Steap/skelpy | 0 | 12795160 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""This module defines :class:`LicenseMaker` class."""
from __future__ import absolute_import, print_function
import os
import datetime
from . import settings
from .base import BaseMaker
#: Supported licenses, corresponding template file names, and descriptions
_LICENS... | 2.46875 | 2 |
tests/test_cpu_increment_instructions.py | Hexadorsimal/pynes | 1 | 12795161 | import unittest
from nes.processors.cpu import Cpu
from nes.bus import Bus
from nes.bus.devices.memory import Ram
class CpuIncrementInstructionsTestCase(unittest.TestCase):
def setUp(self):
bus = Bus()
bus.attach_device('RAM', Ram(256), 0, 256)
self.cpu = Cpu(bus)
def test_inc(self):
... | 3.046875 | 3 |
apps/account/tests/tests_custom_user_account.py | nfeslim/dashboard_nfe | 0 | 12795162 | from django.test import TestCase
from apps.account.models import CustomUser
class TestsCustomUserModel(TestCase):
def setUp(self):
self.data_insert = {
"email": "<EMAIL>",
"first_name": "Teste01",
"last_name": "Last",
"is_staff": False,
"is_acti... | 2.734375 | 3 |
thelper/infer/impl.py | beaulima/thelper | 17 | 12795163 | """Explicit Tester definitions from existing Trainers."""
import thelper.concepts
from thelper.infer.base import Tester
from thelper.train.classif import ImageClassifTrainer
from thelper.train.detect import ObjDetectTrainer
from thelper.train.regr import RegressionTrainer
from thelper.train.segm import ImageSegmTraine... | 2.09375 | 2 |
pipeline/tests/test_model.py | pkgpkr/Packge-Picker | 2 | 12795164 | """
Tests for the pipeline model
"""
import os
import unittest
import psycopg2
from model.database import update_bounded_similarity_scores, \
update_popularity_scores, update_trending_scores, \
package_table_postprocessing, write_similarity_scores
class TestModel(unittest.TestCase):
@classmethod
... | 2.828125 | 3 |
executor.py | jina-ai/executor-tagshasher | 1 | 12795165 | import hashlib
import json
import numpy as np
from jina import Executor, DocumentArray, requests
class TagsHasher(Executor):
"""Convert an arbitrary set of tags into a fixed-dimensional matrix using the hashing trick.
Unlike FeatureHashser, you should only use Jaccard/Hamming distance when searching docume... | 3.25 | 3 |
web/addons/gamification/__openerp__.py | diogocs1/comps | 1 | 12795166 | <reponame>diogocs1/comps
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2013 OpenERP SA (<http://openerp.com>).
#
# This program is free software: you can redistribute it and/or modify
# it u... | 1.585938 | 2 |
utils/test/rknn.py | stephanballer/deepedgebench | 1 | 12795167 | <reponame>stephanballer/deepedgebench<filename>utils/test/rknn.py<gh_stars>1-10
from rknn.api import RKNN
from time import time
from utils.img_utils import load_preproc_images
from time import time
def inference_rknn(model_path, datatype, input_dims, dataset, batch_size, repeat):
timestamps, results = list(), list... | 2.09375 | 2 |
p006.py | ChubsB/ProjectEuler | 0 | 12795168 | # Find the absolute difference between the sum of the squares of the first natural numbers and the square of the sum
N = 3
def test(N):
SquareSum = 0
SumSquare = 0
for i in range(1,N+1):
SquareSum += i*i
SumSquare += i
SumSquare = SumSquare * SumSquare
return SumSquare - SquareSum
print(test(N))
| 3.921875 | 4 |
pdfbuilder/sampletemplates.py | citizenengagementlab/django-pdfbuilder | 1 | 12795169 | from pdfbuilder import registry
from pdfbuilder.basetemplates import BaseDocTemplateWithHeaderAndFooter as BaseDocTemplate
from pdfbuilder.basetemplates import OneColumnBaseDocTemplateWithHeaderAndFooter as OneColumnDocTemplate
from pdfbuilder.basetemplates import PDFTemplate
from reportlab.lib import colors
from repo... | 2.421875 | 2 |
python/example/p_chapter05_04.py | groovallstar/test2 | 0 | 12795170 | # Chapter05-04
# 파이썬 심화
# 데코레이터
# 장점
# 1. 중복 제거, 코드 간결, 공통 함수 작성
# 2. 로깅, 프레임워크, 유효성 체크..... -> 공통 기능
# 3. 조합해서 사용 용이
# 단점
# 1. 가독성 감소?
# 2. 특정 기능에 한정된 함수는 -> 단일 함수로 작성하는 것이 유리
# 3. 디버깅 불편
# 데코레이터 실습
import time
def perf_clock(func):
def perf_clocked(*args):
# 함수 시작 시간
st = time.perf_counter()... | 2.8125 | 3 |
Notebooks/Visualization/DataReader.py | keuntaeklee/pytorch-PPUU | 159 | 12795171 | """A class with static methods which can be used to access the data about
experiments.
This includes reading logs to parse success cases, reading images, costs
and speed.
"""
import numpy as np
from glob import glob
import torch
import pandas
import re
import json
from functools import lru_cache
import imageio
EPISO... | 2.96875 | 3 |
src/genie/libs/parser/iosxe/tests/ShowLldpNeighborsDetail/cli/equal/golden_output_3_expected.py | balmasea/genieparser | 204 | 12795172 | expected_output = {
"interfaces": {
"GigabitEthernet1/0/32": {
"if_name": "GigabitEthernet1/0/32",
"port_id": {
"222": {
"neighbors": {
"not advertised": {
"neighbor_id": "not advertised",
... | 1.359375 | 1 |
tests/test_ksvd_simple.py | manvhah/pyksvd | 70 | 12795173 | <filename>tests/test_ksvd_simple.py
from ksvd import KSVD
import numpy.random as rn
from numpy import array, zeros, dot
if __name__ == "__main__":
factor = 2
dict_size = 5
target_sparsity = 3
n_examples = 10
dimension = 4
rs = rn.RandomState(0)
D = rs.normal(size = (dict_size, dimension... | 2.453125 | 2 |
two_additon.py | ykf173/coding_everyday | 0 | 12795174 | class ListNode():
def __init__(self, val):
if isinstance(val, int):
self.val = val
self.next = None
elif isinstance(val, list):
self.val = val[0]
self.next = None
cur = self
for i in val[1:]:
cur.next = ListNode... | 3.40625 | 3 |
src/exams/models.py | GiomarOsorio/another-e-learning-platform | 0 | 12795175 | <filename>src/exams/models.py
from django.core.validators import MaxValueValidator, MinValueValidator
from django.utils.translation import gettext_lazy as _
from django.core.exceptions import ObjectDoesNotExist
from courses.models import Content
from django.utils import timezone
from django.urls import reverse
from ope... | 2.234375 | 2 |
benchmark/bm_mutable_complicated_params.py | ryanlevy/pennylane | 1 | 12795176 | # Copyright 2018-2020 Xanadu Quantum 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... | 1.953125 | 2 |
netbox/utilities/querysets.py | BrnoPCmaniak/netbox | 6 | 12795177 | class DummyQuerySet:
"""
A fake QuerySet that can be used to cache relationships to objects that have been deleted.
"""
def __init__(self, queryset):
self._cache = [obj for obj in queryset.all()]
def all(self):
return self._cache
| 2.65625 | 3 |
demo/mock_view.py | shuai93/drf-demo | 2 | 12795178 | from rest_framework.decorators import (
api_view,
permission_classes,
authentication_classes,
renderer_classes,
)
from rest_framework.permissions import AllowAny
from rest_framework.response import Response
from rest_framework.authentication import BaseAuthentication
from rest_framework.renderers import... | 2.125 | 2 |
images/views.py | Cyci25/Gallery | 0 | 12795179 | <gh_stars>0
from django.shortcuts import render, redirect
from django.http import HttpResponse, Http404, HttpResponseRedirect
import datetime as dt
# Create your views here.
def welcome(request):
return render(request, 'image.html')
def image(request, id):
try:
image = Image.objects.get(pk = id)
... | 2.28125 | 2 |
Unidad 2/packages/extra/ugly/omega.py | angelxehg/utzac-ppy | 0 | 12795180 | def funO():
pass
| 0.949219 | 1 |
snippet/snippet.py | ARMmbed/snippet | 4 | 12795181 | #
# Copyright (C) 2020 Arm Mbed. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
"""Text snippet extractor."""
from typing import List, Optional
from snippet import exceptions
from snippet.config import Config
class Example:
"""An example."""
def __init__(self, path: str, line_num: int, example... | 2.671875 | 3 |
permissions/file_permissions.py | mohitbaviskar/http_server | 0 | 12795182 |
#this is dictionary with permissions about dir.
#first one is for read
#second for write
#0 => not allowed
#1 => allowed
dir_per = {
'/',
'/assets',
'/proxy',
'/samplefortemp'
}
prox = ['./documentroot/proxy/proxyfile.html']
proxy_user = ['ram:123']
temporary = {'./documentroot/temp.html':'samp... | 1.984375 | 2 |
src/WF_WaitForFile.py | SynerClust/SynerClust | 7 | 12795183 | #!/usr/bin/env python
import sys, os, time
def usage():
print "WF_WaitForFile.py [file's dir] [file] [frequency - default=60s]"
sys.exit(1)
def main(argv):
fileDir = argv[0]
file = argv[1]
freq = 60
if len(argv) > 2:
freq = int(argv[2])
file_found = 0
while not file_found:
dirFiles = os.listdir(fileDir... | 3.0625 | 3 |
tests/test_space.py | letmaik/exhaust | 1 | 12795184 | import exhaust
def test_double_iteration():
def gen(state: exhaust.State):
return state.maybe()
space = exhaust.space(gen)
assert len(set(space)) == 2
assert len(set(space)) == 2
| 2.875 | 3 |
ispmanccp/lib/ispman_helpers.py | UfSoft/python-perl | 0 | 12795185 | # -*- coding: utf-8 -*-
# vim: sw=4 ts=4 fenc=utf-8
# =============================================================================
# $Id: ispman_helpers.py 84 2006-11-27 04:12:13Z s0undt3ch $
# =============================================================================
# $URL: http://ispmanccp.ufsoft.org... | 1.523438 | 2 |
Securinets/2021/Quals/web/Warmup/app.py | mystickev/ctf-archives | 1 | 12795186 | from itsdangerous import Signer, base64_encode, base64_decode
from flask import Flask, request, render_template, make_response, g, Response
from flask.views import MethodView
import urlparse
import shutil
import utils
import os
import mimetypes
app = Flask(__name__.split('.')[0])
app.config.from_object(__name__)
BUF... | 2.109375 | 2 |
osmchadjango/roulette_integration/utils.py | jbronn/osmcha-django | 27 | 12795187 | import json
from os.path import join
import requests
from django.conf import settings
def remove_unneeded_properties(feature):
keys_to_remove = [
key for key in feature['properties'].keys()
if key.startswith('osm:') or key.startswith('result:')
]
for key in keys_to_remove:
fea... | 2.140625 | 2 |
python/main_zmq.py | fjctp/find_prime_numbers | 0 | 12795188 | #!/bin/env python3
import argparse
import zmq
import threading
import json
import time
from libs.mylib import is_prime
def parse_args():
parser = argparse.ArgumentParser(description='Find all prime number in a range (from 2).')
parser.add_argument('max', type=int, default=1000,
help='... | 2.625 | 3 |
tests/test_prone.py | 612twilight/CogDL-TensorFlow | 85 | 12795189 | <gh_stars>10-100
import os
import sys
sys.path.append('../')
def test_prone():
os.system("python ../scripts/train.py --task unsupervised_node_classification --dataset wikipedia --model prone --seed 0 1 2 3 4 --hidden-size 2")
pass
if __name__ == "__main__":
test_prone() | 1.632813 | 2 |
testflows/_core/cli/arg/handlers/report/coverage.py | testflows/TestFlows-Core | 3 | 12795190 | # Copyright 2019 Katteli Inc.
# TestFlows.com Open-Source Software Testing Framework (http://testflows.com)
#
# 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/lice... | 1.539063 | 2 |
lorentz_embeddings/lorentz.py | lambdaofgod/lorentz-embeddings | 0 | 12795191 | <gh_stars>0
import os
import sys
import torch
import random
import numpy as np
from torch import nn
from torch import optim
from tqdm import trange, tqdm
from collections import Counter
from datetime import datetime
from tensorboardX import SummaryWriter
from torch.utils.data import Dataset, DataLoader
import datasets
... | 2.265625 | 2 |
tests/conftest.py | sanger/lighthouse | 1 | 12795192 | import copy
import os
from http import HTTPStatus
from unittest.mock import MagicMock, patch
import pytest
import responses
from lighthouse import create_app
from lighthouse.constants.events import PE_BECKMAN_SOURCE_ALL_NEGATIVES, PE_BECKMAN_SOURCE_COMPLETED
from lighthouse.constants.fields import (
FIELD_CHERRYT... | 1.8125 | 2 |
FoxhoundApp/FoxhoundApp/TrafficApp/urls.py | Anton250/MoscowCityHack2021_FoxoundTeam | 0 | 12795193 | <reponame>Anton250/MoscowCityHack2021_FoxoundTeam
from django.conf.urls import url, include
from rest_auth.views import (
LoginView,
LogoutView,
UserDetailsView
)
from rest_framework import routers
from FoxhoundApp.TrafficApp.views import ItemsView, HeatMapView
rest_auth_urls = [
url(r'^login/$', Login... | 1.96875 | 2 |
djnic/cambios/migrations/0003_auto_20201013_2210.py | avdata99/nic | 8 | 12795194 | <reponame>avdata99/nic
# Generated by Django 3.1.2 on 2020-10-14 01:10
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('cambios', '0002_campocambio_uid_anterior'),
]
operations = [
migrations.AlterField(
model_name='campocamb... | 1.515625 | 2 |
tests/utils/test_throttle.py | binderjoe/sdu-commons | 0 | 12795195 | from botocore.exceptions import ClientError
from osdu_commons.utils.throttle import throttle_exception, ThrottledBotoResource
class Counter:
def __init__(self):
self.counter = 0
def count(self):
self.counter += 1
def test_throttle_exception():
class BogusException(Exception):
p... | 2.546875 | 3 |
qt/CurrencyListModel.py | BradleyCSO/university-thesis | 0 | 12795196 | <filename>qt/CurrencyListModel.py
from PyQt5.QtCore import QModelIndex
from PyQt5.QtGui import QStandardItem, QStandardItemModel
from core import AppCore
class CurrencyListModel(QStandardItemModel):
"""
Model which fetches all known symbols
from the DB and displays them in a list
"""
core = AppCo... | 2.875 | 3 |
odata/navproperty.py | altedra/ODAlchemy | 0 | 12795197 | # -*- coding: utf-8 -*-
"""
Navigation properties
---------------------
The entity can define properties that link to other entities. These are known
as navigation properties and are supported in this library.
.. code-block:: python
>>> order = Service.query(Order).first()
>>> order.Shipper
<Entity(Ship... | 3.34375 | 3 |
billingyard/cli.py | MartinVondrak/billing-yard | 0 | 12795198 | <reponame>MartinVondrak/billing-yard<gh_stars>0
import click
from .billingyard import BillingYard
from .models import Invoice
@click.group('billingyard')
@click.option('-s', '--sender', type=str, default='sender.json')
@click.option('-t', '--template', type=str)
@click.pass_context
def cli(ctx, sender: str, template... | 2.125 | 2 |
python/pynamodb/pynamodb-test/blog.py | kskumgk63/trace-examples | 75 | 12795199 | <gh_stars>10-100
from pynamodb.models import Model
from pynamodb.attributes import UnicodeAttribute
class Blog(Model):
class Meta:
table_name='Blog'
region = 'us-west-1'
write_capacity_units = 1
read_capacity_units = 1
host = "http://dynamodb:8000"
title = UnicodeAttribute(hash_key=True)
con... | 2.421875 | 2 |
examples/vn_trader/data_download.py | ZJMXX/vnpy | 2 | 12795200 | <gh_stars>1-10
import time
from datetime import datetime
from backtest_entrance.setting import Info
from vnpy.app.data_manager import DataManagerApp
from vnpy.app.data_manager.engine import ManagerEngine
from vnpy.event import EventEngine
from vnpy.gateway.binance import BinanceGateway
from vnpy.gateway.binances impor... | 1.710938 | 2 |
examples/FigureCanvas.py | Ellis0817/Introduction-to-Programming-Using-Python | 0 | 12795201 | from tkinter import * # Import tkinter
class FigureCanvas(Canvas):
def __init__(self, container, figureType, filled = False,
width = 100, height = 100):
super().__init__(container,
width = width, height = height)
self.__figureType = figureType
... | 3.3125 | 3 |
file_handlers.py | EpocDotFr/microsoft-sticky-notes-kanboard-sync | 0 | 12795202 | from watchdog.events import PatternMatchingEventHandler
from utils import debug
from urllib.parse import unquote
from rtf.Rtf2Markdown import getMarkdown
import watchdog.events
import olefile
import sqlite3
import configparser
import codecs
import threading
class FileHandlerInterface(PatternMatchingEventHandler):
... | 2.375 | 2 |
src/backend/django_messages_drf/utils.py | jeremyd4500/senior-project-2020 | 0 | 12795203 | <gh_stars>0
"""
All Utils used on this package module live here
"""
from django.db import models
from functools import wraps
def cached_attribute(func):
cache_name = f"_{func.__name__}"
@wraps(func)
def inner(self, *args, **kwargs):
if hasattr(self, cache_name):
return getattr(self, c... | 2.453125 | 2 |
crawler/RISJbot/spiders/newsspecifiedspider.py | ausnews/ausnews-search | 10 | 12795204 | # -*- coding: utf-8 -*-
import logging
from scrapy.spiders import Spider
from scrapy.http import Request
logger = logging.getLogger(__name__)
# This spider is a base for those attempting to crawl and parse a specified
# list of URLs rather than using an RSS feed or a sitemap. It needs the
# SPECIFIED_URIS_FILE settin... | 2.90625 | 3 |
unit5/problem_sets/1_1/solution/u5_ps1_1_p_6_7.py | ga-at-socs/pa-2021-code | 0 | 12795205 | # -*- coding: utf-8 -*-
"""
Practical Algorthns
Problem set: Unit 5, 1.1
Problem statement:
4. Modify your binary search algorithm (from #3) to work with words rather
than integers. Test it on a small list of words, e.g.,
["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"].
The search... | 4.21875 | 4 |
index_2/np_dot.py | specbug/nnfs | 0 | 12795206 | import numpy as np
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
dot_product = np.dot(a, b)
print(dot_product) | 3.34375 | 3 |
Text.py | Joseph-Barker/cst205-group16-project | 0 | 12795207 | """
<NAME>, <NAME>, <NAME>, <NAME>, <NAME>
CST 205 Project: Group 16
Text.py
5/8/2020
This class is responsible for handling text extracted from image.
"""
class Text:
"""A simple class to define text extracted from an image"""
def __init__( self, text, app_window ):
# instance variables unique to each instan... | 3.046875 | 3 |
calculate.py | cu-swe4s-fall-2020/version-control-maclyne | 1 | 12795208 | #!/usr/bin/env python
# File: calculate.py
# Initial date: 4 Sept 2020
# Author: <NAME>
# School assignment: For Assignment #0 of class MCDB6440: Software Engineering for Scientists
# Description: Intro to using GitHub Classroom. Practice with creating and uploading files to github etc.
# This file imports funcitons... | 3.78125 | 4 |
tests/test_httpbroker.py | scieloorg/scieloapi.py | 1 | 12795209 | <filename>tests/test_httpbroker.py
import unittest
import mocker
from scieloapi import httpbroker, exceptions
import doubles
class CheckHttpStatusTests(unittest.TestCase):
def test_400_raises_BadRequest(self):
response = doubles.RequestsResponseStub()
response.status_code = 400
self.as... | 2.53125 | 3 |
maui/backend/serial/partition.py | cstatz/maui | 0 | 12795210 | <reponame>cstatz/maui<filename>maui/backend/serial/partition.py
# -*- coding: utf-8 -*-
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
__author__ = 'christoph.statz <at> tu-dresden.de'
from numpy import ndindex
from maui.backend.helper import calc_local... | 2.328125 | 2 |
shift_detector/utils/ucb_list.py | hpi-bp1819-naumann/shift-detector | 3 | 12795211 | <reponame>hpi-bp1819-naumann/shift-detector
# from https://stackoverflow.com/questions/243831/unicode-block-of-a-character-in-python
def block(character):
""" Return the Unicode block name for character, or None if character has no block.
from https://stackoverflow.com/questions/243831/unicode-block-of-a-char... | 3.25 | 3 |
subsequence_tree.py | luvalenz/time-series-variability-tree | 1 | 12795212 | <filename>subsequence_tree.py
import numpy as np
from sklearn.cluster import AffinityPropagation
#import pydotplus as pydot
from collections import Counter
from distance_utils import time_series_twed
import pandas as pd
class SubsequenceTree:
def __init__(self, max_level, prototype_subsequences_list,
... | 2.546875 | 3 |
tests/contrib/backends/hbase/test_domain_cache.py | buildfail/frontera | 1,267 | 12795213 | <filename>tests/contrib/backends/hbase/test_domain_cache.py<gh_stars>1000+
# -*- coding: utf-8 -*-
from frontera.contrib.backends.hbase.domaincache import DomainCache
from happybase import Connection
import logging
import unittest
class TestDomainCache(unittest.TestCase):
def setUp(self):
logging.basicCon... | 2.140625 | 2 |
opnsense_cli/callbacks/click.py | jan-win1993/opn-cli | 13 | 12795214 | import yaml
import os
from opnsense_cli.facades.commands.base import CommandFacade
from opnsense_cli.factories.cli_output_format import CliOutputFormatFactory
from opnsense_cli.formats.base import Format
"""
Click callback methods
See: https://click.palletsprojects.com/en/8.0.x/advanced/#parameter-modifications
"""
... | 2.3125 | 2 |
ceda_intake/database_handler.py | cedadev/ceda-intake | 0 | 12795215 | import psycopg2
import os
class DBHandler:
_max_id_length = 255
_max_record_length = 255
def __init__(self, table_name="intake_records", error_table_name="scan_errors"):
"""
:param table_name: (str) Optional string name of the main db table.
:param error_table_name: (str) Op... | 3.3125 | 3 |
cogs/util/file_handling.py | dd0lynx/Toast-Bot | 0 | 12795216 | <filename>cogs/util/file_handling.py<gh_stars>0
import os, os.path
import errno
import json
def mkdir_p(path):
try:
os.makedirs(path)
except OSError as e:
if e.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise
def load_json(path):
data = {}
... | 2.671875 | 3 |
tests/cv/utils/test_iou.py | SkalskiP/onemetric | 48 | 12795217 | from contextlib import ExitStack as DoesNotRaise
from typing import Tuple, Optional
import numpy as np
import pytest
from onemetric.cv.utils.iou import box_iou, mask_iou, box_iou_batch
@pytest.mark.parametrize(
"box_true, box_detection, expected_result, exception",
[
(None, None, None, pytest.raises... | 2.109375 | 2 |
Synapse/Synapse Unsupervised Model.py | Zeel2864/Synapse_ML | 1 | 12795218 |
"""
@author: <NAME>,<NAME>
"""
import numpy as np
import streamlit as st
import pandas as pd
import plotly.graph_objects as go
import plotly.express as px
st.title("Synapse Unsupervised Models")
uploaded_file = st.file_uploader("Choose a csv file", type="csv")
if uploaded_file is not None:
data = pd.read_csv(... | 3.171875 | 3 |
main.py | digitaltembo/kismet | 0 | 12795219 | <filename>main.py
from application import app
app = app
| 1.132813 | 1 |
aiopoke/objects/resources/moves/move.py | beastmatser/aiopokeapi | 3 | 12795220 | <gh_stars>1-10
from typing import TYPE_CHECKING, Any, Dict, List, Optional
from aiopoke.objects.resources.contests.super_contest_effect import SuperContestEffect
from aiopoke.objects.resources.pokemon.ability import AbilityEffectChange
from aiopoke.objects.utility import (
MachineVersionDetail,
Name,
Named... | 1.90625 | 2 |
tests/spam_test.py | peixinchen/spam | 2 | 12795221 | import spam
def TestSystem():
r = spam.system("ls -l")
assert r == 0
def TestNothingDone():
r = spam.nothing_done()
assert r is None
| 2.359375 | 2 |
repo_health/check_makefile.py | edly-io/edx-repo-health | 0 | 12795222 | """
Checks to see if Makefile follows standards
"""
import re
import os
import pytest
from pytest_repo_health import add_key_to_metadata
from repo_health import get_file_content
module_dict_key = "makefile"
@pytest.fixture(name='makefile')
def fixture_makefile(repo_path):
"""Fixture containing the text content... | 2.375 | 2 |
infra/migrations/0003_instancemodel.py | Maulikchhabra/Terraform-Console | 0 | 12795223 | <gh_stars>0
# Generated by Django 3.1.5 on 2021-02-11 06:19
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('infra', '0002_keymodel_region'),
]
operations = [
migrations.CreateModel(
name='InstanceModel',
... | 1.703125 | 2 |
BB/bbObjects/battles/BattleShip.py | Laura7089/GOF2BountyBot | 6 | 12795224 | from ..items.modules import bbCloakModule
from ..items import bbShip
class BattleShip:
"""A class representing ships participting in a duel.
The ship has three health pools; hull, armour and shield.
"""
def __init__(self, bbShip : bbShip.bbShip):
"""
:param bbShip bbShip: The bbShip f... | 3.34375 | 3 |
tensorflow_data_validation/utils/stats_util.py | rtg0795/data-validation | 0 | 12795225 | <filename>tensorflow_data_validation/utils/stats_util.py
# Copyright 2018 Google LLC
#
# 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
#
# Un... | 1.828125 | 2 |
Mars_Scraping/scraping.py | SiMewL8/Mission-To-Mars | 0 | 12795226 | # --------------------------------------------------------------------------------------------------------------------------------
# Imports and Executables
# --------------------------------------------------------------------------------------------------------------------------... | 1.875 | 2 |
Aula 14/ex059P.py | alaanlimaa/Python_CVM1-2-3 | 0 | 12795227 | <reponame>alaanlimaa/Python_CVM1-2-3<filename>Aula 14/ex059P.py<gh_stars>0
from time import sleep
n1 = int(input('Primeiro Valor: '))
n2 = int(input('Segundo valor: '))
opcao = 0
while opcao != 5:
print(''' [ 1 ] Somar
[ 2 ] Multiplicar
[ 3 ] Maior
[ 4 ] Novos Números
[ 5 ] Sair do programa''')
... | 3.53125 | 4 |
bookwyrm/models/status.py | daveross/bookwyrm | 0 | 12795228 | ''' models for storing different kinds of Activities '''
from django.utils import timezone
from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models
from model_utils.managers import InheritanceManager
from bookwyrm import activitypub
from .base_model import ActivitypubMixin, ... | 2.15625 | 2 |
utils/__init__.py | JacobChen258/AI-Constraints-Satisfaction | 0 | 12795229 | <reponame>JacobChen258/AI-Constraints-Satisfaction
from .directions import Direction
from .directions import direction_to_vector
from .directions import vector_to_direction
from .constants import ASSETS
from .constants import LINE_LIMIT
from .constants import TILESIZE
from .constants import TETROMINO_GRID_SIZE
from .c... | 0.851563 | 1 |
src/GameObject.py | LangArthur/FlappyBird-AILearning | 1 | 12795230 | <filename>src/GameObject.py
#!/usr/bin/python3
# implementing a gameObject
class GameObject():
# constructor
# param x: the window of the game
def __init__(self, x, y, displayable):
self.x = x
self.y = y
self.displayable = displayable
# draw the gameObject
# param window: ... | 3.1875 | 3 |
crossbaker/libs/softFinder.py | josephkirk/MeshBaker | 0 | 12795231 | <filename>crossbaker/libs/softFinder.py
from io import StringIO
import traceback
import wmi
from winreg import (HKEY_LOCAL_MACHINE, KEY_ALL_ACCESS,
OpenKey, EnumValue, QueryValueEx)
softFile = open('softLog.log', 'w')
errorLog = open('errors.log', 'w')
r = wmi.Registry ()
result, names = r.Enu... | 2.03125 | 2 |
tests/sfmutils/test_stream_consumer.py | NGTmeaty/sfm-utils | 2 | 12795232 | from __future__ import absolute_import
from unittest import TestCase
from mock import MagicMock, patch
import socket
import tempfile
import os
import shutil
from sfmutils.consumer import MqConfig
from sfmutils.stream_consumer import StreamConsumer
from sfmutils.supervisor import HarvestSupervisor
class TestStreamCons... | 2.171875 | 2 |
p25.py | fiskenslakt/aoc-2021 | 0 | 12795233 | from itertools import count
from aocd import lines
rows = len(lines)
cols = len(lines[0])
_map = {}
east = []
south = []
for y, line in enumerate(lines):
for x, sc in enumerate(line):
if sc == '>':
east.append((x,y))
elif sc == 'v':
south.append((x,y))
_map[(x,y)] ... | 2.859375 | 3 |
src/SpectralAnalysis/bayes.py | axr6077/Black-Hole-X-ray-binary-Evolution | 1 | 12795234 | from __future__ import print_function
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator
try:
import cPickle as pickle
except ImportError:
import pickle
import copy
import numpy as np
from src.SpectralAnalysis import utils
from src.SpectralAnalysis import powerspectrum
from src.Spect... | 2.34375 | 2 |
various/closure.py | sideroff/python-exercises | 0 | 12795235 |
def parent(msg, flag: bool):
local_variable = '15'
print('parent executed {}'.format(msg))
def first_child():
print('first_child {}'.format(msg))
def second_child():
print('first_child {}, {}'.format(msg, local_variable))
return (
first_child if flag
else ... | 2.90625 | 3 |
Text/LSTM.py | walter114/TIPRDC | 13 | 12795236 | import torch.nn as nn
import torch
import torch.nn.functional as F
from torch.autograd import Variable
class FeatureExtractor(nn.Module):
def __init__(self, voacb_size, embedding_dim=300, hidden_dim=300):
super(FeatureExtractor, self).__init__()
self.embedding_dim = embedding_dim
self.hi... | 2.90625 | 3 |
src/testing/task_plot_private_test_demand_shares.py | covid-19-impact-lab/sid-germany | 4 | 12795237 | import warnings
import matplotlib.pyplot as plt
import pandas as pd
import pytask
import seaborn as sns
from src.config import BLD
from src.config import PLOT_END_DATE
from src.config import PLOT_SIZE
from src.config import PLOT_START_DATE
from src.config import SRC
from src.plotting.plotting import style_plot
from s... | 2.234375 | 2 |
services/trainer/lib/network.py | ZeshanA/transport | 1 | 12795238 | import json
import logging
from typing import Dict
import numpy
class ClientSet:
def __init__(self):
self.sockets_by_host_id = {}
self.route_ids_by_host_id = {}
self.host_ids_by_socket = {}
def add(self, host_id, socket):
logging.info(f"Registered hostID '{host_id}'")
... | 2.65625 | 3 |
scsr_api/user/api.py | hiperlogic/scsr-api | 1 | 12795239 | <reponame>hiperlogic/scsr-api<filename>scsr_api/user/api.py<gh_stars>1-10
from flask.views import MethodView
from flask import jsonify, request, abort, render_template
import uuid
import json
from jsonschema import Draft4Validator
from jsonschema.exceptions import best_match
from datetime import datetime
from sys_app.... | 2.28125 | 2 |
acmicpc/3058.py | juseongkr/BOJ | 7 | 12795240 | <reponame>juseongkr/BOJ
for _ in range(int(input())):
l = [*map(int, input().split())]
s, m = 0, []
for i in l:
if i % 2 == 0:
s += i
m.append(i)
m.sort()
print(s, end=' ')
print(m[0])
| 2.875 | 3 |
dict_zip/__init__.py | kitsuyui/dict_zip | 0 | 12795241 | import functools
def dict_zip(*dictionaries):
common_keys = functools.reduce(lambda x, y: x | y,
(set(d.keys()) for d in dictionaries),
set())
return {
key: tuple(d[key] for d in dictionaries)
for key in common_keys
... | 3.3125 | 3 |
tests/test_utils.py | Ouranosinc/Magpie | 0 | 12795242 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_utils
----------------------------------
Tests for the various utility operations employed by Magpie.
"""
import os
import unittest
from distutils.version import LooseVersion
import mock
import six
from pyramid.httpexceptions import HTTPBadRequest, HTTPForbidden... | 2.1875 | 2 |
tableloader/tableFunctions/volumes.py | DEQC/yamlloader | 0 | 12795243 | import os
import csv
from sqlalchemy import Table,literal_column,select
def importVolumes(connection, metadata, source_path):
invVolumes = Table('invVolumes', metadata)
invTypes = Table('invTypes', metadata)
with open(
os.path.join(source_path, 'invVolumes1.csv'), 'r'
) as groupVolumes:
... | 2.734375 | 3 |
msgvis/apps/importer/models.py | hds-lab/textvis-drg | 10 | 12795244 | <reponame>hds-lab/textvis-drg
import sys, six
from django.db import IntegrityError
from django.utils.timezone import utc
from urlparse import urlparse
import json
from datetime import datetime
from email.utils import parsedate
from msgvis.apps.questions.models import Article, Question
from msgvis.apps.corpus.models im... | 2.203125 | 2 |
theape/plugins/sleep_plugin.py | rsnakamura/theape | 0 | 12795245 |
# python standard library
from collections import OrderedDict
# third party
from configobj import ConfigObj
# this package
from theape import BasePlugin
from theape.parts.sleep.sleep import TheBigSleep
from theape.infrastructure.timemap import time_validator
SLEEP_SECTION = 'SLEEP'
END_OPTION = 'end'
TOTAL_OPTION =... | 2.65625 | 3 |
bnbapp/bionetbook/_old/verbs/views.py | Bionetbook/bionetbook | 0 | 12795246 | <reponame>Bionetbook/bionetbook<gh_stars>0
from django.http import Http404
from django.views.generic import TemplateView
from verbs import forms as verb_forms
from verbs.utils import VERB_LIST
class VerbBaseView(object):
def get_verb_form(self, slug=None):
if slug is None:
slug = self.kwar... | 2.1875 | 2 |
stk/connect.py | jolsten/STK | 1 | 12795247 | # -*- coding: utf-8 -*-
"""
Created on Tue Aug 4 20:13:37 2020
@author: jolsten
"""
import sys, logging
import socket
import time
from abc import ABCMeta, abstractmethod
from .exceptions import *
from .utils import STK_DATEFMT, inherit_docstrings
class _AbstractConnect(metaclass=ABCMeta):
'''An... | 2.890625 | 3 |
xcparse/Xcode/PBX/PBXResourcesBuildPhase.py | samdmarshall/xcparser | 59 | 12795248 | from .PBXResolver import *
from .PBX_Base_Phase import *
class PBXResourcesBuildPhase(PBX_Base_Phase):
def __init__(self, lookup_func, dictionary, project, identifier):
super(PBXResourcesBuildPhase, self).__init__(lookup_func, dictionary, project, identifier);
self.bundleid = 'com.apple.buildp... | 1.875 | 2 |
src/simplestack/hypervisors/xen.py | locaweb/simplestack | 9 | 12795249 | # Copyright 2013 Locaweb.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | 1.859375 | 2 |
mathematica/style.py | DbxDev/pygments-mathematica | 62 | 12795250 | <gh_stars>10-100
# -*- coding: utf-8 -*-
# Copyright (c) 2016 rsmenon
# Licensed under the MIT License (https://opensource.org/licenses/MIT)
from pygments.style import Style
from mathematica.lexer import MToken
class MathematicaStyle(Style):
default_style = ''
background_color = '#fefefe'
styles = {
... | 1.523438 | 2 |