code
stringlengths
2
1.05M
repo_name
stringlengths
5
104
path
stringlengths
4
251
language
stringclasses
1 value
license
stringclasses
15 values
size
int32
2
1.05M
""" Methods for interacting with Tanda shifts """ from flask import session from flask_login import current_user from swappr.user.tanda_api import tanda_auth, get_user_by_id from swappr.database import db_session from swappr.models import Shift import swappr.god_request import json import datetime #Might be benificial...
swappr-tanda-team/swappr
swappr/shift/tanda_shift.py
Python
mit
4,754
import pandas as pd import numpy as np import ml_metrics as metrics from sklearn.ensemble import RandomForestClassifier, ExtraTreesClassifier from sklearn.calibration import CalibratedClassifierCV from sklearn.cross_validation import StratifiedKFold from sklearn.metrics import log_loss path = '../Data/' print("read tr...
puyokw/kaggle_Otto
new/src/1st_level/extraTree_tfidf.py
Python
mit
2,236
from django.contrib import admin from zealous.blog.models import Category, Post, PostImage class PostImageInline(admin.TabularInline): model = PostImage extra = 0 class PostAdmin(admin.ModelAdmin): fieldsets = [ ('Basic Info', { 'fields': ['name', 'slug', 'author', 'categories', 'pub...
jeffschenck/zealous
zealous/blog/admin.py
Python
mit
1,536
#! /usr/bin/env python #Read arguments from sys import argv if len(argv)!=2: print("Usage: {} <dataset_name>".format(argv[0])) exit(1) PREFIX=argv[1] #Read data import csv DATA_FILE=PREFIX x,y,clase=[],[],[] with open(DATA_FILE,'r') as f: reader = csv.reader(f) for row in reader: if '\t' in r...
mvpossum/machine-learning
tp1/plot_2d_dataset.py
Python
mit
1,274
from setuptools import setup try: # Try to seed the prng to make the tests repeatable. # Unfortunately, numpy might not be installed. import numpy as np np.random.seed(1) except ImportError as e: pass setup(name = 'vampyre', version = '0.0', description = 'Vampyre is a Python package f...
GAMPTeam/vampyre
setup.py
Python
mit
730
""" Setup module for wagoner. """ from setuptools import setup, find_packages with open("README.rst", "r") as readme: setup( name="wagoner", version="1.1", description="A random word generator.", long_description=readme.read(), url="https://github.com/sbusard/wagoner", ...
sbusard/wagoner
setup.py
Python
mit
1,055
def test_age(): from isochrones.priors import AgePrior age_prior = AgePrior() age_prior.test_integral() age_prior.test_sampling() def test_distance(): from isochrones.priors import DistancePrior distance_prior = DistancePrior() distance_prior.test_integral() distance_prior.test_sampl...
timothydmorton/isochrones
isochrones/tests/test_priors.py
Python
mit
1,270
class EqualityMixin(object): def __eq__(self, other): return (isinstance(other, self.__class__) and self.__dict__ == other.__dict__) def __ne__(self, other): return not self.__eq__(other) def __hash__(self): return hash(str(self)) class BasicMixin(object): de...
clark800/pystarch
backend/type_objects.py
Python
mit
4,330
#!/usr/bin/env python3 # # architecture.py # SWN Architecture Generator # # Copyright (c) 2014 Steve Simenic <orffen@orffenspace.com> # # This file is part of the SWN Toolbox. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Sof...
mosodemus/swn
architecture.py
Python
mit
1,964
# -*- coding: utf-8 -*- """Chat robot based on natural language understanding and machine learning.""" __name__ = 'chat' __verison__ = '1.0.7' __author__ = 'Decalogue' __author_email__ = '1044908508@qq.com'
Decalogue/chat
chat/__init__.py
Python
mit
209
# -*- coding: utf-8 -*- """ chemdataextractor.parse.table ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import logging import re from lxml.builder import E from .common import de...
mcs07/ChemDataExtractor
chemdataextractor/parse/table.py
Python
mit
24,740
#!/usr/bin/python from __future__ import division from __future__ import with_statement import math import numpy import os import toolbox_basic import xml.etree.ElementTree as xmlTree class Output: def __init__(self, path=None, root_name='idynomics'): if path == None or not os.path.isfile(path): ...
roughhawkbit/robs-python-scripts
toolbox_results.py
Python
mit
16,594
import numpy as np import unittest from accuread import ReadART class TestAccuRead(unittest.TestCase): def setUp(self): self.PA = ReadART('demo1',basefolder='accuread/tests/testdata', scalar=True,iops=True,direct=True,sine=True,radiance=True, runvarfile='sza.txt') def test_wl(...
TorbjornT/pyAccuRT
accuread/tests/test_basic.py
Python
mit
2,225
################## # Projective Set # # Sam Ettinger # # April 2014 # ################## import random, pygame, sys from pygame.locals import * if not pygame.font: print 'Warning, fonts disabled' # Colors aqua = (0, 255, 255) bgcol = (230, 230, 230) black = (0, 0, 0) blue = (0, 0, 255) fuschia = (255...
settinger/proset
proset.py
Python
mit
10,193
#! /usr/bin/python # Originally found on http://www.mobileread.com/forums/showthread.php?t=25565 import getopt, sys from pyPdf import PdfFileWriter, PdfFileReader def usage (): print """sjvr767\'s PDF Cropping Script. Example: my_pdf_crop.py -s -p 0.5 -i input.pdf -o output.pdf my_pdf_crop.py --skip --percent 0...
ActiveState/code
recipes/Python/576837_Crop_PDF_File_with_pyPdf/recipe-576837.py
Python
mit
5,316
"""homeweb URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.10/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-ba...
srenner/homeweb-v2
homeweb/homeweb/urls.py
Python
mit
859
from sys import argv import logging import numpy as np def pearson_mtx(mtx1, mtx2): assert mtx1.shape[0] == mtx2.shape[0] if len(mtx1.shape) == 1: mtx1 = np.reshape(mtx1, (mtx1.shape[0], 1)) if len(mtx2.shape) == 1: mtx2 = np.reshape(mtx2, (mtx2.shape[0], 1)) logging.info('Matrix1 size...
juditacs/dsl
dsl/utils/pearson.py
Python
mit
1,689
import copy from proxy import Proxy class ProxyList(list): """ A proxy wrapper for a normal Python list. A lot of functionality is being reproduced from Proxy. Inheriting Proxy would simplify things a lot but I get type errors when I try to do so. It is not exactly clear what a partial copy entail...
diffoperator/pycow
src/pycow/proxylist.py
Python
mit
4,140
# -*- encoding: utf-8 -*- from __future__ import absolute_import, unicode_literals import base64 import json import six from addonpayments.hpp.card_storage.requests import CardStorageRequest from addonpayments.hpp.payment.requests import PaymentRequest from addonpayments.hpp.common.responses import HppResponse from...
ComerciaGP/addonpayments-Python-SDK
addonpayments/hpp/utils.py
Python
mit
3,972
# 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 os from fairseq import checkpoint_utils, tasks import sentencepiece as spm import torch try: from simuleval import READ_ACTION, W...
pytorch/fairseq
examples/simultaneous_translation/eval/agents/simul_t2t_enja.py
Python
mit
7,099
import csv import json import logging import os.path import sys import sqlite3 import xml.etree.ElementTree as xml FORMAT = '%(asctime)-15s %(levelname)-7s %(funcName)s: %(message)s' logging.basicConfig(format=FORMAT) logger = logging.getLogger('zipviz') logger.setLevel(logging.INFO) def construct_database(filename='...
johnstonskj/zipviz
data/kml_to_here.py
Python
mit
5,518
import zipfile import os import tarfile import unittest import six from mock import Mock from conans.client.tools import untargz, unzip from conans.client.tools.files import chdir, save from conans.test.utils.mocks import TestBufferConanOutput from conans.test.utils.test_files import temp_folder from conans.errors i...
conan-io/conan
conans/test/unittests/util/files/strip_root_extract_test.py
Python
mit
9,684
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tsune.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
DummyDivision/Tsune
manage.py
Python
mit
248
def return_pow(): return "pow"
bigsassy/pytest-pythonpath
test_path/sitedir3/pow.py
Python
mit
35
# Enter your code here. Read input from STDIN. Print output to STDOUT import itertools s=input() x=((len(list(p)),int(k)) for k,p in itertools.groupby(s)) print(*x)
manishbisht/Competitive-Programming
Hackerrank/Practice/Python/6.itertools/52.Compress the String!.py
Python
mit
172
import socket import gevent import cv2.cv as cv def main(): cv.NamedWindow("camera", 1) capture = cv.CaptureFromCAM(0) while True: img = cv.QueryFrame(capture) """ im_gray = cv.CreateImage(cv.GetSize(img),cv.IPL_DEPTH_8U,1) cv.CvtColor(img,im_gray,cv.CV_RGB2G...
mabotech/mabo.io
py/vision/test1/test1.py
Python
mit
1,352
from os.path import join import sh from pythonforandroid.recipe import NDKRecipe from pythonforandroid.util import current_directory from pythonforandroid.logger import shprint from multiprocessing import cpu_count class OpenCVRecipe(NDKRecipe): ''' .. versionchanged:: 0.7.1 rewrote recipe to support ...
kivy/python-for-android
pythonforandroid/recipes/opencv/__init__.py
Python
mit
6,694
import logging import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F from torch.autograd import Variable class QNetwork(nn.Module): def __init__(self, state_dims=5, action_dims=6, hidden_dims=128): super(QNetwork, self).__init__() self.fc1 = nn.Linear(state_dims, hid...
LK/Plato
plato-server/network.py
Python
mit
757
# -*- coding: utf-8 -*- # python-holidays # --------------- # A fast, efficient Python library for generating country, province and state # specific sets of holidays on the fly. It aims to make determining whether a # specific date is a holiday as fast and flexible as possible. # # Author: ryanss <ryanssdev@icl...
ryanss/python-holidays
holidays/countries/belarus.py
Python
mit
2,698
# Copyright (C) 2014 by Maxim Bublis <b@codemonkey.ru> # # 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, m...
satori/edu
codejam/2008/beta/b.py
Python
mit
2,446
import config import utils import sublime import sublime_plugin #################################################################################### # VIEW #################################################################################### class SwiDebugView(object): """ The SWIDebugView wraps a normal view, a...
sokolovstas/SublimeWebInspector
views.py
Python
mit
8,478
# -*- coding: utf-8 -*- """Tests for the proofreadpage module.""" # # (C) Pywikibot team, 2015-2017 # # Distributed under the terms of the MIT license. # from __future__ import absolute_import, unicode_literals import json import pywikibot from pywikibot.data import api from pywikibot.proofreadpage import IndexPage,...
magul/pywikibot-core
tests/proofreadpage_tests.py
Python
mit
24,736
from django.core.management.base import BaseCommand, CommandError from main.models import Port, Country, settings import csv # This file is part of https://github.com/cpina/science-cruise-data-management # # This project was programmed in a hurry without any prior Django experience, # while circumnavigating the Antarc...
cpina/science-cruise-data-management
ScienceCruiseDataManagement/main/management/commands/importports.py
Python
mit
1,825
# encoding: utf-8 """ Utilities for working with strings and text. Inheritance diagram: .. inheritance-diagram:: IPython.utils.text :parts: 3 """ #----------------------------------------------------------------------------- # Copyright (C) 2008-2011 The IPython Development Team # # Distributed under the terms...
mattvonrocketstein/smash
smashlib/ipy3x/utils/text.py
Python
mit
23,460
#!/usr/bin/python3 # -*- coding: UTF-8 -*- # Introduction: 本程序用于 # Created by galaxy on 2016/9/8 10:50 import os my_path = os.getcwd() gbk_dir = os.path.join(my_path, 'gbk') batch_lines = [] for root, dirs, files in os.walk(gbk_dir): for each_file in files: gbk_path = 'gbk/{0}'.format(each_file) e...
cvn001/RecentHGT
src/convertGenbank2table_InBatch.py
Python
mit
691
from setuptools import setup, find_packages from opensimplex import __version__, __author__ with open("README.md", "r") as fh: long_description = fh.read() setup( name='opensimplex', version=__version__, author=__author__, author_email='opensimplex@larus.se', description='OpenSimplex n-dimen...
lmas/opensimplex
setup.py
Python
mit
1,011
''' Sort entries in a tabular BLAST output file in reverse order. ----------------------------------------------------------- (c) 2013 Allegra Via and Kristian Rother Licensed under the conditions of the Python License This code appears in section 8.4.2 of the book "Managing Biological Data with Python". ...
raymonwu/Managing_Your_Biological_Data_with_Python_3
08-sorting_data/8.4.2_sort_blast_output.py
Python
mit
883
#!/usr/bin/python3 # # Copyright (c) 2013 Mikkel Schubert <MikkelSch@gmail.com> # # 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 ...
MikkelSchubert/paleomix
paleomix/resources/examples/phylo_pipeline/synthesize_reads.py
Python
mit
16,296
def y(): raise TypeError def x(): y() try: x() except TypeError: print('x')
paopao74cn/noworkflow
tests/test_exception.py
Python
mit
84
# -*- coding: utf-8 -*- # Copyright (c) 2015-2016 Mark Spicer # Made available under the MIT license. import time import freshroastsr700 class Roaster(object): def __init__(self): """Creates a freshroastsr700 object passing in methods included in this class.""" self.roaster = freshroastsr...
Roastero/freshroastsr700
examples/advanced.py
Python
mit
1,551
''' Provide pre-/postconditions as function decorators. Example usage: >>> def in_ge20(inval): ... assert inval >= 20, 'Input value < 20' ... >>> def out_lt30(retval, inval): ... assert retval < 30, 'Return value >= 30' ... >>> @precondition(in_ge20) ... @postcondition(out_lt30) ... def inc(va...
spradeepv/dive-into-python
decorators/pre_post_decorator.py
Python
mit
3,245
import numpy def shift(mtx, offset): ''' Circular shift 2D matrix samples by OFFSET (a [Y,X] 2-tuple), such that RES(POS) = MTX(POS-OFFSET). ''' dims = mtx.shape if len(dims) == 1: mtx = mtx.reshape((1, dims[0])) dims = mtx.shape offset = numpy.mod(numpy.negative(offset), d...
tochikuji/pyPyrTools
pyrtools/shift.py
Python
mit
670
# Read output files and make spectrogram import pylab as pl import pyfits as pf import os import scipy.stats as stats import scipy.signal as sig import astronomy as ast #import movingaverage as MA X = pl.load('ec2117ans_2_cc.dat') files = os.listdir(os.curdir) files.sort() ff = [] for f in files: name,ext = o...
ezietsman/msc-thesis
spectroscopy/final/pyspecgram.py
Python
mit
5,152
# settings/base.py ''' THIS PROJECT IS NOW USING DJANGO VERSION 1.11 THIS PROJECT IS NOW USING DJANGO VERSION 2.0 THIS PROJECT IS NOW USING DJANGO VERSION 2.1 ''' import os import json # Normally we wouldn't import ANYTHING from Django directly # into our settings, but ImproperlyConfigured is an exception. from djang...
patcurry/WebGIS
main/settings/base.py
Python
mit
4,432
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
AutorestCI/azure-sdk-for-python
azure-batch/azure/batch/models/pool_resize_options.py
Python
mit
3,069
import warnings from braintree.util.http import Http from braintree.successful_result import SuccessfulResult from braintree.error_result import ErrorResult from braintree.resource import Resource from braintree.credit_card import CreditCard from braintree.address import Address from braintree.configuration import Conf...
eldarion/braintree_python
braintree/customer.py
Python
mit
6,348
# -*- coding: utf-8 -*- import unittest from nose.plugins.skip import SkipTest try: from urllib3.contrib.pyopenssl import (inject_into_urllib3, extract_from_urllib3) except ImportError as e: raise SkipTest('Could not import PyOpenSSL: %r' % e) from mock import patch...
Lukasa/urllib3
test/contrib/test_pyopenssl_dependencies.py
Python
mit
1,662
import sys for line in sys.stdin: try: print("%.2f" % eval(line.replace(";", "").replace(",", ""))) except Exception: print("Expressao incorreta")
vitorgt/SCC0202
t1_calculadora_de_expressoes_aritimeticas.py
Python
mit
172
# -*-coding:utf-8 -* import pygame from pygame.locals import * NOM_CARTE_LANCEMENT = "LD26-Ferme" DOSSIER_RESSOURCES = "Ressources" FENETRE = dict() FENETRE["messageErreurInitialisationPygame"]="Une erreur s'est produite durant l'initialisation de Pygame, le programme doit donc se fermer." FENETRE["messageErreurInit...
Rastagong/A-Scholar-In-The-Woods
Trunk/constantes.py
Python
mit
983
##@file flp.py #@brief model for solving the capacitated facility location problem """ minimize the total (weighted) travel cost from n customers to some facilities with fixed costs and capacities. Copyright (c) by Joao Pedro PEDROSO and Mikio KUBO, 2012 """ from pyscipopt import Model, quicksum, multidict def flp(I,...
SCIP-Interfaces/PySCIPOpt
examples/finished/flp.py
Python
mit
3,029
# -*- coding: utf-8 -*- __all__ = ['Distribution'] import io import sys import re import os import warnings import numbers import distutils.log import distutils.core import distutils.cmd import distutils.dist import distutils.command from distutils.util import strtobool from distutils.debug import DEBUG from distutils...
nataddrho/DigiCue-USB
Python3/src/venv/Lib/site-packages/setuptools/dist.py
Python
mit
40,150
import os from ..ast import (Assignment, BinaryOperator, Block, Function, IfStatement, Invocation, NumericLiteral, StringLiteral, Return, Symbol, ListLiteral, Import) from ..ast.inference import infer, SymbolType, resolve_types, is_concrete_type, InferenceError def join_arguments(args): out = [] for ar...
bbonf/matcha
matcha/js/__init__.py
Python
mit
3,412
import os import pytest from uqbar.strings import normalize import supriya.synthdefs import supriya.ugens @pytest.mark.skipif( os.environ.get("GITHUB_ACTIONS") == "true", reason="sclang broken under GitHub Actions", ) def test_Splay_01_sclang(server): sc_synthdef = supriya.synthdefs.SuperColliderSynthDe...
josiah-wolf-oberholtzer/supriya
tests/synthdefs/test_synthdefs_SynthDefCompiler_splay.py
Python
mit
20,228
class Solution(object): def isSelfCrossing(self, x): """ :type x: List[int] :rtype: bool """ n=len(x) if n<4: return False # start with the fourth element i=3 while i<n: # if i cross with i-3, it's very simple ...
Tanych/CodeTracking
335-Self-Crossing/solution.py
Python
mit
1,246
#!/usr/bin/env python import simplekml import argparse import colorsys import numpy import simplejson import csv import os from lib.config import Config def RGBToHTMLColor(rgb_tuple): """ convert an (R, G, B) tuple to #RRGGBB """ hexcolor = '%02x%02x%02xff' % (int(rgb_tuple[0]*256), int(rgb_tuple[1]*256), in...
sean/delivery-routes
gen_kml.py
Python
mit
3,068
#!/usr/bin/env python3 # Copyright (c) 2015-2016 The Flurbo Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # # Test the CHECKLOCKTIMEVERIFY (BIP65) soft-fork logic # from test_framework.test_framework import Flur...
Flurbos/Flurbo
qa/rpc-tests/bip65-cltv.py
Python
mit
3,172
class BaseTwitterClient(): def __init__(self): pass def authenticate(self): '''Authenticate against the Twitter API and check the return to make sure we have a valid connection, return true or false''' raise NotImplementedError() def request(self): '''Make an HTTP request''' raise NotImplementedError()
blairg23/TweetyPy
BaseTwitterClient.py
Python
mit
317
from qualdocs.core import *
qualdocs/qualdocs
qualdocs/__init__.py
Python
mit
27
import os import unittest import GeometrA from PIL import Image, ImageTk from io import BytesIO import base64 from GeometrA.src.TestScript.TestCase import TestCase from GeometrA.src.TestScript.TestStep import Step class TestCaseTestSuite(unittest.TestCase): def setUp(self): GeometrA.app.testing = True ...
NTUTVisualScript/Visual_Script
tests/TestScript/test_TestCase.py
Python
mit
4,375
# This file is part of Indico. # Copyright (C) 2002 - 2022 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from indico.modules.events.management.views import WPEventManagement from indico.util.i18n import _ from i...
indico/indico
indico/modules/rb/views.py
Python
mit
767
#from __future__ import division # #import os, os.path #import json #import itertools #from collections import namedtuple #import matplotlib.pyplot as plt #import numpy as np # #from csxj.datasources.parser_tools.article import ArticleData # # # #BACKGROUND_COLOR = '#e3e1dd' #LIGHT_COLOR = '#f0efed' #DARK_COLOR = '#4c...
sevas/csxj-crawler
scripts/make_figures.py
Python
mit
7,756
#!/usr/bin/env python ########################################################################....... from __future__ import division, print_function import sys import ui PLACEHOLDER_TEXT = "No Views Presented" class Multipanel(object): # Class of the object stored in ui.multipanel def __init__(self): ...
dgelessus/pythonista-scripts
multipanel.py
Python
mit
4,859
import log import sys, string import xml.dom.minidom from xml.dom.minidom import Node global VERBOSE VERBOSE = False global TIMERESOURCES TIMERESOURCES = False global pkgName, pkgVersion, pkgRevision, pkgArchitecture, pkgCategoryMajor, pkgCategoryMinor global files, root, protocol, server, location, tags, environme...
andreioprisan/apkg
source/parser/reader.py
Python
mit
21,750
"""Test Device Tracker config entry things.""" from homeassistant.components.device_tracker import DOMAIN, config_entry as ce from homeassistant.core import callback from homeassistant.helpers import device_registry as dr, entity_registry as er from homeassistant.helpers.dispatcher import async_dispatcher_connect from...
rohitranjan1991/home-assistant
tests/components/device_tracker/test_config_entry.py
Python
mit
6,345
#! /usr/bin/env python3.7 HELP_TEXT = ["!rank <user?>", "Retrieve basic information about an osu user."] def call(salty_inst, c_msg, **kwargs): try: user = c_msg["message"].split("rank ")[1] except IndexError: user = "" osu_nick = user or c_msg["channel"][1:] success, response = salty...
BatedUrGonnaDie/salty_bot
modules/commands/rank.py
Python
mit
949
"""Convenience function to create a context for the built in error functions""" import logging import copy import symengine from pycalphad import variables as v from pycalphad.codegen.callables import build_callables from pycalphad.core.utils import instantiate_models, filter_phases, unpack_components from espei.error...
PhasesResearchLab/ESPEI
espei/error_functions/context.py
Python
mit
4,910
import pygame import sys pygame.init() w = pygame.display.set_mode((800,800)) pygame.display.set_caption("QFPD") clock = pygame.time.Clock() sprite = pygame.image.load("test.png") leave = False def drawSprite(x, y): w.blit(sprite, (x, y)) while not leave: drawSprite(0, 0) for event in...
AbusementPark/Quest-For-Pink-Donught
QFPD/main.py
Python
mit
588
import datetime import json import logging import md5 import random import tba_config import urllib import uuid import webapp2 from google.appengine.api import urlfetch from google.appengine.ext import deferred from google.appengine.ext import ndb from consts.account_permissions import AccountPermissions from consts....
jaredhasenklein/the-blue-alliance
controllers/api/api_base_controller.py
Python
mit
11,616
""" TrueType Fonts """ from .base_font import PdfBaseFont class TrueTypeFont(PdfBaseFont): """For our purposes, these are just a more restricted form of the Type 1 Fonts, so...we're done here.""" def text_space_coords(self, x, y): """Type1 fonts just scale by 1/1000 to convert from glyph sp...
ajmarks/gymnast
gymnast/pdf_elements/fonts/true_type.py
Python
mit
359
#!/usr/bin/env python #coding:utf-8 # Purpose: test node organizer # Created: 31.01.2011 # Copyright (C) 2011, Manfred Moitzi # License: MIT from __future__ import unicode_literals, print_function, division __author__ = "mozman <mozman@gmx.at>" import unittest # test helpers from mytesttools import create...
iwschris/ezodf2
tests/test_epilogue_tagblock.py
Python
mit
5,381
from functools import partial import traceback import sys from typing import TYPE_CHECKING from PyQt5.QtCore import QObject, pyqtSignal from PyQt5.QtWidgets import (QHBoxLayout, QLabel, QVBoxLayout) from electrum_ltc.plugin import hook from electrum_ltc.i18n import _ from electrum_ltc.gui.qt.util import ThreadedButto...
pooler/electrum-ltc
electrum_ltc/plugins/labels/qt.py
Python
mit
3,637
## # @file main.py # @brief this file run the case that only magnetic field exists # @author Pi-Yueh Chuang (pychuang@gwu.edu) # @version alpha # @date 2015-11-17 # python 3 import numpy from Field import Field from Particle import Particle e = 1.602176565e-19 # [C] me = 9.10938291e-31 # [kg] eps0 = 8.85e-12 # [s^...
piyueh/PlasmaPIC
src/verify_B=0.1_E=0.py
Python
mit
2,272
from disco.types.message import MessageEmbed from disco.api.http import APIException import re import string from abc import ABC, abstractmethod import gevent class TriggerItemReminder(object): def __init__(self, content, embed=None, attachments=[]): self.content = content self.embed = embed self.attachments =...
winterismute/mcreminder-discordbot
bot/triggeritem.py
Python
mit
5,795
""" Base class for all the queue system implementations """ import subprocess, os import plugins class QueueSystem: def __init__(self, *args): pass def submitSlaveJob(self, cmdArgs, slaveEnv, logDir, submissionRules, jobType): try: process = subprocess.Popen(cmdArgs, stdout=s...
emilybache/texttest-runner
src/main/python/lib/queuesystem/abstractqueuesystem.py
Python
mit
3,518
#!/usr/bin/env python import setpath import unittest from bike.refactor.extractMethod import ExtractMethod, \ extractMethod, coords from bike import testdata from bike.testutils import * from bike.parsing.load import Cache def assertTokensAreSame(t1begin, t1end, tokens): it = t1begin.clone() pos = 0 ...
srusskih/SublimeBicycleRepair
bike/refactor/test_extractMethod.py
Python
mit
21,788
#!/usr/bin/env python """ :Author Patrik Valkovic :Created 11.03.2019 21:45 :Licence MIT Part of grammpy """ from unittest import TestCase, main from grammpy import Grammar, Nonterminal, Rule from grammpy.exceptions import RuleNotDefinedException, RuleSyntaxException, TerminalDoesNotExistsException, NonterminalDoesNot...
PatrikValkovic/grammpy
tests/grammpy_test/rule_tests/handling_tests/AddingTest.py
Python
mit
7,025
import numpy as np from keras.models import Sequential from keras.layers.core import Dense, Activation from keras.layers.advanced_activations import LeakyReLU from keras.optimizers import SGD from sklearn import datasets from sklearn.model_selection import train_test_split np.random.seed(1234) ''' データの生成 ...
inoue0124/TensorFlow_Keras
chapter4/leaky_relu_keras.py
Python
mit
1,484
from collections import namedtuple Point = namedtuple('Point', 'x y') Size = namedtuple('Size', 'w h') def is_child(child, parent): """ returns True if class child is child of class parent and only if it is child, returns False otherwise """ try: return issubclass(child, parent) and child is not parent ex...
evuez/disclosure
generic.py
Python
mit
618
# -*- coding: utf8 -*- # Copyright (c) 2017-2021 THL A29 Limited, a Tencent company. 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...
tzpBingo/github-trending
codespace/python/tencentcloud/cls/v20201016/errorcodes.py
Python
mit
7,850
import aioredis import pickle from aiohttp_cached.exceptions import ImproperlyConfigured from aiohttp_cached.cache.backends import AsyncBaseCache __all__ = ( 'RedisCache', ) class RedisCache(AsyncBaseCache): def __init__(self, location: str, params: dict, loop=None): super().__init__(location, param...
TheML9I/aiohttp-cached
aiohttp_cached/cache/backends/redis.py
Python
mit
3,246
class Solution: # @return an integer def lengthOfLongestSubstring(self, s): s = s.strip() if not s: return 0 else: a = [] max = 0 for i in s: if i not in a: a.append(i) else: ...
Crayzero/LeetCodeProgramming
Solutions/Longest Substring Without Repeating Characters/longestSubstring.py
Python
mit
928
""" https://leetcode.com/problems/binary-string-with-substrings-representing-1-to-n/ https://leetcode.com/submissions/detail/217341263/ """ class Solution: def queryString(self, S: str, N: int) -> bool: for i in range(1, N + 1): s = bin(i)[2:] if s not in S: return...
vivaxy/algorithms
python/problems/binary_string_with_substrings_representing_1_to_n.py
Python
mit
626
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_selenium_astride ---------------------------------- Tests for `selenium_astride` module. """ from flask import Flask, render_template, redirect, url_for, request, session, flash from flask.ext.testing import LiveServerTestCase from selenium import webdriver imp...
reclamador/python_selenium_astride
tests/test_selenium_astride.py
Python
mit
3,265
import theano import lasagne import numpy as np import theano.tensor as T from numpy import random as rnd, linalg as la from layers import UnitaryLayer, UnitaryKronLayer, RecurrentUnitaryLayer, ComplexLayer, WTTLayer, ModRelu from matplotlib import pyplot as plt from utils.optimizations import nesterov_momentum, cust...
Nehoroshiy/urnn
examples/lasagne_rnn.py
Python
mit
8,511
#!/usr/bin/env python import os import os.path import re import sys # Ugly hack so we can import pytoutv_plus lib_path = os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'video-tools')) sys.path.append(lib_path) import pytoutv_plus def main(): filenames = [] for (dirpath, dirn...
bmaupin/junkpile
python/one-offs/import-toutv.py
Python
mit
2,456
# -*- coding: cp936 -*- #!/usr/bin/env python # Author: # Quinn Song <quinn4dev@gmail.com> # add_brackets.py: insert one or two pairs of brackets randomly; # add return a valid expression import random import re def apply_pattern1 (source): """ Add brakets using pattern 1 """ source = re.sub('([+*/...
QuinnSong/LoveMath
src/add_brackets.py
Python
mit
1,489
# This file was automatically generated by SWIG (http://www.swig.org). # Version 3.0.7 # # Do not make changes to this file unless you know what you are doing--modify # the SWIG interface file instead. from sys import version_info if version_info >= (2, 6, 0): def swig_import_helper(): from os.path imp...
EnEff-BIM/EnEffBIM-Framework
SimModel_Python_API/simmodel_swig/Release/SimAppObjNameDefault_DistributionSystem_SitePowerDemand.py
Python
mit
9,158
from pylab import * D = loadtxt("MCP4161-104E-P_Resistance_vs_Ntap.csv",delimiter=",") X = D[:,0] Y = D[:,1] p = polyfit(X,Y,1) X_fit = arange(257) Y_fit = X_fit*p[0] + p[1] plot(X,Y,'b.') plot(X_fit,Y_fit, 'k-') title("Calibration of MCP4161-104E/P\n8bit 100k Digital Potentiomenter") xlabel("Tap Number, N") ylabel...
p-v-o-s/olm-pstat
test/MCP4161-104E-P_Resistance_vs_Ntap_analysis.py
Python
mit
470
from django.db import models from samples.models import Specimen from picker.models import SpecimenSource from analysis.models import Analysis from agency.models import Agency # Create your models here. class Order(models.Model): specimen = models.ForeignKey(Specimen) analysis = models.ForeignKey(Analysis)...
timothypage/etor
etor/order/models.py
Python
mit
952
import random from collections import defaultdict class MarkovGenerator(object): def __init__(self, corpus, tuple_size=3): """ Initialize the MarkovGenerator object. Digests the corpus of text provided as a list of tokens and creates a cache of predicted next-word values Code fo...
bmd/markov-at-the-movies
markov_generator.py
Python
mit
2,998
from .cypher import Create, Match, Merge from .graph import Graph from .ogm import OGMBase, OneToManyRelation, ManyToManyRelation from .primitives import Node, Relationship from .shared.objects import Property
TwoBitAlchemist/NeoAlchemy
neoalchemy/__init__.py
Python
mit
210
# THIS FILE IS AUTO-GENERATED. DO NOT EDIT from verta._swagger.base_type import BaseType class UacSetOrganizationResponse(BaseType): def __init__(self, organization=None): required = { "organization": False, } self.organization = organization for k, v in required.items(): if self[k] is N...
mitdbg/modeldb
client/verta/verta/_swagger/_public/uac/model/UacSetOrganizationResponse.py
Python
mit
645
from django.conf.urls import patterns, url from django.views.generic import ListView, DetailView from .models import Audio, Videos urlpatterns = patterns('', url(r'^audio/$', ListView.as_view(model=Audio, queryset=Audio.objects.all(), ...
CARocha/cesesma
multimedia/urls.py
Python
mit
1,282
#!/usr/bin/python import os import shutil base = os.path.dirname(os.path.realpath(__file__)) base = os.path.join(base, '../boot') def create_dir(path): path = os.path.join(base, path) if not os.path.exists(path): os.makedirs(path) def delete_dir(path): path = os.path.join(base, path) shut...
JustSid/Firedrake
scripts/make_image.py
Python
mit
851
#!/usr/bin/env python # # Wrapper script for Java Conda packages that ensures that the java runtime # is invoked with the right options. Adapted from the bash script (http://stackoverflow.com/questions/59895/can-a-bash-script-tell-what-directory-its-stored-in/246128#246128). # # # Program Parameters # import os import...
rob-p/bioconda-recipes
recipes/dedup/dedup.py
Python
mit
2,655
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
lmazuel/azure-sdk-for-python
azure-mgmt-network/azure/mgmt/network/v2018_01_01/models/virtual_network_gateway_connection.py
Python
mit
7,595
# This file helps to compute a version number in source trees obtained from # git-archive tarball (such as those provided by githubs download-from-tag # feature). Distribution tarballs (built by setup.py sdist) and build # directories (produced by setup.py build) will contain a much shorter file # that just contains t...
MrLeeh/jsonwatchqt
jsonwatchqt/_version.py
Python
mit
15,771
from questions import signals
Kuzenkov/SimpleAnalogueStackOverflow
questions/__init__.py
Python
mit
29
"""Mongodb implementations of assessment objects.""" # pylint: disable=no-init # Numerous classes don't require __init__. # pylint: disable=too-many-public-methods,too-few-public-methods # Number of methods are defined in specification # pylint: disable=protected-access # Access to protected methods allowe...
birdland/dlkit-doc
dlkit/mongo/assessment/objects.py
Python
mit
131,041
from FlightInfo import FlightInfo from Interval import * from Gate import Gate from Queue import * from random import * def assign(intervals, num_gates=0, start_time=scheduled_start_time, end_time=scheduled_end_time): gates = [Gate() for i in xrange(0, num_gates)] # initialise priority queue pq = PriorityQueue() ...
sozos/RAS
source/schedule.py
Python
mit
2,831