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
import pymongo import configparser def db(): config = configparser.RawConfigParser() config.read('./.config') host = config.get('tumblr', 'host') port = config.get('tumblr', 'port') user = config.get('tumblr', 'user') passwd = config.get('tumblr', 'passwd') client = pymongo.MongoClient(hos...
blacksky0000/tools
tumblr/dbconnect.py
Python
mit
463
import pytest from nex.reader import Reader, ReaderBuffer from common import (test_not_here_file_name, test_file_name, test_chars, test_2_chars) def test_buffer_init(): """Check buffer works sensibly.""" r = ReaderBuffer(test_chars) assert r.i == -1 assert r.chars == test_chars ...
eddiejessup/nex
tests/test_reader.py
Python
mit
3,129
# -*- coding: utf-8 -*- #BEGIN_HEADER # The header block is where all import statments should live import os import uuid from KBaseReport.KBaseReportClient import KBaseReport #END_HEADER class RRoller: ''' Module Name: RRoller Module Description: A KBase module: RRoller This sample module con...
sychan/RRoller
lib/RRoller/RRollerImpl.py
Python
mit
4,705
# encoding: utf-8 from __future__ import unicode_literals import pytest from web.core.context import Context from web.db.sa import SQLAlchemyConnection from sqlalchemy import Column, String, Integer, ForeignKey from sqlalchemy.orm import relationship from sqlalchemy.ext.declarative import declarative_base Base = ...
marrow/web.db
test/test_sqlalchemy.py
Python
mit
1,437
# import os # os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" # os.environ["CUDA_VISIBLE_DEVICES"] = "1" import torch import torch.nn as nn from torch import optim from torch.autograd import Variable import torch.nn.functional as F from src.python.dingo_utils2 import * from src.python.preprocess2 import * from src.p...
yotamfr/prot2vec
src/python/dingo_net1.py
Python
mit
13,615
#!/usr/bin/env python3 # Copyright (c) 2020-2021 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test the send RPC command.""" from decimal import Decimal, getcontext from itertools import product f...
kallewoof/bitcoin
test/functional/wallet_send.py
Python
mit
29,974
""" Contains the models to be used with the SQLAlchemy database interface.\n Meant to be used by the background scripts, not the Flask app.\n Created by Abigail Franz on 3/12/2018.\n Last modified by Abigail Franz on 4/30/2018. Update March 2019 - This is a really helpful guide: https://stackoverflow.com/questions/41...
jazzij/powertoken
data/models.py
Python
mit
4,868
from cs50 import SQL from flask import session from helpers import usd db = SQL("sqlite:///finance.db") def get_cash(): return float(db.execute("SELECT cash FROM users WHERE id = :id", id=session["user_id"])[0]["cash"]) def get_username(): return db.execute("SELECT username FROM ...
marzique/cs50_finance
sqlquery.py
Python
mit
382
#usr/bin/python ######## LICENSE ######## ##This is a template file that shows the basic layout for most games. It ##is a good starting point when beginning a game. I have tried to ##document the code as clearly as possible. This template was created ##by Simon Baumgardt-Wellander for use by the Olympia High School G...
tectronics/ohs-gdc-roy
src/template.py
Python
mit
7,185
#!/usr/bin/env python3 # 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. """ Agent that gets the local keyboard input in the act() function. Applies safety classifier(s) to process user and par...
facebookresearch/ParlAI
parlai/agents/safe_local_human/safe_local_human.py
Python
mit
4,597
# Copyright (c) 2012 The Khronos Group Inc. # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and /or associated documentation files (the "Materials "), to deal in the Materials without restriction, including without limitation the rights to use, copy, modify, merge, publis...
KhronosGroup/COLLADA-CTS
Scripts/FMaya.py
Python
mit
16,662
""" Timeout decorator. :copyright: (c) 2012-2013 by PN. :license: MIT, see LICENSE for more details. """ from __future__ import print_function from __future__ import unicode_literals from __future__ import division import sys import time import multiprocessing import signal from functools import wraps #####...
yetone/timeout-decorator
timeout_decorator/timeout_decorator.py
Python
mit
5,411
'''Convert a grammar to CNF form and print it to stdout in HTML.''' from cfg import core, cnf CFG = core.ContextFreeGrammar CNF = cnf.ChomskyNormalForm G = CFG(''' S -> ASA | aB A -> B | S B -> b | ''') print '<h1><var>G</var>:</h1>' print G.html() print print '<h1><var>G&prime;</var>:</h1>' print CNF(G).html()
bdusell/pycfg
demos/cnf_html_test.py
Python
mit
318
#!/usr/bin/env python # # Generate pnSeed[] from Pieter's DNS seeder # NSEEDS=600 import re import sys from subprocess import check_output def main(): lines = sys.stdin.readlines() ips = [] pattern = re.compile(r"^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3}):18409") for line in lines: m = patt...
Skytells/Oxcoin
contrib/seeds/makeseeds.py
Python
mit
709
""" MiePy ======= Python module to calcuate scattering coefficients of a plane wave incident on a sphere or core-shell structure using Mie theory """ #main submodules from . import scattering from . import materials from . import mie_sphere from . import array_io from .mie_sphere import sphere from .materials import m...
johnaparker/MiePy
miepy/__init__.py
Python
mit
343
# Copyright (c) 2011 Florian Mounier # Copyright (c) 2012, 2014 Tycho Andersen # Copyright (c) 2013 Craig Barnes # Copyright (c) 2014 Sean Vig # Copyright (c) 2014 Adi Sieker # Copyright (c) 2014 Sebastien Blot # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and assoc...
de-vri-es/qtile
test/test_fakescreen.py
Python
mit
15,532
from setuptools import setup, find_packages setup( name="pypatterns", version="0.2.0", packages=find_packages(), author="Yoav Luft", author_email="yoav.luft@gmail.com", description="Functional style pattern matching for Python", license="MIT", url="https://github.com/Luftzig/pypatterns...
Luftzig/pypatterns
setup.py
Python
mit
809
Python 3.4.2 (default, Oct 19 2014, 13:31:11) [GCC 4.9.1] on linux Type "copyright", "credits" or "license()" for more information. >>> print("hello Joe") hello Joe >>>
davisjoe/joesrobotchallenge
expermients/hello Joe.py
Python
mit
171
"""Settings that need to be set in order to run the tests.""" import os DEBUG = True SITE_ID = 1 APP_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) DATABASES = { 'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', } } LOGIN_REDIRECT_URL = '/hello' HIJA...
arteria/django-hijack
hijack/tests/test_settings.py
Python
mit
3,291
import lexical_uuid from sqlalchemy.dialects.postgresql import BYTEA from sqlalchemy.types import TypeDecorator class LexicalUUID(TypeDecorator): impl = BYTEA def __init__(self): self.impl.length = 16 super(LexicalUUID, self).__init__(length=self.impl.length) def process_bind_param(self, value, dialec...
samuraisam/lexical_uuid
lexical_uuid/alchemy.py
Python
mit
999
import collections from supriya import CalculationRate from supriya.ugens.filters import Filter class BEQSuite(Filter): """ Abstract base class of all BEQSuite UGens. """ class BAllPass(BEQSuite): """ An all-pass filter. :: >>> source = supriya.ugens.In.ar(0) >>> ball_pass...
josiah-wolf-oberholtzer/supriya
supriya/ugens/beq.py
Python
mit
5,478
"""Define tests for systems."""
w1ll1am23/simplisafe-python
tests/system/__init__.py
Python
mit
32
#!/usr/bin/env python people = 30 cars = 40 trucks = 15 if cars > people: print("We should take the cars.") elif cars < people: print("We should not take the cars") else: print("We can't decide.") if trucks > cars: print("That's too many trucks.") elif trucks < cars: print("Maybe we coudl take th...
davvi/Hardway3
ex30.py
Python
mit
492
from flask import Blueprint, request, render_template from ..load import processing_results, api import string import tweepy twitter_mod = Blueprint('twitter', __name__, template_folder='templates', static_folder='static') ascii_chars = set(string.printable) ascii_chars.remove(' ') ascii_chars.add('...') def takeout...
griimick/feature-mlsite
app/twitter/views.py
Python
mit
1,537
import logging logging.basicConfig( level=logging.INFO, format='%(asctime)s|%(name)s|%(levelname)s|%(message)s') logging.getLogger('vcr.stubs').setLevel(logging.WARNING) logging.getLogger('requests.packages.urllib3.connectionpool')\ .setLevel(logging.WARNING) def get_logger(*args, **kwargs): return loggi...
mindriot101/k2catalogue
k2catalogue/k2logging.py
Python
mit
350
# -*- coding: utf-8 -*- import docutils from docutils import nodes from docutils.parsers.rst import Directive, directives from html import escape from collections import Counter import re import os from sphinx.directives.code import CodeBlock from sphinx.errors import SphinxError from sphinx.util.fileutil import copy_a...
Aalto-LeTech/a-plus-rst-tools
directives/annotated.py
Python
mit
15,406
class Solution(object): def nextPermutation(self, nums): cursor = -1 for i in range(len(nums) - 1, 0, -1): if nums[i - 1] < nums[i]: cursor = i - 1 break for i in range(len(nums) - 1, -1, -1): if nums[i] > nums[cursor]: ...
luosch/leetcode
python/Next Permutation.py
Python
mit
459
from django.http import HttpResponse ## ## Courtesy of tastypie ## from djrest.common.helpers import json_parse class HttpCreated(HttpResponse): status_code = 201 def __init__(self, *args, **kwargs): location = kwargs.pop('location', '') super(HttpCreated, self).__init__(*args, **kwargs) ...
humwerthuz/djrest
djrest/http/responses.py
Python
mit
2,012
"""Compute the archive start time of a HADS/DCP/COOP network""" import sys import datetime from pyiem.network import Table as NetworkTable from pyiem.util import get_dbconn, logger LOG = logger() THISYEAR = datetime.datetime.now().year HADSDB = get_dbconn("hads") MESOSITEDB = get_dbconn("mesosite") def get_minvalid...
akrherz/iem
scripts/dbutil/compute_hads_sts.py
Python
mit
2,162
# -*- coding: utf-8 -*- import json from cwr.parser.decoder.common import Decoder from cwr.parser.decoder.dictionary import FileDictionaryDecoder """ Classes for decoding CWR classes from JSON dictionaries. """ __author__ = 'Bernardo Martínez Garrido' __license__ = 'MIT' __status__ = 'Development' class JSONDecod...
weso/CWR-DataApi
cwr/parser/decoder/cwrjson.py
Python
mit
570
from datetime import datetime from json import loads, dumps import os DEFAULTCONFIG = """{"people": []}""" PERSONTEMPLATE = {"name": None, "tags": None, "birthday": None, "pic": None, "frequency": 0} class PeopleContainer(object): def __init__(self, app): self.data = [] self.cfgpath = os.path.join(app.get_...
1egoman/quail-flask
src/people.py
Python
mit
1,454
""" Examples of loading all information about an object or set of objects from the database. """ from __future__ import absolute_import from __future__ import print_function import PyOpenWorm as P from PyOpenWorm.connection import Connection from PyOpenWorm.neuron import Neuron from PyOpenWorm.context import Context f...
gsarma/PyOpenWorm
examples/test_bgp.py
Python
mit
1,886
# !/usr/bin/env python3 # -*- coding: utf-8 -*- from urllib import request # URL抓取 with request.urlopen('https://api.douban.com/v2/book/2129650') as f: data = f.read() print('Status:', f.status, f.reason) for k, v in f.getheaders(): print('%s : %s' % (k, v)) print('Data:', data.decode('utf-8')...
KrisCheng/HackerPractice
Python/module/urllibDemo.py
Python
mit
326
discs = [] # Create data discs.append((13, 11)) discs.append((5, 0)) discs.append((17, 11)) discs.append((3, 0)) discs.append((7, 2)) discs.append((19, 17)) discs.append((11, 0)) done = False t = 0 while done is False: done = True for i, disc in enumerate(discs): if (t + i + 1 + disc[1]) % disc[0] is ...
snyderks/advent-solutions
Day15.py
Python
mit
430
from django.conf.urls import url from . import views app_name = 'polls' urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^(?P<question_id>[0-9]+)$', views.vote, name='vote'), url(r'^(?P<question_id>[0-9]+)/results$', views.results, name='results'), url(r'^add$', views.add, name='add'), ...
kura-pl/fast_polls
polls/urls.py
Python
mit
583
from seabreeze.pyseabreeze.features._base import SeaBreezeFeature # Definition # ========== # # TODO: This feature needs to be implemented for pyseabreeze # class SeaBreezeGPIOFeature(SeaBreezeFeature): identifier = "gpio" modes = dict( GPIO_OUTPUT_PUSH_PULL=0x00, GPIO_OPEN_DRAIN_OUTPUT=0x01,...
ap--/python-seabreeze
src/seabreeze/pyseabreeze/features/gpio.py
Python
mit
2,140
# -*- coding: utf-8 -*- from youtubeAPICrawler.database import * db = YTDatabase() with db._session_scope(True) as session: # Get all channel historys with video counts zero zch = session.query(ChannelHistory).filter( (ChannelHistory.videoCount <= 0) | (ChannelHistory.subscriberCount <= 0) |\ (Channe...
lodemo/CATANA
src/data_collection/youtubeAPICrawler/filterChannelByCounts.py
Python
mit
615
from frasco import Feature, action, hook, current_app, g, request, url_for class MenuMissingError(Exception): pass class Menu(object): def __init__(self, name=None, label=None, view=None, login_required=None, childs=None, separator=False, url=None, **options): self.name = name self.label = l...
frascoweb/frasco-menu
frasco_menu.py
Python
mit
2,929
""" podpy is an implementatin of the pixel optical depth method as described in Turner et al. 2014, MNRAS, 445, 794, and Aguirre et al. 2002, ApJ, 576, 1. Please contact the author (Monica Turner) at turnerm@mit.edu if you have any questions, comment or issues. """
turnerm/podpy
podpy/__init__.py
Python
mit
271
from time import sleep def menu(): try: sleep(1.5) print(menuStr) sleep(0.5) choose = int(input("For Play = 1\nFor Exit = 0\nChoose : ")) print(stars) except: print("There's something wrong about your input. Try again.") menu() if choose == 1: ...
cyhmat/pythonDersleri
XOX.py
Python
mit
8,375
#!/usr/bin/env python # -*- coding: utf-8 -*- # The MIT License (MIT) # Copyright (c) 2017 Juan Cabral # 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 withou...
carpyncho/feets
feets/datasets/synthetic.py
Python
mit
10,431
#!/usr/bin/env python # -*- coding:utf-8 -*- # from __future__ import unicode_literals import codecs import sys reload(sys) sys.setdefaultencoding('utf8') # ranges of ordinals of unicode ideographic characters ranges = [ {"from": ord(u"\u3300"), "to": ord(u"\u33ff")}, # compatibility ideographs {"from": ord...
jntkym/rappers
utils.py
Python
mit
1,664
import time, traceback, string from xmlunit.unittest import _WritelnDecorator, XmlTextTestRunner as his_XmlTextTestRunner from django.test.simple import * from xml.sax.saxutils import escape try: # The django.utils.unittest alias is available in Django >= 1.3 from django.utils import unittest except ImportEr...
garethr/django-test-extensions
src/test_extensions/testrunners/xmloutput.py
Python
mit
5,341
""" Tests for various Pyflakes behavior. """ from sys import version_info from pyflakes import messages as m from pyflakes.test.harness import TestCase, skip, skipIf class Test(TestCase): def test_duplicateArgs(self): self.flakes('def fu(bar, bar): pass', m.DuplicateArgument) def test_localReferen...
bitglue/pyflakes
pyflakes/test/test_other.py
Python
mit
42,084
days = "Mon Tue Wed Thu Fri Sat Sun" months = "Jan\nFeb\nMar\nApr\n...\nSpe\nNov\nDec" print "Here are the days:", days print "Here are the months:", months print "Months: %r" % months # raw printing retains special characters print ''' There's something going on here with the three double quotes We'll be able to t...
aurelo/lphw
source/ex9.py
Python
mit
413
import time import sublime import sublime_plugin ST3 = int(sublime.version()) >= 3000 if ST3: from .view_collection import ViewCollection from .git_gutter_popup import show_diff_popup else: from view_collection import ViewCollection from git_gutter_popup import show_diff_popup def async_event_listen...
natecavanaugh/GitGutter
git_gutter_events.py
Python
mit
3,715
import os import sys import inspect _module = sys.modules[__name__] _safe_import_list = [_x.__name__ for _x in _module, os, sys, inspect] for mod in [m for m in sys.modules.keys() if m != __name__ and sys.modules[m] != None and m.startswith(__name__) and len(m.split(__name__ + ".")[-1].split(".")) == 1 and (not sys.m...
deathglitch/metarigging
python/metaui/__init__.py
Python
mit
1,252
import re import logging log = logging.getLogger('pajbot') class EmoteComboParser: def __init__(self, bot): self.bot = bot self.emote_count = 0 self.current_emote = None def inc_emote_count(self): self.emote_count += 1 if self.emote_count >= 5: self.bot.we...
gigglearrows/anniesbot
pajbot/models/emotecomboparser.py
Python
mit
1,638
from GestureAgentsTUIO.Gestures2D.RecognizerTap import RecognizerTap from recognizer_testing import t_r events_tap = [ ('f', 1, (0.5, 0.5), ( (0, 'in'), (0.1, 'out'))), ] class TUIOTapTestCase1(t_r(events_tap, RecognizerTap, ("newTap",), 1)): pass events_2tap = [ ('f', 1, (0.5, 0.5), ( (...
chaosct/GestureAgents
Apps/TestComposition/test_TUIO_Gestures.py
Python
mit
2,810
import unittest from ddt import ddt, data import tripy class PolyData(object): def __init__(self, name, vertices, triangles, total_area): self.name = name self.vertices = vertices self.triangles = triangles self.total_area = total_area TEST_DATA = [ PolyData( name='St...
linuxlewis/tripy
tests.py
Python
mit
9,113
''' Nesse exer você deve casar linha que tenham alguma consoante seguida de 'aba'. Para fixação, usar o '[^]' (lista negada). ''' import re import sys REGEX = r'' lines = sys.stdin.readlines() for line in lines: if re.search(REGEX, line): print(line.replace('\n', ''))
deniscostadsc/regex-tutorial
17-exercises/03-lista-negada/regex.py
Python
mit
288
from django.urls import reverse from workshops.models import Event, Role, Tag, Task from workshops.tests.base import TestBase class TestInstructorIssues(TestBase): """Tests for the `instructor_issues` view.""" def setUp(self): super().setUp() self._setUpUsersAndLogin() TTT, _ = Tag....
pbanaszkiewicz/amy
amy/reports/tests/test_instructor_issues.py
Python
mit
1,579
import sys with open(sys.argv[1], 'r') as test_cases: for test in test_cases: lista = (test.strip().split(',')) bin1 = bin(int(lista[0])) if bin1[-int(lista[1])] == bin1[-int(lista[2])]: print ('true') else: print ('false')
palaxi00/palaxi00.github.io
Codeeval/bit_positions.py
Python
mit
295
#!/usr/bin/env python # -*- coding: utf-8 -*- import pika from config import * credentials = pika.PlainCredentials(USERNAME,PASSWORD) conn_params = pika.ConnectionParameters(HOST,PORT,PATH,credentials=credentials) conn_broker = pika.BlockingConnection(conn_params) channel = conn_broker.channel() channel.exchange_de...
enixdark/rabbitmq-py
ria/ctl/server.py
Python
mit
1,179
import requests from time import sleep URL = 'http://anonymouse.org/cgi-bin/anon-www.cgi/http://www.ign.com/private/prime/promo/modern-combat-4/code' for i in range(1, 1000): r = requests.get(URL) print r.json()['code'] sleep(2)
avinassh/random-python-scripts
Modern-Combat-4/MC4.py
Python
mit
242
import numpy as np def empirical_rmt(input_returns): """ Empirical RMT computes an empirical correlation matrix and then filters using Random Matrix Theory. THIS FUNCTION TAKES AS INPUT A CLEAN NUMPY ARRAY (please remove n/a first !) To compute a correlation matrix, and then apply Wishart RMT, it is ...
gpostelnicu/fin_data
fin_data/stat/correlation/random_matrix.py
Python
mit
2,722
# -*- coding: utf-8 -*- # # Copyright © Spyder Project Contributors # Licensed under the terms of the MIT License # (see spyder/__init__.py for details) """Spyder terminal default configuration.""" import os import sys WINDOWS = os.name == 'nt' LINUX = sys.platform.startswith('linux') CONF_SECTION = 'terminal' CON...
spyder-ide/spyder-terminal
spyder_terminal/config.py
Python
mit
1,346
#procesamiento digital de senales #universidad santiago de cali from scipy import signal import matplotlib.pyplot as plt import numpy as np import sys sys.path.append('tools/') from fourierFunc import fourierAn from scipy.signal import get_window ########################################## #BLOQUE 1 #definir la frecue...
miltonsarria/dsp-python
filters/ex2/ejemplo_window.py
Python
mit
1,773
# http://codeforces.com/problemset/problem/9/C n = 0 ret = 0 def generate(num): global ret global n if int(num) > n: return ret += 1 generate(num + '0') generate(num + '1') n = int(raw_input()) generate('1') print ret
bristy/HackYourself
codeforces/training/9C.py
Python
mit
255
from AmazonSQSMessage import AmazonSQSMessage class ArchiveJobMessage (AmazonSQSMessage): """ Interface for an ArchiveJob message. """ def __init__ (self, name = None, bucket = None, destinationBucket = None, filePath = None, destinationPath = None): """ Initializes the message and val...
matthappens/taskqueue
taskqueue/ArchiveJobMessage.py
Python
mit
716
############################################################################### # # The MIT License (MIT) # # Copyright (c) Tavendo GmbH # # 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 with...
meejah/AutobahnPython
autobahn/util.py
Python
mit
24,461
""" Code used for running the package directly from the Command Line """ import os.path import logging import argparse import sys from .db import AvailabilityDB from .core import AvailabilityInfo from .reports import ALL_REPORTS from .settings import get_settings def run(): # ----------------------...
supernathan23/dn_availability
dn_availability/cli.py
Python
mit
13,300
"""autogenerated by genpy from hoverboard/ServoRaw.msg. Do not edit.""" import sys python3 = True if sys.hexversion > 0x03000000 else False import genpy import struct import std_msgs.msg class ServoRaw(genpy.Message): _md5sum = "cf1c9d17f7bbedbe8dd2c29cdb7700f8" _type = "hoverboard/ServoRaw" _has_header = True ...
robotics-silver-surfer/surfer-main
lab3/hoverboard/src/hoverboard/msg/_ServoRaw.py
Python
mit
5,572
import seaborn as sns from pudzu.charts import * from pudzu.sandbox.bamboo import * countries = pd.read_csv("datasets/countries.csv")[["country", "continent", "flag"]].split_columns('country', "|").explode('country').set_index('country') df = pd.read_csv("datasets/nobels.csv") df = df[df['category'] == "Litera...
Udzu/pudzu
dataviz/nobelslit.py
Python
mit
5,009
#!/usr/bin/env python import pika import os cloud_broker_host = os.environ.get('CLOUD_BROKER_HOST') cloud_broker_port = os.environ.get('CLOUD_BROKER_PORT') cloud_broker_auth = os.environ.get('CLOUD_BROKER_AUTH') cloud_username = cloud_broker_auth.split(':')[0] cloud_password = cloud_broker_auth.split(':')[1] # Connect...
cloudcomputinghust/IoT
test-component/receive_data_only.py
Python
mit
1,140
from elastic_boogaloo import classifiers, distributions, scorers from elasticsearch import Elasticsearch es_client = Elasticsearch('localhost:9200') scorer = scorers.ElasticsearchIndexTopScorer(es_client, 'megacorp') positive_distribution = distributions.ExponentialDistribution() negative_distribution = distribution...
nkashy1/elastic-boogaloo
example.py
Python
mit
706
# coding=utf-8 __author__ = 'mic' from django import forms from django.utils.translation import ugettext, ugettext_lazy as _ from django.contrib.auth.forms import UserCreationForm from public.models import User class UserSignupForm(forms.ModelForm): """ A form that creates a user, with no privileges, from th...
micfan/dinner
src/public/forms.py
Python
mit
2,640
# -*- coding: utf-8 -*- #!/usr/bin/env python from flask import Markup #Markup(u'<strong>Hello &lt;blink&gt;hacker&lt;/blink&gt;!</strong>') Markup('<strong>Hello %s!</strong>') % '<blink>hacker</blink>' #Markup(u'&lt;blink&gt;hacker&lt;/blink&gt;') Markup.escape('<blink>hacker</blink>') #u'Marked up \xbb HTML' Mar...
Akagi201/learning-python
flask/markup.py
Python
mit
371
import os import re from django.conf import settings from django.core import mail from django.core.urlresolvers import reverse from django.test import TestCase from django.contrib.auth.models import User import pinax from emailconfirmation.models import EmailAddress, EmailConfirmation class PasswordResetTest(Test...
amarandon/pinax
pinax/apps/account/tests/test_password_reset.py
Python
mit
7,013
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('visit', '0073_visit_student_absent_reason'), ] operations = [ migrations.AlterField( model_name='visit', ...
koebbe/homeworks
visit/migrations/0074_auto_20150826_2122.py
Python
mit
670
from Naked.toolshed.shell import muterun from pynode.exceptions import NodeExecutionFailedException from pynode.runners.Runner import Runner class BabelRunner(Runner): def __init__(self, ignore=None, extensions=None, presets=None, plugins=None): babel_arguments = '' if ignore is not None: ...
ptMuta/python-node
pynode/runners/BabelRunner.py
Python
mit
2,294
# -*- coding: utf-8 -*- import uuid import hashlib from datetime import datetime from flask import current_app, request from flask.ext.login import UserMixin, AnonymousUserMixin from werkzeug.security import generate_password_hash, check_password_hash from itsdangerous import TimedJSONWebSignatureSerializer as Serial...
pastgift/seed-website-py
app/models.py
Python
mit
4,907
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Problem' db.create_table(u'game_problem', ( (u'id', self.gf('django.db.models.fi...
hackcyprus/junior
game/migrations/0001_initial.py
Python
mit
4,851
""" To understand why this file is here, please read: http://cookiecutter-django.readthedocs.io/en/latest/faq.html#why-is-there-a-django-contrib-sites-directory-in-cookiecutter-django """ # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.conf import settings from django.db import migrations...
betobaz/django_docker
actio_control/contrib/sites/migrations/0002_set_site_domain_and_name.py
Python
mit
1,140
import math from collections import deque def run(): N, K, W = list(map(int, input().split())) Ls = list(map(int, input().split())) A_L, B_L, C_L, D_L = list(map(int, input().split())) Hs = list(map(int, input().split())) A_H, B_H, C_H, D_H = list(map(int, input().split())) for i in range(K+1, ...
mjenrungrot/competitive_programming
Facebook Hackercup/2020/Round 1/A1.py
Python
mit
3,016
# -*- coding: utf-8 -*- # Generated by Django 1.9.11 on 2017-03-16 04:50 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('payments', '0006_auto_20161231_2045'), ] operations = [ migrations.AlterFie...
phildini/logtacts
payments/migrations/0007_auto_20170316_0450.py
Python
mit
784
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ Here are all the test parameters and values for the each `~astropy.modeling.FittableModel` defined. There is a dictionary for 1D and a dictionary for 2D models. Explanation of keywords of the dictionaries: "parameters" : list or dict Model parame...
piotroxp/scibibscan
scib/lib/python3.5/site-packages/astropy/modeling/tests/example_models.py
Python
mit
8,459
import threading class Server_recv(threading.Thread): def __init__(self, client_sock_, list_of_sockets_): threading.Thread.__init__(self) self.client_sock = client_sock_ self.list_of_sockets = list_of_sockets_ def run(self): while True: msg_from_client = self.client...
validata/ExaminationChat
Server/Controller/Server_threading.py
Python
mit
1,049
from gps import * import time import threading import math class GpsController(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.gpsd = gps(mode=WATCH_ENABLE) #starting the stream of info self.running = False def run(self): self.running = True ...
linusluotsinen/RPiAntiTheft
util/gps_handler/gps_controller.py
Python
mit
1,812
from django.contrib import admin from login.models import Category, Page from login.models import UserProfile class CategoryAdmin(admin.ModelAdmin): prepopulated_fields = {'slug':('name',)} admin.site.register(Category, CategoryAdmin) admin.site.register(Page) admin.site.register(UserProfile) # Register your mo...
jnayak1/cs3240-s16-team16
login/admin.py
Python
mit
331
# encoding=utf-8 ## SOLVED 2014/11/29 ## 661 # Consider quadratic Diophantine equations of the form: # x^2 – Dy^2 = 1 # For example, when D=13, the minimal solution in x is 649^2 – 13×180^2 = 1. # It can be assumed that there are no solutions in positive integers when D is # square. # By finding minimal solutions ...
6112/project-euler
problems/066.py
Python
mit
2,117
MAX_RESULTS_PER_PAGE = 100 def all(listf, **kwargs): """ Simple generator to page through all results of function `listf`. """ if not kwargs.get('limit'): kwargs['limit'] = MAX_RESULTS_PER_PAGE resp = listf(**kwargs) for obj in resp['objects']: yield obj while resp['meta...
philipn/localwiki-geocode-pagenames
geocode_pagenames/utils.py
Python
mit
688
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Choice', fields=[ ('id', models.AutoField(verbo...
civet-software/CIVET-Django
djcivet_site/djciv_data/migrations/0001_initial.py
Python
mit
1,089
#!/usr/bin/env python3 # generate 'mandel_grid.vtr' first ! import vtk # source r = vtk.vtkXMLRectilinearGridReader() r.SetFileName('mandel_grid.vtr') # mapper mandelMapper = vtk.vtkDataSetMapper() mandelMapper.SetInputConnection(r.GetOutputPort()) mandelMapper.SetScalarModeToUsePointFieldData() mandelMapper.SelectC...
dubrayn/dubrayn.github.io
examples/vtk/vtk_load_grid.py
Python
mit
784
# Input: # N # U:p,q # U:x,y # ..... # U:a,b # C:a,y # Output: # TRUE/FALSE import os from subprocess import Popen, PIPE import time count = 0 def printline(): x = '' for i in range(80): x = x + "=" print x def singleTest(qn, ansExp): global count child = Popen("./exe", stdin=PIPE, stdout=PIPE) c...
bhagatyj/algorithms
dataStructures/priorityQ/c/priorityQTest.py
Python
mit
1,399
import os import numpy as np import pandas as pd import matplotlib.pyplot as plt from scipy.interpolate import interp1d import spectral.io.envi as envi import tensorflow as tf from scipy import optimize switch_excel = 0 switch_envi = 1 switch_dataFrame = 0 switch_sp_choice_envi = 0 switch_mutiBands = 1 #Modified ga...
Vincentyao1995/Globalink2017-UBC
Vincent/REE_Patterns/ModifiedGaussianModel.py
Python
mit
11,072
#!/usr/bin/env python3 # -*- encoding: utf-8 -*- import weakref a_set = {0, 1} wref = weakref.ref(a_set) print(wref) print(wref()) a_set = {2, 3, 4} print(wref()) print(wref() is None) print(wref() is None) class Cheese: def __init__(self, kind): self.kind = kind def __repr__(self): return...
xu6148152/Binea_Python_Project
FluentPython/object_reference_mutability_recycling/weakref_test.py
Python
mit
647
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('hikaye', '0001_initial'), ] operations = [ migrations.RenameModel( old_name='stories', new_name='Sto...
oznurf/EKSI_HIKAYE
hikaye/migrations/0002_auto_20150819_1605.py
Python
mit
342
import pytest from django_cookiecutter_docker.users.forms import UserCreationForm from django_cookiecutter_docker.users.tests.factories import UserFactory pytestmark = pytest.mark.django_db class TestUserCreationForm: def test_clean_username(self): # A user with proto_user params does not exist yet. ...
realpython/django_cookiecutter_deploy
django_cookiecutter_docker/users/tests/test_forms.py
Python
mit
1,151
""" Nose plugin to add warnings filters (turn them into error) using nose.cfg file. """ from __future__ import absolute_import __version__ = '0.1.5' from .testing import utils from .base import import_item, from_builtins, InvalidConfig, WarningFilter, WarningFilterRunner
Carreau/nose_warnings_filters
nose_warnings_filters/__init__.py
Python
mit
277
import os import pytest from cffitsio._cfitsio import ffi, lib @pytest.fixture def fits_open_file(test_file): f = ffi.new('fitsfile **') status = ffi.new('int *') lib.fits_open_file(f, test_file.encode('utf-8'), 0, status) assert status[0] == 0 return (f, status) def test_create_file(tmpdir): ...
mindriot101/fitsio-cffi
testing/test_direct_wrapper.py
Python
mit
1,990
# -*- 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/tione/v20191022/models.py
Python
mit
91,250
def print_time(t): print "%2d : %2d : %2d" % (t.hour, t.minute, t.second) def time_to_int(time): minutes = time.hour * 60 + time.minute seconds = minutes * 60 + time.second return seconds def int_to_time(seconds): time = Time() minutes, time.second = divmod(seconds, 60) time...
Faraaz54/python_training_problems
codecademy_scripts/class_time.py
Python
mit
908
# coding: utf-8 import os from datetime import datetime from pigrate import PigrateError class Pigration(object): def __init__(self, id, name, script): self.id = id self.name = name self.script = script def __repr__(self): return '{0}-{1}.pigrate.py'.format(self.id, self.name...
eiiches/pigrate
pigrate/internal.py
Python
mit
2,208
from .scheduler import SchedulerResource from .worker import WorkerResource
wehriam/awspider
awspider/resources2/__init__.py
Python
mit
75
from django.conf.urls import include, url from django.views.generic.base import RedirectView from server.views import app # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = [ # Uncomment the next line to enable the admin: url(r'^admin/', i...
mwillmott/techbikers
server/urls.py
Python
mit
482
from bitcoinrpc.authproxy import AuthServiceProxy, JSONRPCException from btcrpc.utils.config_file_reader import ConfigFileReader import json import socket, errno from btcrpc.utils.log import * log = get_log("BTCRPCCall:") class BTCRPCCall(object): def __init__(self, wallet="receive", currency="btc"): yml_conf...
BTCX/BTCX_blockchain
btcxblockchainapi/btcrpc/utils/btc_rpc_call.py
Python
mit
3,371
import unittest import transaction from pyramid import testing from climasng.tests import ProseMakerTestCase from climasng.parsing.prosemaker import ProseMaker # =================================================================== class TestProseMakerConditions(ProseMakerTestCase): # ----------------------------...
DanielBaird/CliMAS-Next-Generation
climas-ng/climasng/tests/test_prosemaker_conditions_rangenum.py
Python
mit
8,241
import time import sys import urllib2 import urllib2 n = int(sys.argv[1]) url = sys.argv[2] headers = {"Accept-Language" : "en" } req = urllib2.Request(url, None, headers) t0 = time.time() for k in xrange(n): data = urllib2.urlopen(req).read() print (time.time()-t0)/n if n==1: print data
andersonsilvade/python_C
Python32/web2py/scripts/bench.py
Python
mit
295
myname = "the_package" crow2_pluginset = True
lahwran/crow2
crow2/test/plugin_targets/simple_package/__init__.py
Python
mit
46