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
# -*- coding: utf-8 -*- """ Created on Fri Aug 17 13:41:28 2018 @author: mtkes """ import numpy as np from scipy.integrate import odeint import matplotlib.pyplot as plt # function that returns dy/dt def model(y,t): k = 0.3 dydt = -k * y return dydt # initial condition y0 = 5 # time points t = np.linspa...
RocketRedNeck/PythonPlayground
odeintExample.py
Python
mit
443
# -*- coding: utf-8 -*- from scipy import random from scipy.sparse import hstack from sklearn.neighbors import NearestNeighbors from scipy.spatial.distance import pdist from scipy.spatial.distance import squareform from os.path import abspath from os.path import split as pathsplit from scipy import vstack import j...
opoirion/pres_ml
python_code/generate_random_json.py
Python
mit
1,294
import datetime as date from django.db import models from mixins.models import ModifiedDate from photosync.flickr import Flickr # Create your models here. class Collection(ModifiedDate): title = models.CharField(max_length=250) slug = models.CharField(max_length=250) total = models.PositiveIntegerField(...
useEvil/flickr-photo-sync
flickrphotosync/photosync/models.py
Python
mit
4,333
class Information(object): def __init__(self, pygame): self.pygame = pygame self.display_fps = False def _show_fps(self, clock, screen): font = self.pygame.font.SysFont('Calibri', 25, True, False) text = font.render("fps: {0:.2f}".format(clock.get_fps()), True, (0, 0, 0)) ...
evasilchenko/castle
core/info.py
Python
mit
536
#! python3 ''' mad_libs.py - reads in text files and lets the user add their own text anywhere the word ADJECTIVE, NOUN, ADVERB, or VERB appears in the text file. For example, a text file may look like this: ``` The ADJECTIVE panda walked to the NOU...
pezy/AutomateTheBoringStuffWithPython
practice_projects/mad_libs.py
Python
mit
1,471
from django.apps import AppConfig class RestateConfig(AppConfig): name = 'restate'
MrSami/sandbox
alpagu/restate/apps.py
Python
mit
89
from office365.runtime.client_object import ClientObject from office365.runtime.queries.service_operation_query import ServiceOperationQuery from office365.runtime.paths.resource_path import ResourcePath from office365.sharepoint.userprofiles.userProfile import UserProfile class ProfileLoader(ClientObject): def ...
vgrem/Office365-REST-Python-Client
office365/sharepoint/userprofiles/profileLoader.py
Python
mit
1,190
# _*_ coding:utf-8 _*_ from __future__ import print_function from dataFunctions import * import time from collections import OrderedDict import pickle s = time.time() ONLINE_30 = datetime.datetime(2015, 12, 18, 16) START_DATE = datetime.datetime(2016, 1, 3) - datetime.timedelta(hours=8) END_DATE = START_DATE + date...
summer-liu/events_cache_scripts
report/report03.py
Python
mit
14,920
import logging import signal import tornado.ioloop import tornado.log import torpedomsg tornado.log.enable_pretty_logging() class LineReader(object): def __init__(self, host, port): self.client = torpedomsg.TorpedoClient(host, port) self.client.set_connect_callback(self.connect_callback) ...
misuzu/torpedomsg
examples/client.py
Python
mit
1,270
from dbot import info info()
alex-i-git/LearnPython-Diploma-Project
info.py
Python
mit
29
from django.utils.translation import gettext_lazy as gettext_lazy JP_PREFECTURES = ( ('hokkaido', gettext_lazy('Hokkaido'),), ('aomori', gettext_lazy('Aomori'),), ('iwate', gettext_lazy('Iwate'),), ('miyagi', gettext_lazy('Miyagi'),), ('akita', gettext_lazy('Akita'),), ('yamagata', gettext_lazy...
jonaustin/advisoryscan
django/django/contrib/localflavor/jp/jp_prefectures.py
Python
mit
2,057
""" [04/22/13] REMINDER: Week-Long Challenge #1 due today! https://www.reddit.com/r/dailyprogrammer/comments/1cv8oo/042213_reminder_weeklong_challenge_1_due_today/ Hey r/DailyProgrammers, As a friendly reminder, our first week-long challenge (making a (tiny) video game) concludes today, at midnight, here in the Ameri...
DayGitH/Python-Challenges
DailyProgrammer/DP20130422.py
Python
mit
818
from django.conf import settings from django.conf.urls.defaults import * from models import * from django.views.generic import date_based, list_detail from django.contrib.auth.decorators import login_required # Number of random images from the gallery to display. SAMPLE_SIZE = ":%s" % getattr(settings, 'GALLERY_SAMPLE...
garyp/djwed
photologue/urls.py
Python
mit
3,400
import params def mgid2glom(gid): return int((gid-params.gid_mitral_begin)/params.Nmitral_per_glom)
JustasB/MitralSuite
Models/Migliore2014/gidfunc.py
Python
mit
103
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('adopteitor_core', '0010_ipn'), ] operations = [ migrations.AlterModelOptions( name='ipn', options={'...
smarbos/adopteitor-server
adopteitor_core/migrations/0011_auto_20170221_2157.py
Python
mit
368
""" App para almacenar los estudios socioeconómicos. Este app almacena la información no vital de los estudios socioeconómicos, es decir, los campos que no se utilizan de forma frecuente en la aplicación. """
erikiado/jp2_online
estudios_socioeconomicos/__init__.py
Python
mit
214
class Solution(object): def plusOne(self, digits): """ :type digits: List[int] :rtype: List[int] """ for i in range(len(digits) - 1, -1, -1): if digits[i] < 9: digits[i] += 1 return digits digits[i] = 0 new_digi...
yehzhang/RapidTest
examples/solutions/plus_one.py
Python
mit
400
#!/usr/bin/python import logging logger = logging.getLogger('pytest') class AccountService: ''' account service template ''' def place_order(self): '''authentication''' print 'account service - authentication' logger.info('account service - authentication') @staticmethod ...
vollov/python-test
services/account_service.py
Python
mit
437
''' Created on 24.10.2011 @author: michi ''' from PyQt4.QtCore import QObject, QMutexLocker from landmarkabstractrequest import LandmarkAbstractRequest #@UnresolvedImport from landmarkfilter import LandmarkFilter #@UnresolvedImport class LandmarkFetchRequest(LandmarkAbstractRequest): ''' The QLandmarkFetchR...
mtils/ems
ems/qt4/location/landmarks/landmarkfetchrequest.py
Python
mit
4,739
# Python - 3.6.0 gets = lambda i: 's' if i != 1 else '' getn = lambda i: f'{i if i > 0 else "no more" if i == 0 else 99} bottle{gets(i)}' getm = lambda i: 'Go to the store and buy some more' if i <= 0 else 'Take one down and pass it around' getl1 = lambda i: f'{getn(i)} of beer on the wall, {getn(i)} of beer.'.capital...
RevansChen/online-judge
Codewars/8kyu/8kyu-interpreters-hq9-plus/Python/solution2.py
Python
mit
552
import numpy as np import env from base import BaseEstimator from utils import RNG, print_inline, width_format, Stopwatch from layers import FullyConnected from activations import sigmoid class RBM(BaseEstimator): """ Examples -------- >>> X = RNG(seed=1337).rand(32, 256) >>> rbm = RBM(n_hidden=1...
monsta-hd/ml-mnist
ml_mnist/nn/rbm.py
Python
mit
8,597
# -*- encoding: utf-8 -*- ############################################################################## # # Acrisel LTD # Copyright (C) 2008- Acrisel (acrisel.com) . All Rights Reserved # # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public...
Acrisel/acris
acris/acris_example/virtual_resource_pool.py
Python
mit
2,037
#!/usr/bin/env python2 # Print out the 2^n possibilities of a word with the length n import unittest from itertools import product, permutations def word_variations(s): try: if not len(s): return lower, upper = s.lower(), s.upper() except: return # Since number strings won't produ...
mikar/projects
various/word_possibilities.py
Python
mit
1,021
# # Metrix++, Copyright 2009-2013, Metrix++ Project # Link: http://metrixplusplus.sourceforge.net # # This file is a part of Metrix++ Tool. # # Metrix++ is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the ...
vijaysm/mmodel-software-analysis
contrib/metrixplusplus-1.3.168/tests/common.py
Python
mit
11,187
#!/usr/bin/python2.4 # # Copyright 2009 Empeeric LTD. 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 requir...
katemsu/kate_website
kate3/utils/bitly.py
Python
mit
6,991
import SMSLibrary as sms import time as t sms.init(0) motorId = [4, 5, 6, 7, 8, 9] t.sleep(0.02) sms.broadcastStop() t.sleep(0.02) sms.broadcastStart() # sms.start(motorId) for i in motorId: sms.resetErrors(i) # print(sms.getPosition(i)) t.sleep(0.02) for i in motorId: # sms.setProfiledVelocitySetpo...
mikekaram/SMS_python
example_6dof.py
Python
mit
905
from opendc.models.cpu import CPU from opendc.util import exceptions from opendc.util.rest import Response def GET(request): """Get the specs of a CPU.""" # Make sure required parameters are there try: request.check_required_parameters( path={ 'id': 'int' ...
atlarge-research/opendc-web-server
opendc/api/v1/specifications/cpus/id/endpoint.py
Python
mit
747
import asyncio import discord from discord.ext import commands def setup(bot): # Disabled for now return # Add the bot and deps settings = bot.get_cog("Settings") bot.add_cog(Monitor(bot, settings)) # This is the Monitor module. It keeps track of how many messages fail class Monitor(commands.Cog)...
corpnewt/CorpBot.py
Cogs/Monitor.py
Python
mit
2,040
import datetime from django.conf import settings from django.shortcuts import render from django.views import View class TasksCodes(View): def get(self, request): data = dict((("_%s" % s['_id'], s['feeds']) for s in self.stats)) chart_name = "task_codes" chart_type = "counter" form...
samuelclay/NewsBlur
apps/monitor/views/newsblur_tasks_codes.py
Python
mit
1,165
from prodtest import ProduceTestCase class PretendUpToDateTest(ProduceTestCase): def test_pretend_up_to_date(self): # a # | # b # / \ # c d normal = lambda: self.produce('a') pretending = lambda: self.produce('a', **{'-u': 'b'}) self.assertD...
texttheater/produce
t/test_pretend_up_to_date.py
Python
mit
763
# -*- coding: utf-8 -*- # Generated by Django 1.9 on 2016-01-20 16:34 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0004_auto_20160120_1633'), ] operations = [ migrations.AlterField( ...
Raulios/django-blog
core/migrations/0005_auto_20160120_1634.py
Python
mit
458
# encoding: UTF-8 import talib as ta import numpy as np from ctaBase import * from ctaTemplate import CtaTemplate import time ######################################################################## class TickBreaker(CtaTemplate): """跳空追击策略(MC版本转化)""" className = 'TickBreaker' author = u'融拓科技' # 策略...
freeitaly/Trading-System
vn.trader/ctaAlgo/strategyTickBreaker.py
Python
mit
8,133
import zipfile, sys, os, glob import xml.etree.ElementTree as ET from clint.textui import progress from collections import defaultdict anim_map = defaultdict( list ) for zipfilename in progress.bar( glob.glob( "*.zip" ) ): try: with zipfile.ZipFile( zipfilename, "r" ) as zf: root = ...
kleientertainment/ds_mod_tools
pkg/win32/mod_tools/exported/validate.py
Python
mit
854
# coding=utf-8 """ Uses /proc/mounts and os.statvfs() to get disk space usage #### Dependencies * /proc/mounts #### Examples # no exclude filters at all exclude_filters =, # exclude everything that begins /boot or /mnt exclude_filters = ^/boot, ^/mnt # exclude everything that includes the le...
MediaMath/Diamond
src/collectors/diskspace/diskspace.py
Python
mit
9,080
from functools import wraps from inspect import Parameter import mock from doctor.resource import ResourceAnnotation, ResourceSchemaAnnotation from .base import TestCase from .types import ItemId from .utils import add_doctor_attrs def does_nothing(func): """An example decorator that does nothing.""" @wrap...
upsight/doctor
test/test_resource.py
Python
mit
4,127
#!/usr/bin/env python from time import sleep import twk_utils import math import sys import xpf6020 import tools.utils as tools import watlowf4 from tools import shell from blessings import Terminal t = Terminal() franz_num = raw_input('How many Franz are you testing? [1,2,3,or 4]: ').strip() cycle_num = raw_input('...
taiwenko/python
acs/acs_cold_start.py
Python
mit
7,587
from crizzle.patterns.memoize import memoize from crizzle.patterns.observer import Observable, Observer from crizzle.patterns.singleton import Singleton from crizzle.patterns.deprecated import deprecated from crizzle.patterns.value_checking import assert_none, assert_not_none, assert_in, assert_type, assert_equal from ...
tasercake/Crypto_Algotrader
crizzle/patterns/__init__.py
Python
mit
398
import pwn from basechatter import basechatter class process(basechatter): def __init__(self, cmd, *args, **kwargs): env = kwargs.get('env', {}) timeout = kwargs.get('timeout', 'default') silent = kwargs.get('silent', False) basechatter.__init__(self, timeout, silent) self.p...
Haabb/pwnfork
pwn/process.py
Python
mit
1,834
from django.conf import settings from django.db.models import signals from django.utils.translation import ugettext_noop as _ if "notification" in settings.INSTALLED_APPS: from notification import models as notification def create_notice_types(app, created_models, verbosity, **kwargs): notificatio...
ericholscher/pinax
pinax/apps/projects/management.py
Python
mit
922
from typing import List from scipy.optimize import brentq import numpy as np def m1(m2: float) -> float: return 1 - m2 def x1(m2: float) -> float: return -m2 def x2(m2: float) -> float: return 1 - m2 def lagrange_points(m2: float) -> List[float]: """ The 3 colinear Lagrange points ...
Camiloasc1/AstronomyUNAL
CelestialMechanics/canonical_units/canonical_units.py
Python
mit
781
from ..base import AST CLASS = "statements.assignment" class AssignmentStatement(AST): """ Assign statement class for AST. interpret - runtime function for Evaluator (return variable by name from environment). Example: x := 56 """ def __init__(self, variable, aexp): super().__init__(C...
PetukhovVictor/compiler
src/Parser/AST/statements/assignment.py
Python
mit
445
# A comment, this is so you can read your program later. # Anything after the # is ignored by python. print("I could have code like this.") # and the comment after is ignored # You can also use a comment to "disable" or comment out a piece of code: # print "This won't run." print("This will run.")
Oreder/PythonSelfStudy
Exe_02.py
Python
mit
302
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys from telesto import plot OFFSET = 1000 # REMEMBER TO CALCULATE MANUALLY! def main(): path = sys.argv[1] mean = plot.mean( plot.rows(path, plot.parse_middleware_line), ("waiting", "parsing", "database", "response") ) dev = p...
dola/Telesto
tools/protocol/telesto/plot/phases.py
Python
mit
718
from PySide.QtCore import * from PySide.QtGui import * import managers class lineNumberBarClass(QWidget): def __init__(self, edit, parent=None): QWidget.__init__(self, parent) self.edit = edit self.highest_line = 0 self.setMinimumWidth(30) self.edit.installEventFilter(self) ...
cineuse/CNCGToolKit
apps/pw_multiScriptEditor/widgets/numBarWidget.py
Python
mit
3,802
#!/usr/bin/env python # encoding: utf-8 import logging import os import sys import time import beanstalkc logging.basicConfig(level=logging.DEBUG, format=u'%(asctime)-15s %(name)-12s: %(levelname)-8s %(message)s') LOG = logging.getLogger('queueit') LOG.setLevel(logging.DEBUG) # Loading values from the shell ENV QHOS...
chexov/queueit
beanstalkd/queueit/__init__.py
Python
mit
12,543
# -*- coding: utf-8 -*- from __future__ import division import stripe from django.db import models from django.conf import settings from django.core.exceptions import ValidationError from ..accounts.models import Member if hasattr(settings, 'STRIPE_SECRET_KEY'): stripe.api_key = settings.STRIPE_SECRET_KEY class...
vinta/sublimall-server
sublimall/donations/models.py
Python
mit
1,788
# import the necessary packages from keras.layers.core import Dropout from keras.layers.core import Flatten from keras.layers.core import Dense class FCHeadNet: @staticmethod def build(baseModel, classes, D): # initialize the head model that will be placed on top of # the base, then add a FC layer headModel = ...
CyberLabs-BR/face_detect
pyimagesearch/nn/conv/fcheadnet.py
Python
mit
604
""" This module provides database setup and configuration. """ from database_utils import establish_session from models import Restaurant, MenuItem SESSION = None def create_data(): """Function to create and set up DB and populate with data.""" global SESSION SESSION = establish_session() # Query f...
hessler/udacity-courses
full_stack_foundations/vagrant/restaurant/database_setup.py
Python
mit
3,008
from django.contrib.auth import update_session_auth_hash from rest_framework import serializers from authentication.models import Account class AccountSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True, required=False) confirm_password = serializers.CharField(write_onl...
bewallyt/Classy
authentication/serializers.py
Python
mit
1,481
""" usage 'pinhole port host [newport]' Pinhole forwards the port to the host specified. The optional newport parameter may be used to redirect to a different port. eg. pinhole 80 webserver Forward all incoming WWW sessions to webserver. pinhole 23 localhost 2323 Forward all telnet sessions to port 2323 ...
ActiveState/code
recipes/Python/114642_Pinhole/recipe-114642.py
Python
mit
2,454
import shipane_sdk # 初始化函数,设定要操作的股票、基准等等 def initialize(context): # 定义一个全局变量, 保存要操作的股票 # 000001(股票:平安银行) g.security = '000001.XSHE' # 设定沪深300作为基准 set_benchmark('000300.XSHG') def process_initialize(context): # 创建 StrategyManager 对象 # 参数为配置文件中的 manager id g.__manager = shipane_sdk.Joi...
Pyangs/ShiPanE-Python-SDK
examples/joinquant/simple_strategy.py
Python
mit
911
class IRCUser(object): def __init__(self, user): self.user = None self.hostmask = None self.last_active = None if "!" in user: user_array = user.split("!") self.name = user_array[0] if len(user_array) > 1: user_array = user_array...
HubbeKing/Hubbot_Twisted
hubbot/user.py
Python
mit
629
# -*- coding: utf-8 -*- # main.py import webapp2 from authomatic import Authomatic from authomatic.adapters import Webapp2Adapter from config import CONFIG # Instantiate Authomatic. authomatic = Authomatic(config=CONFIG, secret='some random secret string') # Create a simple request handler for the login procedure. ...
peterhudec/authomatic
examples/gae/simple/main.py
Python
mit
6,966
"""Query utils.""" class LuaScript: def __init__(self, script): self.script = script class LuaStoredQuery: def __init__(self, name, query_args): self.name = name self.args = query_args class LogicalOperator: def __init__(self, *args): self.clauses = args def __str_...
tsileo/blobstash-python-docstore
blobstash/docstore/query.py
Python
mit
4,218
from django.shortcuts import render from django.template.loader import render_to_string def home(request): context_dict = {} return render(request,'ms2ldaviz/index.html',context_dict) def people(request): context_dict = {} return render(request,'ms2ldaviz/people.html',context_dict) def api(request...
sdrogers/ms2ldaviz
ms2ldaviz/ms2ldaviz/views.py
Python
mit
936
#!/usr/bin/env python """ Cacheability checking function. """ from redbot.formatter import relative_time, f_num from redbot.message import HttpRequest, HttpResponse from redbot.speak import Note, categories, levels ### configuration cacheable_methods = ["GET"] heuristic_cacheable_status = ["200", "203", "206", "300"...
mnot/redbot
redbot/message/cache.py
Python
mit
29,383
import praw, time, ConfigParser, pprint from optparse import OptionParser USERAGENT = "Reddit Feedback Thread Cleaner | a bot by /u/BizCaus" # Config parser = OptionParser() parser.add_option("-c", "--config", dest="conf_path", type="string", help="config file path") (options, args) = parser.parse_args() config = Co...
vincentriemer/edmp-fb-thread-cleaner-bot
robot.py
Python
mit
4,040
""" License MIT License Copyright (c) 2017 OpenAdaptronik 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,...
IT-PM-OpenAdaptronik/Webapp
apps/register/urls.py
Python
mit
1,410
from __future__ import print_function, division import numpy as np class Tuning(): """ Equal temperament tuning - allows to convert between frequency and pitch. - unit pitch space - continous, unbounded - 1.0 ~ one octave - step pitch space - continous, unbounded - N steps ~ o...
bzamecnik/tfr
tfr/tuning.py
Python
mit
1,850
class Solution(object): def removeDuplicates(self, nums): """ :type nums: List[int] :rtype: int """ length = len(nums)-1 if length<=0: return 0 pos = 1 cnt = 1 last = nums[0] while length > 0: if nums[pos] == last: ...
xingjian-f/Leetcode-solution
80. Remove Duplicates from Sorted Array II.py
Python
mit
605
#!/usr/bin/env python from __future__ import print_function import sys from BioSQL import BioSeqDatabase from BioSQL import Loader from common import standard_options, get_seqfeature_id_from_qv import csv class CustomDBLoader(Loader.DatabaseLoader): """This is a slightly modified version of Loader.DatabaseLoader ...
ctSkennerton/BioSQL-Extensions
scripts/add_annotation_to_protein.py
Python
mit
9,369
# __init__.py # # Author : James Mnatzaganian # Contact : http://techtorials.me # Organization : NanoComputing Research Lab - Rochester Institute of # Technology # Website : https://www.rit.edu/kgcoe/nanolab/ # Date Created : 12/05/15 # # Description : Defines the examples packag...
tehtechguy/mHTM
src/examples/__init__.py
Python
mit
550
# clustering.py # cluster yelp and TA data # # Rob Churchill # # NOTE: IN ORDER TO GET ANY VISUALIZATIONS OUT OF THIS SCRIPT, # YOU MUST PUT THIS IN AN IPYTHON NOTEBOOK OR SOMETHING SIMILAR # # NOTE: I learned to do this in my data science class last semester. If you are looking for plagiarism things, you will a...
rchurch4/georgetown-data-science-fall-2015
analysis/clusterings/clustering.py
Python
mit
4,732
import factory from django.contrib.auth.models import User from django.utils import timezone from events.models import Event, EventInvite from userprofiles.models import FriendRequest class UserFactory(factory.django.DjangoModelFactory): class Meta: model = User class Params: join_event = No...
kosior/eventful
eventful/events/tests/factories.py
Python
mit
2,221
# Generated by Django 1.10.1 on 2018-03-22 20:02 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('show', '0004_show_slug'), ] operations = [ migrations.AddField( model_name='show', name='short_description', ...
Karspexet/Karspexet
karspexet/show/migrations/0005_show_short_description.py
Python
mit
395
""" Implements a multitask graph convolutional classifier. """ from __future__ import print_function from __future__ import division from __future__ import unicode_literals __author__ = "Han Altae-Tran and Bharath Ramsundar" __copyright__ = "Copyright 2016, Stanford University" __license__ = "MIT" import warnings imp...
Agent007/deepchem
contrib/one_shot_models/multitask_classifier.py
Python
mit
9,985
from collections import deque, OrderedDict from django.conf import settings from elasticsearch_dsl import Document, Date, Integer, Keyword, Text, Search, Index, Boolean, Completion, \ SearchAsYouType, normalizer, analyzer from elasticsearch_dsl.connections import connections from tqdm import tqdm from elasticsearc...
kingsdigitallab/tvof-django
tvof/text_search/es_indexes.py
Python
mit
12,832
class Solution: def summaryRanges(self, nums: List[int]) -> List[str]: i = 0 result = [] while i < len(nums): start = i while i + 1 < len(nums) and nums[i] + 1 == nums[i + 1]: i += 1 if i == start: result.append(str(nums[sta...
jiadaizhao/LeetCode
0201-0300/0228-Summary Ranges/0228-Summary Ranges.py
Python
mit
455
from ctypes import c_void_p from django.contrib.gis.geos.error import GEOSException # Trying to import GDAL libraries, if available. Have to place in # try/except since this package may be used outside GeoDjango. try: from django.contrib.gis import gdal except ImportError: # A 'dummy' gdal module. ...
diego-d5000/MisValesMd
env/lib/python2.7/site-packages/django/contrib/gis/geos/base.py
Python
mit
1,714
#!/usr/bin/env python CARD_IMAGE_TOKEN_CLASS = 'card-small-icon' CARD_TEXT_BOX_CLASS = 'card-text' ### PATHS ### If Gatherer changes how it stores card details, the paths ### can be edited here # Path for card links on a search result page CARD_LINKS = '//tr/td/div/span[@class="cardTitle"]/a' # Path to the table wh...
Trigition/MTG-DataScraper
mtg_dataminer/paths.py
Python
mit
1,594
class Emitter(object): _events = None def __init__(self): self._events = {} def on(self, name, fn): self._events.setdefault(name, set([])).add(fn) return self def fire(self, name, data): for fn in self._events.get("*", set([])): fn(name, data) for ...
panoplyio/panoply-python-sdk
panoply/events.py
Python
mit
401
from rllab.envs.mujoco.gather.gather_env import GatherEnv from sandbox.snn4hrl.envs.mujoco.ant_env import AntEnv class AntGatherEnv(GatherEnv): MODEL_CLASS = AntEnv ORI_IND = 3
florensacc/snn4hrl
envs/mujoco/gather/ant_gather_env.py
Python
mit
189
from django.conf import settings as django_settings # noinspection PyPep8Naming class LazySettings: @property def REQUIRE_MAIN_NAME(self): return getattr(django_settings, 'REQUIRE_MAIN_NAME', 'main') @property def DEFAULT_PAGINATE_BY(self): return getattr(django_settings, 'DEFAULT_PAG...
Pyco7/django-ajax-views
ajaxviews/conf.py
Python
mit
1,622
######################################################################elias's code import turtle import random import time turtle.tracer(1,0) size_x=800 size_y=500 turtle.setup(size_x,size_y) turtle.penup() #how far the snake moves SQUARE_SIZE=20 pos_list=[] plane=turtle.clone() #the shape of the plane turtle.regist...
shellyw19-meet/meet2017y1final-proj
elias.py
Python
mit
2,393
""" These functions are written assuming the under a moto call stack. TODO add check is a fake bucket? """ import boto3 def pre_load_s3_data(bucket_name, prefix, region='us-east-1'): s3 = boto3.client('s3', region_name=region) res = s3.create_bucket(Bucket=bucket_name) default_kwargs = {"Body": b"Fake da...
DigitalGlobe/gbdxtools
tests/unit/moto_test_data.py
Python
mit
1,017
#-*-coding:utf-8-*- from functools import wraps from flask import abort from flask.ext.login import current_user from models import Permission def permission_required(permission): #用于检查权限,就像检查登陆一样 def decorator(f): @wraps(f) def decorated_function(*args, **kwargs): if not current_use...
chen940303/Diaosier_home
app/decorators.py
Python
mit
698
class __ConfigBus(object): def __init__(self): """Private object *_ConfigBus* provides private functions for various config classes. """ self.conf = 'eems.conf' def _read(self): """Private function *_read* reads the eems.conf file and returns all lines. :return: *l...
enricoba/eems-box
configbus.py
Python
mit
2,756
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('api', '0009_dummyprovider'), ] o...
h2020-westlife-eu/VRE
api/migrations/0010_auto_20160121_1536.py
Python
mit
4,758
import sys from collections import Counter rows = zip(*[l.strip() for l in sys.stdin]) print ''.join(Counter(l).most_common()[-1][0] for l in rows) # 0 zamiast -1 dla part1
tehasdf/AdventOfCode2016
p6.py
Python
mit
175
from ipaddress import IPv4Address, IPv4Interface, IPv4Network, IPv6Address, IPv6Interface, IPv6Network import pytest from pydantic import BaseModel, IPvAnyAddress, IPvAnyInterface, IPvAnyNetwork, ValidationError # # ipaddress.IPv4Address # ipaddress.IPv6Address # pydantic.IPvAnyAddress # @pytest.mark.parametrize( ...
samuelcolvin/pydantic
tests/test_networks_ipaddress.py
Python
mit
17,339
import time import numpy import sqlite3 from matplotlib.ticker import MaxNLocator class PlotDepth(object): def __init__(self, figure, canvas, axconf=None): self._setup_db() self.fig = figure self.canvas = canvas if axconf: self.ax = self.fig.add_axes(axconf) el...
knowitnothing/btcx
gui/plot/depthplot.py
Python
mit
6,480
from setuptools import setup, find_packages from codecs import open from os import path here = path.abspath(path.dirname(__file__)) # Get the long description from the README file with open(path.join(here, 'README.md'), encoding='utf-8') as f: long_description = f.read() setup( name='funfolding', version...
mbrner/funfolding
setup.py
Python
mit
1,277
from django import forms from django.contrib.auth.models import User from django.forms.models import ModelForm from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit from .models import UserProfile class UserForm(ModelForm): password = forms.CharField(widget=forms.PasswordInput()) ...
kburts/django-playlist
django_playlist/auth/forms.py
Python
mit
954
# MIT License # Copyright (c) 2017 MassChallenge, Inc. from accelerator.models import UserRole from impact.v1.events.base_user_became_mentor_event import ( BaseUserBecameMentorEvent, ) class UserBecameDesiredMentorEvent(BaseUserBecameMentorEvent): EVENT_TYPE = "became desired mentor" USER_ROLE = UserRole...
masschallenge/impact-api
web/impact/impact/v1/events/user_became_desired_mentor_event.py
Python
mit
362
#!usr/bin/python from BeautifulSoup import BeautifulSoup as bs def schedule(text): soup = bs(text) l = soup.body.table.findAll('td', attrs={'class':'scheduleBody'}) final = [] for row in l: if 'portal' in str(row): if row: sp = bs(str(row)) url = sp.a['href'] name = sp.a.b.contents[0] final.a...
legoktm/legoktm
icstalker/iclib/scrape.py
Python
mit
695
from abc import ABCMeta, abstractmethod, abstractproperty import os class STORE_TYPE: PATH = 0 # TODO: cover with tests class StorageAbstract(object): """Data storage abstract class """ __metaclass__ = ABCMeta @abstractmethod def store(self): """ :param output: of type IOHandl...
doclements/pywps-4
pywps/storage.py
Python
mit
2,563
#!/usr/bin/env python2 # -*- coding : utf8 -*- import unittest import re from section.four import * class TestSectionFour(unittest.TestCase): def setUp(self): """this is run before each test, we need to create a SectionFour object""" self.testee=SectionFour() def test_init(self): se...
SpoonBoy/python-aws-foundation
test/test_four.py
Python
mit
1,580
# 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-mgmt-web/azure/mgmt/web/models/conn_string_info.py
Python
mit
1,412
__author__ = 'breddels' # from https://github.com/pyinstaller/pyinstaller/wiki/Recipe-PyQt4-API-Version import sip sip.setapi(u'QDate', 2) sip.setapi(u'QDateTime', 2) sip.setapi(u'QString', 2) sip.setapi(u'QTextStream', 2) sip.setapi(u'QTime', 2) sip.setapi(u'QUrl', 2) sip.setapi(u'QVariant', 2)
maartenbreddels/vaex
packages/vaex-ui/vaex/ui/rthook_pyqt4.py
Python
mit
298
# -*- coding: utf-8 -*- # # fluff documentation build configuration file, created by # sphinx-quickstart on Wed Jan 6 16:41:47 2016. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All...
simonvh/fluff
docs/conf.py
Python
mit
9,233
from pprint import pformat import boto3 from clint.textui import indent, puts, prompt def _get_instance_details(instance): return { 'tags': instance.tags, 'launch_time': instance.launch_time.isoformat(), 'instance_type': instance.instance_type, 'state': instance.state, 'ke...
lchi/blimp
blimp/commands/terminate.py
Python
mit
1,260
from __future__ import unicode_literals import os import paramiko from django.utils import six from djblets.testing.decorators import add_fixtures from reviewboard import scmtools from reviewboard.hostingsvcs.models import HostingServiceAccount from reviewboard.reviews.models import ReviewRequest from reviewboard.sc...
1tush/reviewboard
reviewboard/webapi/tests/test_repository.py
Python
mit
31,592
"""taskburster 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') Clas...
danhuynhdev/taskbuster
taskbuster/urls.py
Python
mit
1,187
""" Google's clitable.py is inherently integrated to Linux: This is a workaround for that (basically include modified clitable code without anything that is Linux-specific). _clitable.py is identical to Google's as of 2017-12-17 _texttable.py is identical to Google's as of 2017-12-17 _terminal.py is a highly stripped...
fooelisa/netmiko
netmiko/_textfsm/_clitable.py
Python
mit
12,990
import re import tempfile from dependencies_resolver.config.configuration import \ REGEX_MULTIPART_UPLOAD_PATTERN from dependencies_resolver.utils.md5_checksum import get_aws_like_md5_checksum from tests.utils.test_s3_utils import MOCKED_MD5_CHECKSUM def test_get_md5_checksum_no_multipart_upload(): """A test...
onfido/dependencies-resolver
tests/utils/test_md5_checksum.py
Python
mit
1,242
#!/usr/bin/python3 """Print information about pmaps.""" import numpy as np import dwi.conf import dwi.files from dwi.files import Path import dwi.image import dwi.mask import dwi.util lambdas = dict( path=lambda x: x.info['path'], name=lambda x: x.info['path'].name, stem=lambda x: x.info['path'].stem, ...
jupito/dwilib
dwi/tools/pmapinfo.py
Python
mit
3,191
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('order', '0003_customer_customer_slug'), ] operations = [ migrations.AddField( model_name='product', ...
alejo8591/angular-labs
lab15/order/migrations/0004_product_product_likes.py
Python
mit
467
import _plotly_utils.basevalidators class LocationsValidator(_plotly_utils.basevalidators.DataArrayValidator): def __init__( self, plotly_name="locations", parent_name="volume.slices.x", **kwargs ): super(LocationsValidator, self).__init__( plotly_name=plotly_name, pare...
plotly/plotly.py
packages/python/plotly/plotly/validators/volume/slices/x/_locations.py
Python
mit
427
# -*- coding: utf-8 -*- import time import math import numpy as np from toolz.curried import operator as op import importlib.util from typing import Union, Text, NewType, List, Callable, Tuple try: importlib.util.find_spec('RPi.GPIO') importlib.util.find_spec('smbus2 ') import smbus2 as smbus import RPi...
HARDWAREdotASTRO/ROBh.aTnetwork
Robhat/Robhat/Dome/Sensors.py
Python
mit
9,062
from .models import Users from .conftest import USER_CREDENTIALS import pytest PRIVATE_ROUTES = [ ('/search'), ('/add/{name}/{id}'), ('/delete/{sym}'), ('/portfolio'), ('/details/{sym}'), ] PUBLIC_ROUTES = [ ('/login'), ('/about'), ('/new_user') ] @pytest.mark.parametrize('route', PU...
tanyaweaver/market-analysis
market_analysis/test_security.py
Python
mit
7,649