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
tests/test_data/lazy_mod.py
brettcannon/modutil
17
3000
import modutil mod, __getattr__ = modutil.lazy_import(__name__, ['tests.test_data.A', '.B', '.C as still_C']) def trigger_A(): return mod.A def trigger_B(): return mod.B def trigger_C(): return mod.still_C def trigger_failure(): return mod.does_not_exist
1.9375
2
test.py
xiaohuaibaoguigui/EllSeg
1
3001
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os import sys import tqdm import torch import pickle import resource import numpy as np import matplotlib.pyplot as plt from args import parse_args from modelSummary import model_dict from pytorchtools import load_from_file from torch.utils.data import DataLoader ...
1.960938
2
tests/test_util.py
meskio/tuf
1
3002
#!/usr/bin/env python """ <Program Name> test_util.py <Author> <NAME>. <Started> February 1, 2013. <Copyright> See LICENSE for licensing information. <Purpose> Unit test for 'util.py' """ # Help with Python 3 compatibility, where the print statement is a function, an # implicit relative import is invali...
2.828125
3
background/forms.py
BFlameSwift/AirplaneReservationSystem
3
3003
from django import forms class FlightrForm(forms.Form): flight_number = forms.CharField(max_length=30, label="航班号", widget=forms.TextInput(attrs={'class': 'form-control'})) plane_type_choices = [ ('波音', ( ('1', '747'), ('2', '777'), ('3', '787'), ) ...
2.25
2
cams/propressing/data_rotate.py
boliqq07/cam3d
1
3004
<gh_stars>1-10 from functools import lru_cache from math import cos, sin import scipy from scipy.ndimage import affine_transform import numpy as np @lru_cache(maxsize=10) def get_matrix(angles=(90, 90, 90), inverse=False): """ Axis of rotation Get matrix by angle. (shear+compress) Examples: z = 120 ...
2.796875
3
playground/conversions/parser/lola2dot.py
flange/esp
0
3005
#!/usr/bin/env python import sys #lolafile = open("ex-small.graph", "r") source = 0 target = 0 lowlink = 0 trans = "bla" print("digraph {") with open(sys.argv[1]) as lolafile: for line in lolafile: if len(line) == 1: continue linelist = line.split(" ") if "STATE" in linelist: ...
3.140625
3
engkor/views.py
takeshixx/dprkdict
10
3006
<gh_stars>1-10 import re import urllib.parse from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse, JsonResponse from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage from .models import Definition RE_HANGUL = re.compile(r'[(]*[\uAC00-\uD7AF]+[\uAC00-\uD7AF ()...
2.21875
2
appdaemon/apps/toggle_switch/toggle_switch.py
Mithras/ha
3
3007
<reponame>Mithras/ha import globals class ToggleSwitch(globals.Hass): async def initialize(self): config = self.args["config"] self._input = config["input"] self._toggle_service = config["toggle_service"] self._toggle_payload = config["toggle_payload"] self._power = config[...
2.34375
2
templates_deepdive_app_bagofwords/udf/dd_extract_features.py
charlieccarey/rdoc
0
3008
<filename>templates_deepdive_app_bagofwords/udf/dd_extract_features.py<gh_stars>0 #!/usr/bin/env python from __future__ import print_function ''' 1\taaaa~^~bbbb~^~cccc 2\tdddd~^~EEEE~^~ffff ''' import sys ARR_DELIM = '~^~' for row in sys.stdin: row = row.strip() sent_id, lemmas = row.split('\t') lemmas ...
2.390625
2
src/supplier/templates/supplier/urls.py
vandana0608/Pharmacy-Managament
0
3009
from django.urls import path from . import views urlpatterns = [ path('', views.SupplierList.as_view(), name='supplier_list'), path('view/<int:pk>', views.SupplierView.as_view(), name='supplier_view'), path('new', views.SupplierCreate.as_view(), name='supplier_new'), path('view/<int:pk>', views.Suppli...
1.765625
2
web_scraper/extract/common.py
rarc41/web_scraper_pro
0
3010
<reponame>rarc41/web_scraper_pro<filename>web_scraper/extract/common.py import yaml __config=None def config(): global __config if not __config: with open('config.yaml', mode='r') as f: __config=yaml.safe_load(f) return __config
2.0625
2
engine/config/constant.py
infiniteloop98/lazies-cmd
1
3011
APP_PROFILE_DIRECTORY_NAME = 'lazies-cmd' DOSKEY_FILE_NAME = 'doskey.bat' AUTO_RUN_REGISTRY_NAME = 'AutoRun'
1.117188
1
sequence/get_seqs_from_list.py
fanglu01/cDNA_Cupcake
1
3012
#!/usr/bin/env python import os, sys from Bio import SeqIO def get_seqs_from_list(fastafile, listfile): seqs = [line.strip() for line in open(listfile)] for r in SeqIO.parse(open(fastafile), 'fasta'): if r.id in seqs or r.id.split('|')[0] in seqs or any(r.id.startswith(x) for x in seqs): pr...
3.578125
4
ppos_dex_data.py
cusma/pposdex
10
3013
<gh_stars>1-10 import time import json import base64 import msgpack from schema import Schema, And, Optional from datetime import datetime from algosdk import mnemonic from algosdk.account import address_from_private_key from algosdk.error import * from algosdk.future.transaction import PaymentTxn from inequality_inde...
2.25
2
src/test/python/programmingtheiot/part01/unit/system/SystemMemUtilTaskTest.py
Zhengrui-Liu/FireAlarmingSysCDA
0
3014
##### # # This class is part of the Programming the Internet of Things # project, and is available via the MIT License, which can be # found in the LICENSE file at the top level of this repository. # # Copyright (c) 2020 by <NAME> # import logging import unittest from programmingtheiot.cda.system.SystemMemUtilTask...
2.9375
3
api/base/settings/defaults.py
mattclark/osf.io
0
3015
""" Django settings for api project. Generated by 'django-admin startproject' using Django 1.8. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ """ import os from url...
1.945313
2
tests/__init__.py
GTedHa/gblackboard
0
3016
# -*- coding: utf-8 -*- """Unit test package for gblackboard."""
0.875
1
src/fabricflow/fibc/api/fibcapis_pb2_grpc.py
RudSmith/beluganos
119
3017
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! import grpc import fibcapi_pb2 as fibcapi__pb2 import fibcapis_pb2 as fibcapis__pb2 class FIBCApApiStub(object): # missing associated documentation comment in .proto file pass def __init__(self, channel): """Constructor. Args: ...
1.71875
2
cymbology/identifiers/__init__.py
pmart123/security_id
12
3018
<gh_stars>10-100 from cymbology.identifiers.sedol import Sedol from cymbology.identifiers.cusip import Cusip, cusip_from_isin from cymbology.identifiers.isin import Isin __all__ = ('Sedol', 'Cusip', 'cusip_from_isin', 'Isin')
1.734375
2
api/src/error_report/models.py
Noahffiliation/corpus-christi
35
3019
from marshmallow import Schema, fields from marshmallow.validate import Range, Length from sqlalchemy import Column, Integer, Boolean, DateTime from ..db import Base from ..shared.models import StringTypes # ---- Error-report class ErrorReport(Base): __tablename__ = 'error_report' id = Column(Integer, prim...
2.421875
2
Python/Vowel-Substring/solution.py
arpitran/HackerRank_solutions
0
3020
<reponame>arpitran/HackerRank_solutions #!/bin/python3 import math import os import random import re import sys # # Complete the 'findSubstring' function below. # # The function is expected to return a STRING. # The function accepts following parameters: # 1. STRING s # 2. INTEGER k # def isVowel(x): if(x=="...
3.984375
4
nima/models/productos/constants.py
erichav/NIMA
0
3021
<reponame>erichav/NIMA COLLECTION = 'productos'
0.910156
1
deepchem/metrics/score_function.py
hsjang001205/deepchem
1
3022
<reponame>hsjang001205/deepchem<filename>deepchem/metrics/score_function.py """Evaluation metrics.""" import numpy as np from sklearn.metrics import matthews_corrcoef # noqa from sklearn.metrics import recall_score # noqa from sklearn.metrics import cohen_kappa_score from sklearn.metrics import r2_score # noqa from...
2.234375
2
hvm/chains/base.py
hyperevo/py-helios-node
0
3023
<reponame>hyperevo/py-helios-node from __future__ import absolute_import import operator from collections import deque import functools from abc import ( ABCMeta, abstractmethod ) import rlp_cython as rlp import time import math from uuid import UUID from typing import ( # noqa: F401 Any, Optional, ...
1.570313
2
integreat_cms/api/v3/regions.py
Integreat/cms-django
21
3024
<filename>integreat_cms/api/v3/regions.py """ This module includes functions related to the regions API endpoint. """ from django.http import JsonResponse from ...cms.models import Region from ...cms.constants import region_status from ..decorators import json_response def transform_region(region): """ Funct...
2.578125
3
cli/src/ansible/AnsibleVarsGenerator.py
romsok24/epiphany
0
3025
<filename>cli/src/ansible/AnsibleVarsGenerator.py import copy import os from cli.src.Config import Config from cli.src.helpers.build_io import (get_ansible_path, get_ansible_path_for_build, get_ansible_vault_path) from cli.src.helpers.data_loa...
1.945313
2
Python/4 kyu/Snail/test_snail.py
newtonsspawn/codewars_challenges
3
3026
<filename>Python/4 kyu/Snail/test_snail.py<gh_stars>1-10 from unittest import TestCase from snail import snail class TestSnail(TestCase): def test_snail_001(self): self.assertEqual(snail([[]]), []) def test_snail_002(self): self.assertEqual(snail([[1]]), [1]) def test_snail...
2.765625
3
python/tink/jwt/_raw_jwt.py
cuonglm/tink
0
3027
<gh_stars>0 # Copyright 2021 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 # # Unless required by applicable law or agreed to ...
2.140625
2
plenum/test/view_change/test_no_instance_change_before_node_is_ready.py
evernym/indy-plenum
0
3028
import pytest from plenum.server.view_change.view_changer import ViewChanger from stp_core.common.log import getlogger from plenum.test.pool_transactions.helper import start_not_added_node, add_started_node logger = getlogger() @pytest.fixture(scope="module", autouse=True) def tconf(tconf): old_vc_timeout = tc...
2.03125
2
src/cache/requests_cache_abstract.py
tomaszkingukrol/rest-api-cache-proxy
0
3029
<reponame>tomaszkingukrol/rest-api-cache-proxy from abc import ABC, abstractclassmethod from model.response import ResponseModel class CacheInterface(ABC): @abstractclassmethod async def get(cls, url: str) -> ResponseModel: pass @abstractclassmethod async def set(cls, url: str, value: ResponseModel,...
2.59375
3
dialogue-engine/test/programytest/config/file/test_json.py
cotobadesign/cotoba-agent-oss
104
3030
""" Copyright (c) 2020 COTOBA DESIGN, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distri...
1.796875
2
searching/jump_search.py
magnusrodseth/data-structures-and-algorithms
0
3031
import math from typing import List def jump_search(array: List[int], value: int) -> int: """ Performs a jump search on a list of integers. :param array: is the array to search. :param value: is the value to search. :return: the index of the value, or -1 if it doesn't exist.' """ if len(ar...
4.40625
4
pincer/objects/message/sticker.py
mjneff2/Pincer
0
3032
<reponame>mjneff2/Pincer # Copyright Pincer 2021-Present # Full MIT License can be found in `LICENSE` at the project root. from __future__ import annotations from dataclasses import dataclass from enum import IntEnum from typing import List, Optional, TYPE_CHECKING from ...utils.api_object import APIObject from ...u...
2.40625
2
app/core/utils.py
yayunl/llfselfhelp
0
3033
from django.views.generic import \ UpdateView as BaseUpdateView class UpdateView(BaseUpdateView): template_name_suffix = '_form_update'
1.320313
1
demo/test_bug_3d.py
zhanwj/multi-task-pytorch
2
3034
import torch import lib.modeling.resnet as resnet import lib.modeling.semseg_heads as snet import torch.nn as nn import torch.optim as optim import utils.resnet_weights_helper as resnet_utils from torch.autograd import Variable from roi_data.loader import RoiDataLoader, MinibatchSampler, collate_minibatch, collate_mini...
1.914063
2
regenesis/modelgen.py
crijke/regenesis
16
3035
<reponame>crijke/regenesis<filename>regenesis/modelgen.py import json from regenesis.queries import get_cubes, get_all_dimensions, get_dimensions from pprint import pprint def generate_dimensions(): dimensions = [] for dimension in get_all_dimensions(): pprint (dimension) if dimension.get('mea...
2.453125
2
tests/components/evil_genius_labs/test_light.py
liangleslie/core
30,023
3036
<gh_stars>1000+ """Test Evil Genius Labs light.""" from unittest.mock import patch import pytest from homeassistant.components.light import ( ATTR_COLOR_MODE, ATTR_SUPPORTED_COLOR_MODES, ColorMode, LightEntityFeature, ) from homeassistant.const import ATTR_SUPPORTED_FEATURES @pytest.mark.parametrize...
2.1875
2
python_on_whales/download_binaries.py
joshbode/python-on-whales
0
3037
import platform import shutil import tempfile import warnings from pathlib import Path import requests from tqdm import tqdm DOCKER_VERSION = "20.10.5" BUILDX_VERSION = "0.5.1" CACHE_DIR = Path.home() / ".cache" / "python-on-whales" TEMPLATE_CLI = ( "https://download.docker.com/{os}/static/stable/{arch}/docker-...
2.296875
2
reinvent-2019/connected-photo-booth/lambda_code/Cerebro_GetQRCode.py
chriscoombs/aws-builders-fair-projects
0
3038
import boto3 import json import os import logging from contextlib import closing from boto3.dynamodb.conditions import Key, Attr from botocore.exceptions import ClientError from random import shuffle import time import pyqrcode import png __BUCKET_NAME__ = "project-cerebro" dynamo = boto3.client('dynamodb') logg...
2.15625
2
dependencies/svgwrite/tests/test_drawing.py
charlesmchen/typefacet
21
3039
<filename>dependencies/svgwrite/tests/test_drawing.py #!/usr/bin/env python #coding:utf-8 # Author: mozman --<<EMAIL>> # Purpose: test drawing module # Created: 11.09.2010 # Copyright (C) 2010, <NAME> # License: GPLv3 from __future__ import unicode_literals import os import unittest from io import StringIO...
2.3125
2
src/cms/views/error_handler/error_handler.py
digitalfabrik/coldaid-backend
4
3040
<reponame>digitalfabrik/coldaid-backend<gh_stars>1-10 from django.shortcuts import render from django.utils.translation import ugettext as _ # pylint: disable=unused-argument def handler400(request, exception): ctx = {'code': 400, 'title': _('Bad request'), 'message': _('There was an error in your requ...
2.15625
2
examples/ex3/app/models.py
trym-inc/django-msg
7
3041
from typing import NamedTuple from django.contrib.auth.models import AbstractUser from django.db import models from msg.models import Msg class User(AbstractUser): phone_number: 'str' = models.CharField(max_length=255, null=True, blank=True) class HelloSMSMessage(...
2.78125
3
Data_Structures/2d_array_ds.py
csixteen/HackerRank
4
3042
<gh_stars>1-10 matrix = [list(map(int, input().split())) for _ in range(6)] max_sum = None for i in range(4): for j in range(4): s = sum(matrix[i][j:j+3]) + matrix[i+1][j+1] + sum(matrix[i+2][j:j+3]) if max_sum is None or s > max_sum: max_sum = s print(max_sum)
2.875
3
sklearn/utils/_bunch.py
jlopezNEU/scikit-learn
3
3043
<filename>sklearn/utils/_bunch.py class Bunch(dict): """Container object exposing keys as attributes. Bunch objects are sometimes used as an output for functions and methods. They extend dictionaries by enabling values to be accessed by key, `bunch["value_key"]`, or by an attribute, `bunch.value_key`. ...
3.65625
4
tfx/examples/chicago_taxi_pipeline/serving/chicago_taxi_client.py
pingsutw/tfx
1
3044
# Lint as: python2, python3 # Copyright 2019 Google LLC. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless re...
1.6875
2
PyVideo/main.py
BlackIQ/Cute
5
3045
<gh_stars>1-10 from PyQt5.QtCore import (pyqtSignal, pyqtSlot, Q_ARG, QAbstractItemModel, QFileInfo, qFuzzyCompare, QMetaObject, QModelIndex, QObject, Qt, QThread, QTime, QUrl) from PyQt5.QtGui import QColor, qGray, QImage, QPainter, QPalette from PyQt5.QtMultimedia import (QAbstractVideoBuffer, QMediaC...
1.976563
2
tests/snapshot/periodic.py
Uornca/mirheo
22
3046
#!/usr/bin/env python """Test checkpoint-like periodic snapshots. We test that there are that many folders and that the currentStep changes. """ import mirheo as mir u = mir.Mirheo(nranks=(1, 1, 1), domain=(4, 6, 8), debug_level=3, log_filename='log', no_splash=True, checkpoint_every=1...
2.234375
2
tools/resource_prefetch_predictor/generate_database.py
xzhan96/chromium.src
1
3047
<filename>tools/resource_prefetch_predictor/generate_database.py #!/usr/bin/python # # Copyright 2016 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Loads a set of web pages several times on a device, and extracts the ...
2.421875
2
palm_wrapper/job_submission/domain.py
madeline-scyphers/palm
0
3048
from abc import ABC, abstractmethod from typing import Optional from xml import dom import numpy as np import pandas as pd from .utils import get_factors_rev def calc_plot_size(domain_x, domain_y, plot_goal, house_goal): f1 = sorted(get_factors_rev(domain_x)) f2 = sorted(get_factors_rev(domain_y)) plot_...
2.640625
3
zad5.py
Alba126/Laba21
0
3049
#!/usr/bin/env python3 # -*- config: utf-8 -*- from tkinter import * from random import random def on_click(): x = random() y = random() bt1.place(relx=x, rely=y) root = Tk() root['bg'] = 'white' root.title('crown') img = PhotoImage(file='crown.png') bt1 = Button(image=img, command=on_click) bt1.place...
3.5
4
tests/importer/utils/test_utils.py
HumanCellAtlas/ingest-common
0
3050
<gh_stars>0 from openpyxl import Workbook def create_test_workbook(*worksheet_titles, include_default_sheet=False): workbook = Workbook() for title in worksheet_titles: workbook.create_sheet(title) if not include_default_sheet: default_sheet = workbook['Sheet'] workbook.remove(def...
2.453125
2
test/test_import_stats.py
WBobby/pytorch
24
3051
<gh_stars>10-100 import subprocess import sys import unittest import pathlib from torch.testing._internal.common_utils import TestCase, run_tests, IS_LINUX, IS_IN_CI REPO_ROOT = pathlib.Path(__file__).resolve().parent.parent try: # Just in case PyTorch was not built in 'develop' mode sys.path.append(str(REP...
1.984375
2
post_office/validators.py
fasih/django-post_office
661
3052
from django.core.exceptions import ValidationError from django.core.validators import validate_email from django.template import Template, TemplateSyntaxError, TemplateDoesNotExist from django.utils.encoding import force_str def validate_email_with_name(value): """ Validate email address. Both "<NAME> <<...
2.765625
3
paperhub/input.py
GiuseppeBaldini/PaperHub
0
3053
# Input DOI / URL import re import sys # Pyperclip is not built-in, check and download if needed try: import pyperclip except (ImportError, ModuleNotFoundError): print('Pyperclip module not found. Please download it.') sys.exit(0) # Regex for links link_regex = re.compile(r'''( http[s]?:// (?:[a-...
3.3125
3
main.py
chillum1718/EffcientNetV2
0
3054
<filename>main.py import argparse import csv import os import torch import tqdm from torch import distributed from torch.utils import data from torchvision import datasets from torchvision import transforms from nets import nn from utils import util data_dir = os.path.join('..', 'Dataset', 'IMAGENET') def batch(im...
2.46875
2
cgbind/esp.py
duartegroup/cgbind
7
3055
<gh_stars>1-10 import numpy as np from time import time from cgbind.atoms import get_atomic_number from cgbind.log import logger from cgbind.constants import Constants from cgbind.exceptions import CgbindCritical def get_esp_cube_lines(charges, atoms): """ From a list of charges and a set of xyzs create the e...
2.5
2
codes/test_specular.py
mcdenoising/AdvMCDenoise
35
3056
import os import sys import logging import time import argparse import numpy as np from collections import OrderedDict import scripts.options as option import utils.util as util from data.util import bgr2ycbcr from data import create_dataset, create_dataloader from models import create_model # options parser = argpar...
2.015625
2
neuralNetwork/layer3/nerualNet.py
zzw0929/deeplearning
4
3057
<filename>neuralNetwork/layer3/nerualNet.py # coding:utf-8 import time import matplotlib.pyplot as plt import numpy as np import sklearn import sklearn.datasets import sklearn.linear_model import matplotlib matplotlib.rcParams['figure.figsize'] = (10.0, 8.0) np.random.seed(0) X, y = sklearn.datasets.make_moons(200, ...
3.203125
3
app/domain/create_db.py
Lifeistrange/flaskweb
0
3058
<reponame>Lifeistrange/flaskweb<filename>app/domain/create_db.py<gh_stars>0 #!/usr/bin/env python # coding=utf-8 from manage import db import app.domain.model db.create_all()
1.34375
1
tljh_repo2docker/tests/utils.py
TimoRoth/tljh-repo2docker
46
3059
<gh_stars>10-100 import asyncio import json from aiodocker import Docker, DockerError from jupyterhub.tests.utils import api_request async def add_environment( app, *, repo, ref="master", name="", memory="", cpu="" ): """Use the POST endpoint to add a new environment""" r = await api_request( app...
2.453125
2
05_ARIADNE_SUBSCRIPTIONS_GRAPHQL/api/resolvers/mutations/__init__.py
CrispenGari/python-flask
2
3060
from api import db from uuid import uuid4 from ariadne import MutationType from api.models import Post from api.store import queues mutation = MutationType() @mutation.field("createPost") async def create_post_resolver(obj, info, input): try: post = Post(postId=uuid4(), caption=input["caption"]) ...
2.328125
2
async_sched/client/__init__.py
justengel/async_sched
1
3061
<filename>async_sched/client/__init__.py from async_sched.client import quit_server as module_quit from async_sched.client import request_schedules as module_request from async_sched.client import run_command as module_run from async_sched.client import schedule_command as module_schedule from async_sched.client import...
2.0625
2
full-stack-angular-ngrx/backend/src/core/interfaces/crud.py
t4d-classes/angular_02212022
0
3062
import abc from typing import TypeVar, Generic, List, Dict T = TypeVar('T') class CRUDInterface(Generic[T], metaclass=abc.ABCMeta): @abc.abstractmethod def all(self) -> List[T]: pass @abc.abstractmethod def one_by_id(self, entity_id: int) -> T: pass @abc.abstractmethod def ...
3.015625
3
package/tests/test_init_command.py
MrKriss/stonemason
2
3063
<filename>package/tests/test_init_command.py from pathlib import Path import pytest import git import json from conftest import TEST_DIR def test_init_with_project(tmpdir): output_path = Path(tmpdir.strpath) # Set arguments args = f"init -o {output_path} {TEST_DIR}/example_templates/python_project" ...
2.375
2
mistral/mistral/api/controllers/v2/service.py
Toure/openstack_mistral_wip
0
3064
# Copyright 2015 Huawei Technologies Co., Ltd. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
1.726563
2
setup.py
jtauber/greek-utils
13
3065
from setuptools import setup setup( name="greek-utils", version="0.2", description="various utilities for processing Ancient Greek", license="MIT", url="http://github.com/jtauber/greek-utils", author="<NAME>", author_email="<EMAIL>", packages=["greekutils"], classifiers=[ "D...
1.039063
1
source/tweet.py
jfilter/foia-bot
0
3066
""" tweet stuff in intervals """ import time import datetime import twitter from markov_chains import german_text from config import config_no, config_yes MAX_TWEET_LENGTH = 280 greeting = ' Sehr geehrte/r Anstragssteller/in.' ending = ' MfG' num_tweets = 3 class FoiaBot: def __init__(self, config): s...
2.9375
3
account_processing.py
amitjoshi9627/Playong
4
3067
<reponame>amitjoshi9627/Playong from selenium.webdriver import Firefox from selenium.webdriver.firefox.options import Options import getpass import time from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.action_chains import ActionChains from utils import * def login_user(browser, email=''...
2.609375
3
Mundo 3/teste.py
RafaelSdm/Curso-de-Python
1
3068
pessoas = {'nomes': "Rafael","sexo":"macho alfa","idade":19} print(f"o {pessoas['nomes']} que se considera um {pessoas['sexo']} possui {pessoas['idade']}") print(pessoas.keys()) print(pessoas.values()) print(pessoas.items()) for c in pessoas.keys(): print(c) for c in pessoas.values(): print(c) for c, j in pe...
4.34375
4
rsa-cipher/makeRsaKeys.py
mumbo-pro/cyrptography-algorithm
1
3069
# RSA Key Generator 2. # http://inventwithpython.com/hacking (BSD Licensed) 3. 4. import random, sys, os, rabinMiller, cryptomath The program imports the rabinMiller and cryptomath modules that we created in the last chapter, along with a few others. Chapter 24 – Public Key Cryptography and the RSA Cipher 387...
2.78125
3
atlas-outreach-data-tools-framework-1.1/Configurations/PlotConf_TTbarAnalysis.py
Harvard-Neutrino/phys145
0
3070
config = { "Luminosity": 1000, "InputDirectory": "results", "Histograms" : { "WtMass" : {}, "etmiss" : {}, "lep_n" : {}, "lep_pt" : {}, "lep_eta" : {}, "lep_E" : {}, "lep_phi" : {"y_margin" : 0.6}, "lep_...
1.21875
1
modules/optimizations/dead_codes.py
OMGhozlan/deobshell
0
3071
<filename>modules/optimizations/dead_codes.py # coding=utf-8 from ..logger import log_debug from ..utils import parent_map, replace_node, is_prefixed_var, get_used_vars def opt_unused_variable(ast): parents = parent_map(ast) used_vars = get_used_vars(ast) for node in ast.iter(): if node.tag in ["...
2.328125
2
Convert Integer A to Integer B.py
RijuDasgupta9116/LintCode
321
3072
<reponame>RijuDasgupta9116/LintCode """ Determine the number of bits required to convert integer A to integer B Example Given n = 31, m = 14,return 2 (31)10=(11111)2 (14)10=(01110)2 """ __author__ = 'Danyang' class Solution: def bitSwapRequired(self, a, b): """ :param a: :param b: ...
3.578125
4
examples/basic/findQSpark.py
myriadrf/pyLMS7002M
46
3073
from pyLMS7002M import * print("Searching for QSpark...") try: QSpark = QSpark() except: print("QSpark not found") exit(1) print("\QSpark info:") QSpark.printInfo() # print the QSpark board info # QSpark.LMS7002_Reset() # reset the LMS7002M lms700...
2.8125
3
macaddress/__init__.py
paradxum/django-macaddress
42
3074
from django.conf import settings from netaddr import mac_unix, mac_eui48 import importlib import warnings class mac_linux(mac_unix): """MAC format with zero-padded all upper-case hex and colon separated""" word_fmt = '%.2X' def default_dialect(eui_obj=None): # Check to see if a default dialect class has...
2.34375
2
textmagic/test/message_status_tests.py
dfstrauss/textmagic-sms-api-python
2
3075
import time from textmagic.test import ONE_TEST_NUMBER from textmagic.test import THREE_TEST_NUMBERS from textmagic.test import TextMagicTestsBase from textmagic.test import LiveUnsafeTests class MessageStatusTestsBase(TextMagicTestsBase): def sendAndCheckStatusTo(self, numbers): message = 'sdfqwersdfg...
2.46875
2
apps/orders/models.py
LinkanDawang/FreshMallDemo
0
3076
from django.db import models from utils.models import BaseModel from users.models import User, Address from goods.models import GoodsSKU # Create your models here. class OrderInfo(BaseModel): """订单信息""" PAY_METHOD = ['1', '2'] PAY_METHOD_CHOICES = ( (1, "货到付款"), (2, "支付宝"), ) OR...
2.328125
2
event/arguments/prepare/event_vocab.py
hunterhector/DDSemantics
0
3077
<gh_stars>0 from collections import defaultdict, Counter import os import gzip import json import pickle from json.decoder import JSONDecodeError import logging from typing import Dict import pdb from event import util from event.arguments.prepare.slot_processor import get_simple_dep, is_propbank_dep logger = logging...
2.28125
2
20.py
dexinl/kids_math
0
3078
#!/usr/bin/python import random count = 20 test_set = [] while count: a = random.randrange(3,20) b = random.randrange(3,20) if a > b and a - b > 1: if (b, a-b) not in test_set: test_set.append((b, a-b)) count -= 1 elif b > a and b - a > 1: if (a, b-a) not in te...
3.71875
4
autovirt/equipment/domain/equipment.py
xlam/autovirt
0
3079
<reponame>xlam/autovirt from enum import Enum from functools import reduce from math import ceil from typing import Optional, Tuple from autovirt import utils from autovirt.exception import AutovirtError from autovirt.structs import UnitEquipment, RepairOffer logger = utils.get_logger() # maximum allowed equipment p...
2.625
3
day09/part2.py
mtn/advent16
0
3080
<gh_stars>0 #!/usr/bin/env python3 import re with open("input.txt") as f: content = f.read().strip() def ulen(content): ans = 0 i = 0 while i < len(content): if content[i] == "(": end = content[i:].find(")") + i instr = content[i+1:end] chars, times = map(...
3.171875
3
cirq-core/cirq/contrib/quimb/mps_simulator_test.py
Nexuscompute/Cirq
0
3081
<gh_stars>0 # pylint: disable=wrong-or-nonexistent-copyright-notice import itertools import math import numpy as np import pytest import sympy import cirq import cirq.contrib.quimb as ccq import cirq.testing from cirq import value def assert_same_output_as_dense(circuit, qubit_order, initial_state=0, grouping=None)...
1.9375
2
e2e_tests/tests/config.py
winding-lines/determined
0
3082
import os from pathlib import Path from typing import Any, Dict from determined.common import util MASTER_SCHEME = "http" MASTER_IP = "localhost" MASTER_PORT = "8080" DET_VERSION = None DEFAULT_MAX_WAIT_SECS = 1800 MAX_TASK_SCHEDULED_SECS = 30 MAX_TRIAL_BUILD_SECS = 90 DEFAULT_TF1_CPU_IMAGE = "determinedai/environm...
2.046875
2
src/greenbudget/app/subaccount/serializers.py
nickmflorin/django-proper-architecture-testing
0
3083
from django.contrib.contenttypes.models import ContentType from rest_framework import serializers, exceptions from greenbudget.lib.rest_framework_utils.fields import ModelChoiceField from greenbudget.lib.rest_framework_utils.serializers import ( EnhancedModelSerializer) from greenbudget.app.budget.models import B...
1.695313
2
modules/dbnd/src/dbnd/_core/tracking/managers/callable_tracking.py
busunkim96/dbnd
224
3084
import contextlib import logging import typing from typing import Any, Dict, Tuple import attr from dbnd._core.configuration import get_dbnd_project_config from dbnd._core.constants import ( RESULT_PARAM, DbndTargetOperationStatus, DbndTargetOperationType, TaskRunState, ) from dbnd._core.current impo...
1.65625
2
api.py
Benardi/redis-basics
0
3085
import os import logging from json import loads, dumps from datetime import timedelta from argparse import ArgumentParser from redis import Redis from flask import Response, Flask, request app = Flask(__name__) log = logging.getLogger(__name__) parser = ArgumentParser() parser.add_argument("-a", "--address", ...
2.609375
3
zhihu_spider/ZhihuSpider/spiders/zhihu.py
Ki-Seki/gadgets
1
3086
""" 启动此 spider 前需要手动启动 Chrome,cmd 命令如下: cd 进入 Chrome 可执行文件 所在的目录 执行:chrome.exe --remote-debugging-port=9222 此时在浏览器窗口地址栏访问:http://127.0.0.1:9222/json,如果页面出现 json 数据,则表明手动启动成功 启动此 spider 后,注意与命令行交互! 在 settings 当中要做的: # ROBOTSTXT_OBEY = False # 如果不关闭,parse 方法无法执行 # COOKIES_ENABLED = True # 以便 Request 值在传递时自动传递 cookies...
2.640625
3
tests/test_bindiff.py
Kyle-Kyle/angr
6,132
3087
import nose import angr import logging l = logging.getLogger("angr.tests.test_bindiff") import os test_location = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', '..', 'binaries', 'tests') # todo make a better test def test_bindiff_x86_64(): binary_path_1 = os.path.join(test_location, 'x86_64', '...
2.28125
2
main/handle_file.py
nucluster/us_states
0
3088
from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent # def handle_uploaded_file(f): # with open('screenshot.png', 'wb') as destination: # # for chunk in f.chunks(): # # destination.write(chunk) # destination.write(f) with open( BASE_DIR/'media'/'Greater_coat...
2.890625
3
2018/finals/pwn-gdb-as-a-service/web_challenge/challenge/gaas.py
iicarus-bit/google-ctf
2,757
3089
#!/usr/bin/env python3 # # 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 # # Unless required by applicable law ...
1.882813
2
examples/multi_physics/piezo_elasticity.py
BubuLK/sfepy
0
3090
<filename>examples/multi_physics/piezo_elasticity.py r""" Piezo-elasticity problem - linear elastic material with piezoelectric effects. Find :math:`\ul{u}`, :math:`\phi` such that: .. math:: - \omega^2 \int_{Y} \rho\ \ul{v} \cdot \ul{u} + \int_{Y} D_{ijkl}\ e_{ij}(\ul{v}) e_{kl}(\ul{u}) - \int_{Y_2} g_{k...
2.421875
2
01-logica-de-programacao-e-algoritmos/Aula 06/01 Tuplas/1.2 Desempacotamento de parametros em funcoes/ex01.py
rafaelbarretomg/Uninter
0
3091
<reponame>rafaelbarretomg/Uninter<gh_stars>0 # Desempacotamento de parametros em funcoes # somando valores de uma tupla def soma(*num): soma = 0 print('Tupla: {}' .format(num)) for i in num: soma += i return soma # Programa principal print('Resultado: {}\n' .format(soma(1, 2))) print('Resultad...
3.484375
3
services/model.py
theallknowng/eKheti
1
3092
<reponame>theallknowng/eKheti<filename>services/model.py<gh_stars>1-10 import pandas from keras.models import Sequential from keras.layers import Dense from keras.wrappers.scikit_learn import KerasClassifier from keras.utils import np_utils from sklearn.model_selection import cross_val_score from sklearn.model_selectio...
2.53125
3
tests/sentry/api/endpoints/test_project_details.py
erhuabushuo/sentry
0
3093
from django.core.urlresolvers import reverse from sentry.models import Project from sentry.testutils import APITestCase class ProjectDetailsTest(APITestCase): def test_simple(self): project = self.project # force creation self.login_as(user=self.user) url = reverse('sentry-api-0-project-d...
2.234375
2
tests/test_table.py
databook1/python-pptx
0
3094
# encoding: utf-8 """Unit-test suite for `pptx.table` module.""" import pytest from pptx.dml.fill import FillFormat from pptx.dml.border import BorderFormat from pptx.enum.text import MSO_ANCHOR from pptx.oxml.ns import qn from pptx.oxml.table import CT_Table, CT_TableCell, TcRange from pptx.shapes.graphfrm import G...
2.296875
2
imread/tests/test_bmp.py
luispedro/imread
51
3095
<reponame>luispedro/imread<filename>imread/tests/test_bmp.py import numpy as np from imread import imread from . import file_path def test_read(): im = imread(file_path('star1.bmp')) assert np.any(im) assert im.shape == (128, 128, 3) def test_indexed(): im = imread(file_path('py-installer-indexed.bmp'...
2.34375
2
bl60x_flash/main.py
v3l0c1r4pt0r/bl60x-flash
0
3096
from serial import Serial from tqdm import tqdm import binascii import hashlib import struct import time import sys import os def if_read(ser, data_len): data = bytearray(0) received = 0 while received < data_len: tmp = ser.read(data_len - received) if len(tmp) == 0: ...
2.484375
2
lang/py/test/test_avro_builder.py
zerofox-oss/yelp-avro
0
3097
<filename>lang/py/test/test_avro_builder.py # -*- coding: utf-8 -*- import unittest from avro import avro_builder from avro import schema class TestAvroSchemaBuilder(unittest.TestCase): def setUp(self): self.builder = avro_builder.AvroSchemaBuilder() def tearDown(self): del self.builder ...
2.390625
2
monte_py/__init__.py
domluna/fun_with_ffi
1
3098
import random def estimate_pi(sims, needles): trials = [] for _ in xrange(sims): trials.append(simulate_pi(needles)) mean = sum(trials) / sims return mean # use a unit square def simulate_pi(needles): hits = 0 # how many hits we hit the circle for _ in xrange(needles): x = ran...
3.34375
3
tools/mpy_ld.py
UVA-DSI/circuitpython
1
3099
#!/usr/bin/env python3 # # This file is part of the MicroPython project, http://micropython.org/ # # The MIT License (MIT) # # Copyright (c) 2019 <NAME> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in t...
1.539063
2