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 -*-
from datetime import datetime, timedelta
from time import sleep
from django.core.mail.backends.base import BaseEmailBackend
from boto.regioninfo import RegionInfo
from boto.ses import SESConnection
from django_ses_backend import settings
# When changing this, remember to change it in setup... | piotrbulinski/django-ses-backend | django_ses_backend/__init__.py | Python | mit | 7,068 |
#!/usr/bin/env python
import sys
with open(sys.argv[2]) as f:
try:
sol = [int(x) for x in f.readline().split()]
if sol == [0]:
print("No satisfying valuation found")
sys.exit(1)
assert all(-x not in sol for x in sol)
except (ValueError, AssertionError):
... | jaanos/LVR-2016 | homework/common/check-janos.py | Python | mit | 1,157 |
from __future__ import absolute_import, print_function, unicode_literals
import json
import contextlib
from ._utils import indent
@contextlib.contextmanager
def formatter(stream):
stream.write("{\n")
yield JSONFormatter(stream)
stream.write("\n}\n")
stream.flush()
class JSONFormatter(object):
... | ouspg/trytls | runners/trytls/formatters/json.py | Python | mit | 1,815 |
"""
calculator.py
General functions that would be in a finacial calculator.
"""
import numpy as np
# Typical Financial Calculator Functions
# ------------------------------------------------------------------------------------------------------------------------------
def future_value(pv=100.0, r=0.07, n=1.0, f=1.0)... | tmthydvnprt/compfipy | compfipy/calculator.py | Python | mit | 2,674 |
import math
tri = [
[ 75 ],
[ 95, 64 ],
[ 17, 47, 82 ],
[ 18, 35, 87, 10 ],
[ 20, 4, 82, 47, 65 ],
[ 19, 1, 23, 75, 3, 34 ],
[ 88, 2, 77, 73, 7, 63, 67 ],
[ 99, 65, 4, 28, 6, 16, 70, 92 ],
[ 41, 41, 26, 56, 83, 40, 80, 70, 33 ],
[ 41, 48, ... | jokkebk/euler | p18.py | Python | mit | 1,040 |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 23 10:11:53 2016
@author: ddboline
flask app for make_queue
"""
from __future__ import (absolute_import, division, print_function, unicode_literals)
from movie_collection_app.movie_queue_flask import run_make_queue_flask
if __name__ == '__main__':... | ddboline/movie_collection_app | make_queue_flask.py | Python | mit | 348 |
#!/usr/bin/env python
#
# Electrum - lightweight Bitcoin client
# Copyright (C) 2013 ecdsa@github
#
# 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 li... | protonn/Electrum-Cash | gui/qt/password_dialog.py | Python | mit | 6,019 |
# coding: utf-8
from flask import Flask, render_template, request, redirect, url_for
from sqlalchemy import Column, Integer, create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from pyuploadcare_sqlalchemy import ImageType
from pyuploadcare import conf
app = ... | uploadcare/pyuploadcare-sqlalchemy | example/main.py | Python | mit | 1,144 |
#!/usr/bin/python3
import threading
import time
class Scale(threading.Thread):
"""This Scale is a debugging tool for use when real scales are unavailable.
Each instance of Scale launches a thread which generates dummy output
and saves that input to an entry in a dict.
Args:
comPort: string; ... | bretter/SpudScale | src/TestScale.py | Python | mit | 1,200 |
from wonderbot import main
if __name__ == '__main__':
from apscheduler.schedulers.blocking import BlockingScheduler
sched = BlockingScheduler()
sched.add_job(main, 'interval', id='wonderbot', seconds=120)
sched.start()
| jmwerner/__WonderBot__ | scheduler.py | Python | mit | 240 |
#!/usr/bin/env python
import sys
import logging
import time
import telepot
import json
import commandmanager
reload(sys).setdefaultencoding('utf-8')
logging.basicConfig(filename='telegramadmin.log')
class TelegramAdmin:
def __init__(self):
self.log = logging.getLogger('telegramadmin')
self.confi... | miciux/telegram-bot-admin | telegramadmin.py | Python | mit | 2,107 |
from .sub_sample_2_1 import (
sub_sample_2_1_now, sub_sample_2_1_sleep,
sub_sample_2_1_time, sub_sample_2_1_today
)
__all__ = [
"sub_sample_2_1_now", "sub_sample_2_1_sleep",
"sub_sample_2_1_time", "sub_sample_2_1_today"
]
| alisaifee/hiro | tests/emulated_modules/sub_module_2/__init__.py | Python | mit | 239 |
import matplotlib.pyplot as plt
import UpDownMethods as ud
def plot_results(results, midpoints=False, figure=None, estimate=False,
reversals=False, runs=True):
if figure is None:
figure = plt.figure()
figure.clf()
figure.add_subplot(111)
plt.hold(True)
# Plot correct r... | codles/UpDownMethods | UpDownMethods/plot.py | Python | mit | 1,966 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
def set_themes(apps, schema_editor):
Theme = apps.get_model("themes", "Theme")
default_theme = Theme.objects.get(is_default=True)
HomePage = apps.get_model('core', 'HomePage')
home, created = Ho... | OpenCanada/website | core/migrations/0020_assign_theme_to_homepage.py | Python | mit | 653 |
#
# mainTab
#
tab = self.notebook.mainTab
tab.settings['Program'] = 'castep'
tab.settings['Output file name'] = 'phonon.castep'
#
# SettingsTab
#
tab = self.notebook.settingsTab
tab.settings['Eckart flag'] = False
tab.settings['Neutral Born charges'] = False
tab.settings['Sigma value'] = 5
tab.settings['Mass definition... | JohnKendrick/PDielec | Examples/Mie/MgO_lognormal/script.py | Python | mit | 2,598 |
from setuptools import setup
setup(name='PyYacht',
version='0.2',
description='Yacht race starter',
url='https://github.com/HUg0005/PyYacht',
author='Hayden Hughes',
author_email='mrhaydenhughes@gmail.com',
license='MIT',
scripts=['bin/PyStart.py'],
zip_safe=Fa... | HUg0005/PyYacht | setup.py | Python | mit | 324 |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2017-10-05 15:37
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('rank', '0005_systemmessage'),
]
operations = [
migrations.AddField(
... | dreardon/leaderboard | rank/migrations/0006_systemmessage_name.py | Python | mit | 499 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright (c) Spyder Project Contributors
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# --------------------------------------------------------------------... | Nodd/spyderplugins.vim | setup.py | Python | mit | 2,136 |
#Finish the solution so that it sorts the passed in array of numbers. If the function passes in an empty array or null/nil value then it should return an empty array.
def solution(nums):
return sorted(nums) if nums else []
#Alternate Solution
def solution(nums):
if not nums:
return []
return sorted... | JLJTECH/TutorialTesting | CodeWars/2016/SortNumbers-7k.py | Python | mit | 326 |
import rethinkdb as r
from tornado import gen
from tornado import ioloop
import random
r.set_loop_type("tornado")
connection = r.connect(host='localhost', port=28015)
| peymanmortazavi/quantifiedSelf | lib/database.py | Python | mit | 168 |
# -*- coding: utf-8 -*-
import datetime
import requests
from pytz import timezone
from django.conf import settings
def get_tz(geoid):
if settings.USE_LOCAL_GEOBASE:
return settings.DB.regionById(int(geoid)).as_dict['tzname']
try:
return requests.get(settings.GEOBASE_API,
... | znick/anytask | anytask/common/timezone.py | Python | mit | 981 |
import sys
import os
brief = "test a model"
aliases = ['m']
def usage(argv0):
print("Usage: {} test model MODEL_NAME|--list|--help".format(argv0))
sys.exit(1)
alias = ['m']
def execute(argv, argv0, engine):
if not argv or '--help' in argv:
usage(argv0)
os.environ["AIOWEB_ENV"] = "test"
... | kreopt/aioweb | wyrm/modules/test/model.py | Python | mit | 1,012 |
import mock
import subprocess
from linkins import script
from linkins.test import util
@mock.patch('multiprocessing.Process')
@mock.patch('linkins.script.log')
@mock.patch('subprocess.Popen')
def test_runscript_simple(fakepopen, fakelog, fakeprocess):
proc = fakepopen.return_value
poll = proc.poll
poll.r... | thelinuxkid/linkins | linkins/test/test_script.py | Python | mit | 4,969 |
#!/usr/bin/env python
""" Assignment 1, Exercise 3, INF1340, Fall, 2015. Troubleshooting Car Issues.
This module contains one function diagnose_car(). It is an expert system to
interactive diagnose car issues.
"""
__author__ = 'Susan Sim'
__email__ = "ses@drsusansim.org"
__copyright__ = "2015 Susan Sim"
__license__... | susanshen/inf1340_2015_asst1 | exercise3.py | Python | mit | 3,239 |
from django.contrib import admin
from Stations.models import Station, Sensor
class StationAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('name',)}
class SensorAdmin(admin.ModelAdmin):
repopulated_fields = {
'slug': ('sensor_type', 'height',),
}
# Register your models here.... | sschultz/FHSU-GSCI-Weather | Stations/admin.py | Python | mit | 405 |
class DatabaseConnection(object):
HOST = 'databaseurl.com'
PORT = '5432'
USERNAME = 'test_user'
| jjensenmike/python | import_constants/config.py | Python | mit | 108 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri May 19 12:32:10 2017
@author: wd
"""
import math
import tensorflow as tf
import numpy as np
cnn = np.load('/home/wd/Workspace/RL/dqn_cnn.npy')
# w3, w4, cnn,
class DQN:
def __init__(self, sess, weight, w1, w2, w3, cnn_eye, bias, input_size,... | blackpigg/RL_landmark_finder | PG_value.py | Python | mit | 5,462 |
"""
pgoapi - Pokemon Go API
Copyright (c) 2016 tjado <https://github.com/tejado>
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... | superfsm/pgoapi | pgoapi/__init__.py | Python | mit | 2,311 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import logging
__author__ = 'tchen'
logger = logging.getLogger(__name__)
from django.contrib.sites.models import Site
def site(request):
import karp
return {
'site': Site.objects.get_current(),
'version': karp.__version__,
}... | tyrchen/karp | karp/context_processors.py | Python | mit | 321 |
from unittest import TestCase
from tests.assertions import CustomAssertions
import numpy as np
from floq.helpers.matrix import is_unitary, adjoint, gram_schmidt, norm, product
class TestIsUnitary(TestCase):
def test_true_if_unitary(self):
u = np.array([[-0.288822 - 0.154483j, 0.20768 - 0.22441j, 0.094903... | sirmarcel/floq | tests/helpers/test_matrix.py | Python | mit | 3,297 |
from django.db import models
import hashlib
import time
import sys
def _createHash():
hash = hashlib.sha1()
hash.update(str(time.time()).encode('utf-8'))
return hash.hexdigest()[:-10]
class Session(models.Model):
data = models.CharField(max_length=sys.maxsize)
hash = models.CharField(max_length=... | martynvandijke/Stargazer | stargazer/simulator/models.py | Python | mit | 355 |
import numpy as np
import pdb
from scipy.special import digamma
import logging
iter_num = 5
np.seterr(over='raise')
def exp_proportion(theta):
exp_theta = np.exp(theta)
return exp_theta / np.sum(exp_theta)
def update_variables(X, theta_1, theta_2, q_z, beta, labels, lbda, rho, u, it):
DOC_NUM, VOCAB_SIZ... | wenchaodudu/SNLDA | lda.py | Python | mit | 5,422 |
"""
High-level fitting and plotting example with MulensModel.
Requires in-line argument which is a config file, e.g.,
example_15_mb07192_v1.cfg or example_15_ob05390_v1.cfg.
"""
import os
import sys
import numpy as np
import emcee
from matplotlib import pyplot as plt
import configparser
import MulensModel as mm
impo... | rpoleski/MulensModel | examples/example_15_fitting.py | Python | mit | 5,757 |
#!/usr/bin/env python
sx=0
sy=0
rx=0
ry=0
total = 2
houses = set()
houses.add( (0,0) ) # starting point
with open("../input/03.txt") as fileobj:
for word in fileobj:
for ch in word:
total+=1
if total % 2 == 0: # santa
if ch == '^':
sx+=1
if ch == 'v':
sx-=1
if ch == '<':
sy-=1
... | dsumike/adventofcode | python/03p2.py | Python | mit | 628 |
import os
import sys
import glob
import datetime
import erppeek
import xmlrpclib
from fabric.api import task, hosts
from fabric.api import local, env, prompt, execute, lcd, run, put
from fabric.context_managers import quiet
from fabric import colors
# see: http://fabric.readthedocs.org/en/1.8/usage/execution.html#lev... | nexiles/odoo.wochenbericht | fabfile.py | Python | mit | 4,380 |
# -*- coding: utf-8 -*-
from datetime import datetime
from django.contrib.auth.models import User
from django.core.cache import cache
from useractivity.utils import get_online_users
def online_users(request):
"""Returns context variable with a set of users online."""
if request.user.is_authenticated():
... | turian/django-instantmessage | pinax-im-dist/apps/useractivity/context_processors.py | Python | mit | 380 |
"""Test of v0x04 queue module."""
from pyof.v0x04.common.queue import (
PacketQueue, QueuePropExperimenter, QueuePropHeader, QueuePropMaxRate,
QueuePropMinRate)
from tests.unit.test_struct import TestStruct
class TestPacketQueue(TestStruct):
"""Packet Queue structure tests (also those in :class:`.TestDump... | kytos/python-openflow | tests/unit/v0x04/test_common/test_queue.py | Python | mit | 2,327 |
# -*- coding: utf-8 -*-
# Copyright 2016 Christoph Reiter
#
# 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... | quodlibet/senf | examples/ls.py | Python | mit | 1,435 |
mess = """
%%$@_$^__#)^)&!_+]!*@&^}@[@%]()%+$&[(_@%+%$*^@$^!+]!&_#)_*}{}}!}_]$[%}@[{_@#_^{*
@##&{#&{&)*%(]{{([*}@[@&]+!!*{)!}{%+{))])[!^})+)$]#{*+^((@^@}$[**$&^{$!@#$%)!@(&
+^!{%_$&@^!}$_${)$_#)!({@!)(^}!*^&!$%_&&}&_#&@{)]{+)%*{&*%*&@%$+]!*__(#!*){%&@++
!_)^$&&%#+)}!@!)&^}**#!_$([$!$}#*^}$+&#[{*{}{((#$]{[$[$$()_#}!@}^@... | feliposz/python-challenge-solutions | level2-histogram.py | Python | mit | 98,947 |
#!/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.
# Download and build the data if it does not exist.
import parlai.core.build_data as build_data
import gzip
import os
im... | facebookresearch/ParlAI | parlai/tasks/opensubtitles/build_2009.py | Python | mit | 4,199 |
# coding: utf-8
"""
ORCID Member
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501
OpenAPI spec version: Latest
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import si... | Royal-Society-of-New-Zealand/NZ-ORCID-Hub | orcid_api_v3/models/history_v30.py | Python | mit | 10,411 |
#!/usr/bin/env python
# -*- coding:utf-8 -*
import datetime
import requests
import re
import simplejson as json
class OWS(object):
def __init__(self):
super(OWS, self).__init__()
def calendar(self):
today = datetime.date.today()
imgUrl = 'http://img.owspace.com/Public/uploads/Downloa... | caspartse/mylittlebot | owsbot.py | Python | mit | 1,734 |
# -*- coding: utf-8 -*-
import re
import os
import subprocess
# Regular expression used to match Python files
pyfile = re.compile('.py$')
# List of allowed example to fail
allowed_errors = (
'simulated_error.py'
)
def test_examples():
# List of file examples
examples = [f for f in os.listdir('examples'... | h2non/pook | tests/integration/examples_test.py | Python | mit | 631 |
# -*- coding:utf-8 -*-
#20161029
import urllib
import urllib2
from bs4 import BeautifulSoup
import re
import os
#要爬取的网址
url = 'http://tieba.baidu.com/p/2511853162?pn=%s'
headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.97 Safari/537.36'}
#爬取网... | nanhuayu/hello-world | Python/WebCrawler/readforum/tieba.py | Python | mit | 1,185 |
#!/usr/bin/env python3
# This is just a PoC, and it comes with no warranty or anything.
# Use it at your own risk. it MUST NOT be used in a production environment or anything other than testing.
# PLEASE respect other people's privacy. Only tested on Linux BTW
import asyncio
import os
from socket import AF_INET, SO_R... | mosajjal/ircbackdoor | main_asyncio.py | Python | mit | 3,169 |
from flask import Flask
from argparse import ArgumentParser
app = Flask(__name__, static_folder='static')
from server import start
from route import initialize
def main():
argparser = ArgumentParser()
argparser.add_argument('-P', '--port', default=8080, type=int)
argparser.add_argument('-H', '--host', def... | vasumv/pokemon_ai | pokemonitor/__init__.py | Python | mit | 441 |
from .ujson import decode, encode, dump, dumps, load, loads # noqa: F401
| explosion/srsly | srsly/ujson/__init__.py | Python | mit | 74 |
"""
Premium Question
"""
import sys
__author__ = 'Daniel'
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def closestValue(self, root, target):
"""
Divide the problem into 2 parts:
1. find... | algorhythms/LeetCode | 270 Closest Binary Search Tree Value.py | Python | mit | 1,307 |
from interactive import InteractiveModule, UserModule
from viewer import ViewerConstants
from screen import Screen
from viewport import Viewport
from state import State
from colon_line import ColonLine
from text_box import TextBox
import log
log = log.logger
class PC(InteractiveModule, UserModule):
def __init__(s... | jghibiki/Cursed | terminal/pc.py | Python | mit | 3,187 |
#coding: utf-8
import requests
import json
import sys
import datetime
import os
from contextlib import closing
def all_sample_code():
'''
library.json来源于https://developer.apple.com/library/content/navigation/library.json
"columns": { "name" : 0,
"id" : 1,
"type" : 2... | LeoXu92/AppleSampleSpider | AppleSampleSpider.py | Python | mit | 1,999 |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
def chunked(fh, size):
'''
Chunks a file handle into block of the given size
'''
while True:
data = fh.read(size)
if data == "":
return
yield data
| Saevon/Recipes | python/chunked.py | Python | mit | 248 |
#!/usr/bin/env python
from __future__ import division
import copy
import threading
from subprocess import Popen
import time
import os
import sys
import numpy as np
import cv2
from cv_bridge import CvBridge, CvBridgeError
import matplotlib.pyplot as plt
import rospy
import rosparam
from sensor_msgs.msg import Image
f... | tom-f-oconnell/multi_tracker | nodes/delta_video_simplebuffer.py | Python | mit | 25,393 |
# encoding: utf-8
import csv
from datetime import date
import datetime
from collections import defaultdict
class ManipulateCSVFile:
# Add filepaths!
def __init__(self):
self.lecture = '/home/aleksanderhh/Downloads/Database/Lectures.csv'
self.lectureFixed = '/home/aleksanderhh/Downloads/... | henrikbossart/courseTracker | server_scripts/Scraper/manipulateCSV.py | Python | mit | 7,046 |
#!/usr/bin/python
import rospy
import rospkg
import os
from std_msgs.msg import String
from trajectory_analysis_gui.srv import *
from ms_face_api.srv import *
from ms_face_api.msg import *
from sensor_msgs.msg import Image
from cv_bridge import CvBridge, CvBridgeError
import glob
import os
import cv2
import json
... | strands-project/aaf_deployment | face_analysis/scripts/opencv_tools.py | Python | mit | 12,514 |
# MySQL Connector/Python - MySQL driver written in Python.
# Copyright (c) 2014, 2015, Oracle and/or its affiliates. All rights reserved.
# MySQL Connector/Python is licensed under the terms of the GPLv2
# <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most
# MySQL Connectors. There are special exceptio... | LuciferJack/python-mysql-pool | PyMysqlPool/mysql/connector/authentication.py | Python | mit | 6,479 |
from ..Qt import QtGui, QtCore, QtWidgets
from ..GraphicsScene import GraphicsScene
from .GraphicsItem import GraphicsItem
__all__ = ['GraphicsWidget']
class GraphicsWidget(GraphicsItem, QtWidgets.QGraphicsWidget):
_qtBaseClass = QtWidgets.QGraphicsWidget
def __init__(self, *args, **kargs):
"""
... | mylxiaoyi/mypyqtgraph-qt5 | pyqtgraph/graphicsItems/GraphicsWidget.py | Python | mit | 2,172 |
# -*- coding: utf-8 -*-
"""
traceview.discovery
This module contains the objects associated with Discovery API resources.
http://dev.appneta.com/docs/api-v2/discovery.html
"""
from .resource import Resource
class Action(Resource):
def get(self):
return self.api.get('actions')
class Browser(Resourc... | danriti/python-traceview | traceview/discovery.py | Python | mit | 896 |
# pylint: disable=missing-docstring,blacklisted-name,invalid-name,not-callable
dependency = None
foo = None
bar = None
def do_work_using_import_module():
dependency.foo()
dependency.bar()
def do_work_using_from_import():
foo()
bar()
| whyzdev/impject | tpkg/production_no_import.py | Python | mit | 253 |
"""
Based on
https://github.com/jupyter/notebook/blob/master/notebook/static/services/kernels/comm.js
https://github.com/ipython/ipykernel/blob/master/ipykernel/comm/manager.py
https://github.com/ipython/ipykernel/blob/master/ipykernel/comm/comm.py
Which are distributed under the terms of the Modified BSD License.
""... | sserrot/champion_relationships | venv/Lib/site-packages/qtconsole/comms.py | Python | mit | 8,976 |
# coding=utf-8
import datetime
import logging
import re
from lxml import etree
from lxml import html
import requests
import requests.utils
import ziniurrss.cache
import ziniurrss.feed
import ziniurrss.parallel
log = logging.getLogger(__name__)
def get_remote_content(url):
log.debug('Getting [%s].' % url)
u... | tori3852/ziniurrss | src/ziniurrss/main.py | Python | mit | 6,120 |
# 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 ... | Azure/azure-sdk-for-python | sdk/graphrbac/azure-graphrbac/azure/graphrbac/models/group_get_member_groups_parameters_py3.py | Python | mit | 1,627 |
import pytest
import vcr
from six.moves.urllib.request import urlopen
def test_making_extra_request_raises_exception(tmpdir, httpbin):
# make two requests in the first request that are considered
# identical (since the match is based on method)
with vcr.use_cassette(str(tmpdir.join("test.json")), match_on... | Azure/azure-sdk-for-python | tools/vcrpy/tests/integration/test_multiple.py | Python | mit | 886 |
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
import os
import unittest
from monty.serialization import dumpfn, loadfn
from pymatgen.core.structure import Molecule
from pymatgen.io.qchem.outputs import QCOutput, check_for_structure_changes
from pymatgen.util.testing im... | materialsproject/pymatgen | pymatgen/io/qchem/tests/test_outputs.py | Python | mit | 12,614 |
# Generated by Django 2.0.4 on 2018-04-23 18:09
import django.contrib.auth.models
import django.contrib.auth.validators
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0009_alter_user_last_name_ma... | snicoper/django-boilerplate | src/apps/accounts/migrations/0001_initial.py | Python | mit | 3,042 |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.3 on 2017-06-30 12:30
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('features', '0009_merge_20170613_1205'),
]
operations = [
migrations.AddFiel... | KDD-OpenSource/fexum | features/migrations/0010_calculation_features.py | Python | mit | 484 |
## Coursera_Downloader
## MIT License, 2014 Gurjot S. Sidhu
## Runs on Python 3.x using the urllib module
import time
import urllib.request as urr
import os
from shutil import copyfileobj
# Enter the link to the directory where you want the downloaded files to be saved
download_directory = "/home/user/Lectures"
# E... | gsidhu/Coursera_Downloader | downloader_v3x.py | Python | mit | 1,939 |
# encoding: UTF-8
from __future__ import print_function
__author__ = 'CHENXY'
from string import join
from xtp_struct_quote import structDict
from xtp_struct_common import structDict as structDict2
structDict.update(structDict2)
#----------------------------------------------------------------------
def replaceTabs... | rrrrrr8/vnpy | vnpy/api/xtp/pyscript/generate_md_functions.py | Python | mit | 12,218 |
#!/usr/bin/env python
import os, sys, re, csv,subprocess
def sharpen_image(img, destdir=None):
import subprocess,re,os,sys
regex_coded = re.compile(r'^.+?/[1-9][0-9]{8}_[1-6]\.jpg$')
regex_alt = re.compile(r'^.+?/[1-9][0-9]{8}_\w+?0[1-6]\.[JjPpNnGg]{3}$')
regex_valid_style = re.compile(r'^.+?/[1-9][0-9... | relic7/prodimages | python/do_sharpen_only_img.py | Python | mit | 1,816 |
import os
import base64
from sqlite3 import dbapi2 as sqlite3
from flask import Flask, request, session, g, redirect, url_for, abort, \
render_template, flash
current_location = os.path.dirname(os.path.realpath(__file__))+'/'
app = Flask(__name__)
# Load default config and override config from an environment va... | almlab/microbiome-tracker | src/serve.py | Python | mit | 6,821 |
#!/usr/bin/env python
import os
import shutil
import datetime
from pathlib import Path
PROJECT_DIRECTORY = os.path.realpath(os.path.curdir)
def remove_file(filepath):
f = Path(PROJECT_DIRECTORY) / filepath
if f.is_dir():
shutil.rmtree(str(f))
else:
f.unlink()
def replace_contents(filena... | nicfit/nicfit.py | cookiecutter/hooks/post_gen_project.py | Python | mit | 3,552 |
# -*- coding: utf-8 -*-
"""Logging functions."""
#
# (C) Pywikibot team, 2010-2020
#
# Distributed under the terms of the MIT license.
#
from __future__ import absolute_import, division, unicode_literals
import logging
import os
import sys
# logging levels
from logging import DEBUG, INFO, WARNING, ERROR, CRITICAL, St... | PersianWikipedia/pywikibot-core | pywikibot/logging.py | Python | mit | 7,378 |
from shopify.utils import shop_url
from test.test_helper import TestCase
class TestSanitizeShopDomain(TestCase):
def test_returns_hostname_for_good_shop_domains(self):
good_shop_domains = [
"my-shop",
"my-shop.myshopify.com",
"http://my-shop.myshopify.com",
... | Shopify/shopify_python_api | test/utils/shop_url_test.py | Python | mit | 1,736 |
from tovendendo.users.forms import LoginForm, RegistrationForm
from werkzeug.datastructures import MultiDict
import pytest
def test_allows_login_with_valid_data(user):
data = MultiDict({'email': 'user@email.com', 'password': 'pas'})
form = LoginForm(data)
assert form.validate()
@pytest.mark.parametrize... | anapaulagomes/to-vendendo | tests/users/test_form.py | Python | mit | 2,003 |
#!/usr/bin/env python
"""
ar_follower.py - Version 1.0 2013-08-25
Follow an AR tag published on the /ar_pose_marker topic. The /ar_pose_marker topic
is published by the ar_track_alvar package
Created for the Pi Robot Project: http://www.pirobot.org
Copyright (c) 2013 Patrick Goebel. All... | fujy/ROS-Project | src/rbx2/rbx2_ar_tags/nodes/ar_follower.py | Python | mit | 5,999 |
from Bio.Phylo.Applications import PhymlCommandline
import sys
from OrthoEvol.Tools.logit import LogIt
class PhyML(object):
"""The PhyML class uses Biopython's PhyMLCommandline wrapper to generate trees
from the PhyML executable."""
def __init__(self, phyml_input, datatype='aa'):
"""R... | datasnakes/Datasnakes-Scripts | OrthoEvol/Orthologs/Phylogenetics/PhyML/orthophyml.py | Python | mit | 1,577 |
# -*- coding: utf-8 -*-
"""
Defines views.
"""
import calendar
from flask import redirect, render_template, url_for, make_response, abort
from jinja2 import TemplateNotFound
from presence_analyzer.main import app
from presence_analyzer.utils import (jsonify, get_data, mean,
group_... | aadamski/presence-analyzer-aadamski | src/presence_analyzer/views.py | Python | mit | 3,013 |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-05-05 20:31
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Catego... | pratyaymodi/kickstarter | kickstarter_django/kickstarter/migrations/0001_initial.py | Python | mit | 11,349 |
import _plotly_utils.basevalidators
class CustomdataValidator(_plotly_utils.basevalidators.DataArrayValidator):
def __init__(
self, plotly_name="customdata", parent_name="choroplethmapbox", **kwargs
):
super(CustomdataValidator, self).__init__(
plotly_name=plotly_name,
... | plotly/python-api | packages/python/plotly/plotly/validators/choroplethmapbox/_customdata.py | Python | mit | 476 |
import pytest
from utils.page_model import TestResultPage
from utils.config import config
from tests.common import generate_test_url
UNALLOWED_PORT = config['server_port'] + 1
SAME_ORIGIN = 'http://' + config['server_address'] + ':' + str(config['server_port'])
DIFFERENT_ORIGIN = 'http://' + config['server_address'] ... | ilyanesterov/browser-csp-compatibility | tests/frame-ancestors/test_frame_ancestors_iframe.py | Python | mit | 1,775 |
class Stackoverflow:
def __init__(self):
self.post_texts = []
self.post_ratings = []
# use this method to grab all the information from the page and return
# a tuple (Question, Answers[], Ratings[])
def analyze_page(self, page, search):
try:
post_tags = page.soup.f... | Draps-/Nani | nani/interfaces/stackoverflow_interface.py | Python | mit | 750 |
import socket
import time
import numpy as np
import struct
from pathlib import Path
try:
import h5py
except ImportError:
h5py = None
from . import NPKT
def udpunicast(
host: str,
port: int,
h5fn: Path = None,
Nupdate: int = 1000,
bufsize: int = 8192,
Nelbyte: int = 4,
N: int = NP... | scivision/python_c_sockets | python_c_sockets/hdf.py | Python | mit | 3,302 |
from __future__ import absolute_import
import time
import itertools
from celery import shared_task
import irsignal
@shared_task
def press_remote_buttons(devices_and_buttons_and_timeouts):
for device, button, timeout_in_s in grouper(
devices_and_buttons_and_timeouts, 3, 0):
irsignal.press_butt... | luke-moore/house | django/house/tasks.py | Python | mit | 717 |
# -*- coding: utf-8 -*-
# Scrapy settings for browser_simulator project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
# http://doc.scrapy.org/en/latest/topics/settings.html
# http://scrapy.readthedocs.org... | skihyy/GT-Spring-2017-CS6262 | browser_simulator/browser_simulator/settings.py | Python | mit | 3,334 |
from datetime import datetime
from argparse import ArgumentParser
import os
import sys
"""
Script to resume/open recently used files in a directory
"""
def get_recent_files(folder, file_filter, limit):
files = [os.path.join(folder, f) for f in os.listdir(folder)]
if file_filter:
files = list(fil... | harshays/scripts | resume/resume.py | Python | mit | 1,687 |
import base64
import os
from django.db import models
from django.conf import settings
from twython import Twython
class TwitterProfile(models.Model):
def __unicode__(self):
return self.username
def save(self, *args, **kwargs):
if not self.pk:
twitter = Twython(
settings.TWITTER_APP_KEY,
settings.T... | dylanbfox/simple-django-twitter-auth | django_twitter_auth/models.py | Python | mit | 1,507 |
from waitress import wasyncore as asyncore
from waitress import compat
import contextlib
import functools
import gc
import unittest
import select
import os
import socket
import sys
import time
import errno
import re
import struct
import threading
import warnings
from io import BytesIO
TIMEOUT = 3
HAS_UNIX_SOCKETS = h... | ianastewart/cwltc-admin | venv/Lib/site-packages/waitress/tests/test_wasyncore.py | Python | mit | 54,410 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from flask import Flask
from flask.ext.migrate import Migrate, MigrateCommand
from flask.ext.script import Manager
from flask_user import UserManager, SQLAlchemyAdapter
f... | timmartin19/browser-REST-builder | rest_builder/app.py | Python | mit | 1,334 |
import time
import datetime
import threading
from django.apps import AppConfig
from django_eventstream import send_event
class TimeappConfig(AppConfig):
name = 'timeapp'
def ready(self):
ensure_worker_started()
worker_started = False
def ensure_worker_started():
global worker_started
if ... | fanout/django-eventstream | examples/time/timeapp/apps.py | Python | mit | 926 |
# -*- coding: utf-8 -*-
import unittest
import re
from gtts.tokenizer.core import RegexBuilder, PreProcessorRegex, PreProcessorSub, Tokenizer
# Tests based on classes usage examples
# See class documentation for details
class TestRegexBuilder(unittest.TestCase):
def test_regexbuilder(self):
rb = RegexBui... | pndurette/gTTS | gtts/tokenizer/tests/test_core.py | Python | mit | 2,202 |
import json
import requests
from core.models import Client, Driver
from core.serializers import ClientSerializer
from django.conf import settings
from django.db import models
from django.utils import timezone
from pyfcm import FCMNotification
PUSH_SERVICE = FCMNotification(api_key=settings.FIREBASE_DRIVER_KEY)
clas... | cmpe-295/project-backend | safe_ride/ride/models.py | Python | mit | 6,027 |
def ninja_io(args):
"""Return the inputs/outputs as a single string
Args:
args (str | list): a string or list of strings
Returns:
a string
"""
if isinstance(args, list):
return " ".join(list(map(str, args)))
else:
return str(args)
| yuhangwang/ninjag-python | ninjag/core/ninja_io.py | Python | mit | 288 |
"""
This bootstrap module contains code for ensuring that the astropy_helpers
package will be importable by the time the setup.py script runs. It also
includes some workarounds to ensure that a recent-enough version of setuptools
is being used for the installation.
This module should be the first thing imported in th... | adrn/SFD | ah_bootstrap.py | Python | mit | 36,850 |
# -*- coding: utf-8 -*-
"""
Created on 2017-8-8
@author: cheng.li
"""
import unittest
import numpy as np
import pandas as pd
from alphamind.data.rank import rank
class TestRank(unittest.TestCase):
def setUp(self):
self.x = np.random.randn(1000, 1)
self.groups = np.random.randint(0, 10, 1000)
... | wegamekinglc/alpha-mind | alphamind/tests/data/test_rank.py | Python | mit | 1,317 |
# -*- coding: utf-8 -*-
# Copyright (c) 2010 matt
# Copyright (c) 2010 Dieter Plaetinck
# Copyright (c) 2010, 2012 roger
# Copyright (c) 2011-2012 Florian Mounier
# Copyright (c) 2011 Mounier Florian
# Copyright (c) 2011 Timo Schmiade
# Copyright (c) 2012 Mikkel Oscar Lyderik
# Copyright (c) 2012, 2014 Tycho Andersen
#... | dequis/qtile | libqtile/widget/mpdwidget.py | Python | mit | 11,020 |
import win32com,win32com.client
def ad_dict(ldap_path,value_required=1):
attr_dict={}
adobj=win32com.client.GetObject(ldap_path)
schema_obj=win32com.client.GetObject(adobj.schema)
for i in schema_obj.MandatoryProperties:
value=getattr(adobj,i)
if value_required and value==None: continue
attr_... | ActiveState/code | recipes/Python/303348_Get_attributes_object_MS_Active/recipe-303348.py | Python | mit | 575 |
import unittest
from copernicus import Event
__author__ = 'gronostaj'
class EventTests(unittest.TestCase):
event = Event('test', '0101____')
def test_should_extract_argument_correctly(self):
min_ = EventTests.event.extract_arg('01010000')
max_ = EventTests.event.extract_arg('01011111')
... | gronostajo/copernicus-api | tests/testEvent.py | Python | mit | 921 |
# Generated by Django 2.2.24 on 2021-06-16 18:46
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('assays', '0047'),
]
operations = [
migrations.AlterField(
mod... | UPDDI/mps-database-server | assays/migrations/0048.py | Python | mit | 35,620 |
#! /usr/bin/env python
"""
Module with HCIDataset and HCIFrame classes.
"""
__author__ = 'Carlos Alberto Gomez Gonzalez'
__all__ = ['Dataset',
'Frame']
import numpy as np
import copy
import hciplot as hp
from .fits import open_fits
from .fm import (cube_inject_companions, generate_cube_copies_with_injecti... | vortex-exoplanet/VIP | vip_hci/hci_dataset.py | Python | mit | 55,139 |
import base64
import httplib2
import logging
import mimetypes
import mimetools
import urllib
import urlparse
HTTP_STATUS_OK = '200'
logger = logging.getLogger(__name__)
class RestClient(object):
content_type = None
def __init__(self, base_url, username=None, password=None,
connection_class... | nowells/python-wellrested | wellrested/connections/__init__.py | Python | mit | 6,125 |
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "frigg.settings")
from django.core.wsgi import get_wsgi_application # noqa # isort:skip
application = get_wsgi_application()
| frigg/frigg-hq | frigg/wsgi.py | Python | mit | 187 |