code stringlengths 6 947k | repo_name stringlengths 5 100 | path stringlengths 4 226 | language stringclasses 1
value | license stringclasses 15
values | size int64 6 947k |
|---|---|---|---|---|---|
from datetime import datetime
from parsedatetime import parsedatetime, Constants
from scrapy import signals
from scrapy.xlib.pydispatch import dispatcher
from scrapy.exceptions import NotConfigured, IgnoreRequest
from scrapy.utils.misc import load_object
class HistoryMiddleware(object):
DATE_FORMAT = '%Y%m%d'
... | playandbuild/scrapy-history-middleware | history/middleware.py | Python | mit | 3,854 |
import unittest
from contented.app import Application
class AppTests(unittest.TestCase):
def test_load_app(self):
app = Application({})
self.assertTrue(hasattr(app, "settings"))
self.assertTrue(hasattr(app, "content_map"))
self.assertTrue(hasattr(app, "request_processors")) | elbeanio/contented | test/app.py | Python | mit | 312 |
# -*- coding: utf-8 -*-
import pathlib
from typing import Union
import lxml.etree
def save_as_xml(
element_tree: Union[lxml.etree._Element, lxml.etree._ElementTree],
filepath: Union[str, pathlib.Path],
pretty_print: bool = True) -> None:
"""save ElementTree in the file as XML... | 085astatine/togetter | togetter/xml_tools.py | Python | mit | 972 |
# coding=UTF-8
import mysql.connector
import xlrd
import xlsxwriter
import os
from mysql.connector import errorcode
from datetime import datetime
# 符号化后的 Excel 文件名
EXCEL_NAME = '20170223_4.0.1_feedback_result_py'
DB_NAME = 'zl_crash'
config = {
'user': 'root',
'password': '123456',
'host': '127.0.0.1',
... | renguochao/PySymTool | py_group.py | Python | mit | 8,872 |
from ._excel import ExcelXlsTableWriter, ExcelXlsxTableWriter
from ._pandas import PandasDataFramePickleWriter
from ._sqlite import SqliteTableWriter
| thombashi/pytablewriter | pytablewriter/writer/binary/__init__.py | Python | mit | 150 |
import cookielib
import urllib2
import urllib
import json
import time
#Default Settings for a system to keep cookies, please add it before testing
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
urllib2.install_opener(opener)
# Let the single cookie system override the current... | lanking520/Digital_China | backup1.py | Python | mit | 22,145 |
# -*- coding: utf-8 -*-
from .httpclient import HTTPClient
from .models import Video, Show
__all__ = ['Funimation']
class Funimation(object):
def __init__(self):
super(Funimation, self).__init__()
self.http = HTTPClient('http://www.funimation.com/',
[('User-Agent'... | ABusers/A-Certain-Magical-API | funimation/api.py | Python | mit | 3,784 |
#!/usr/bin/python -tt
from behave import *
import os
import subprocess
import glob
import re
import shutil
DNF_FLAGS = ['-y', '--disablerepo=*', '--nogpgcheck']
RPM_INSTALL_FLAGS = ['-Uvh']
RPM_ERASE_FLAGS = ['-e']
def _left_decorator(item):
""" Removed packages """
return u'-' + item
def _right_decorator... | j-mracek/dnf_docker_test | features/steps/test_behave.py | Python | mit | 9,384 |
from __future__ import unicode_literals
# Django
from django.conf import settings
from django.db import models
# 3rd Party
from grapevine import generics
from grapevine.models.base import GrapevineModel
from model_utils.managers import PassThroughManager
# Local Apps
from .querysets import WelcomeEmailQuerySet
cla... | craiglabenz/django-grapevine | tests/core/models.py | Python | mit | 1,420 |
# coding: utf-8
# Author: Vova Zaytsev <zaytsev@usc.edu>
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "nlcd.settings")
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
| LucidAi/nlcd | nlcd/wsgi.py | Python | mit | 221 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# This file is part of fish-bundles.
# https://github.com/fish-bundles/fb
# Licensed under the MIT license:
# http://www.opensource.org/licenses/MIT-license
# Copyright (c) 2014 Bernardo Heynemann heynemann@gmail.com
from fish_bundles.version import __version__
| fish-bundles/fb | fish_bundles/__init__.py | Python | mit | 307 |
# import the libraries that you need
import requests
import csv
# make a GET request to the OneSearch X-Service API
response = requests.get('http://onesearch.cuny.edu/PrimoWebServices'
'/xservice/search/brief?'
'&institution=KB'
'&query=any,contai... | MarkEEaton/api-workshop | 4-json-to-csv.py | Python | mit | 1,093 |
"""
This is pure Python implementation of comb sort algorithm.
Comb sort is a relatively simple sorting algorithm originally designed by Wlodzimierz
Dobosiewicz in 1980. It was rediscovered by Stephen Lacey and Richard Box in 1991.
Comb sort improves on bubble sort algorithm.
In bubble sort, distance (or gap) between ... | TheAlgorithms/Python | sorts/comb_sort.py | Python | mit | 1,851 |
# -*- coding: utf-8 -*-
from django.forms import widgets
from django.template.loader import render_to_string
from django.utils.translation import gettext_lazy as _
from .conf import settings
class PlacesWidget(widgets.MultiWidget):
template_name = 'places/widgets/places.html'
def __init__(self, attrs=None)... | oscarmcm/django-places | places/widgets.py | Python | mit | 1,789 |
from django.shortcuts import render, HttpResponseRedirect, redirect
from django.contrib.auth.decorators import login_required
from django.views.generic.edit import CreateView
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from django.forms.models import inlineformset_... | MrCrawdaddy/humans | profiles/views.py | Python | mit | 2,056 |
#!/usr/bin/env python
import sct_utils as sct
import os
#path = '/Users/benjamindeleener/data/data_testing/C2-T2/'
contrast = 't2'
#path_output_seg = '/Users/benjamindeleener/data/spinal_cord_segmentation_data/training/labels/'
#path_output_im = '/Users/benjamindeleener/data/spinal_cord_segmentation_data/training/dat... | 3324fr/spinalcordtoolbox | dev/generate_ml_data.py | Python | mit | 2,063 |
"""This example samples from a simple bivariate normal distribution."""
import jass.mcmc as mcmc
import jass.samplers as samplers
import numpy as np
import scipy.stats as stats
import triangle
import matplotlib.pyplot as pl
# Define the log-likelihood function to be a bivariate normal
normal_rv = stats.multivariate_n... | ebnn/jass | examples/normal.py | Python | mit | 563 |
from difflib import get_close_matches
import os
from pathlib import Path
def _safe(fn, fallback):
try:
return fn()
except OSError:
return fallback
def _get_all_bins():
return [exe.name
for path in os.environ.get('PATH', '').split(':')
for exe in _safe(lambda: list... | dionyziz/thefuck | thefuck/rules/no_command.py | Python | mit | 848 |
# -*- coding: utf-8 -*-
"""
test
~~~~
Flask-CORS is a simple extension to Flask allowing you to support cross
origin resource sharing (CORS) using a simple decorator.
:copyright: (c) 2014 by Cory Dolphin.
:license: MIT, see LICENSE for more details.
"""
from tests.base_test import FlaskCorsTes... | hoyjustin/ScopusAdapter | CorsTests/test_app_extension.py | Python | mit | 9,998 |
import os, sys
import datetime
import iris
import iris.unit as unit
import iris.analysis.cartography
import numpy as np
from iris.coord_categorisation import add_categorised_coord
diag = 'avg.5216'
cube_name_explicit='stratiform_rainfall_rate'
cube_name_param='convective_rainfall_rate'
pp_file_path='/projects/casc... | peterwilletts24/Monsoon-Python-Scripts | rain/land_sea_diurnal/rain_mask_save_lat_lon_west_southern_indian_ocean.py | Python | mit | 7,070 |
# Tic Tac Toe
# Tic Tac Toe
import random
def drawBoard(board):
# This function prints out the board that it was passed.
# "board" is a list of 10 strings representing the board (ignore index 0)
print(' | |')
print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9])
print(' | |')
p... | pathway27/games-prac | python3/tictactoe.py | Python | mit | 6,138 |
#!/usr/bin/python
"""
@file async_multicast.py
@author Woong Gyu La a.k.a Chris. <juhgiyo@gmail.com>
<http://github.com/juhgiyo/pyserver>
@date March 10, 2016
@brief AsyncMulticast Interface
@version 0.1
@section LICENSE
The MIT License (MIT)
Copyright (c) 2016 Woong Gyu La <juhgiyo@gmail.com>
Permission is... | juhgiyo/pyserver3 | pyserver/network/async_multicast.py | Python | mit | 8,329 |
"""
Author: Lloyd Moore <lloyd@workharderplayharder.com>
Usage:
print perm("01", 2)
> ["00", "01", "10", "11"]
print perm("abcd", 2)
> [ 'aa', 'ab', 'ac', 'ad',
'ba', 'bb', 'bc', 'bd',
'ca', 'cb', 'cc', 'cd',
'da', 'db', 'dc', 'dd' ]
"""
def perm(chars, m, wrd="", wrds=[]):
if len(wrd) == m: return... | ActiveState/code | recipes/Python/577031_Simple_Permutations/recipe-577031.py | Python | mit | 464 |
"""gui systems to manage actions
"""
import os
from sftoolbox.content import ActionContent, PanelContent
from sftoolboxqt import qtgui, qtcore
from sftoolboxqt.tree import PanelsModel, PanelsTreeWidget
class ActionsTreeWidget(qtgui.QTreeWidget):
"""tree widget holding actions
"""
def startDrag(self, dro... | svenfraeys/sftoolbox | sftoolboxqt/editor.py | Python | mit | 4,569 |
import logging
from pyvisdk.exceptions import InvalidArgumentError
########################################
# Automatically generated, do not edit.
########################################
log = logging.getLogger(__name__)
def VmfsDatastoreCreateSpec(vim, *args, **kwargs):
'''This data object type is used when ... | xuru/pyvisdk | pyvisdk/do/vmfs_datastore_create_spec.py | Python | mit | 1,109 |
import av
import logging
import random
import sys
import time
import warnings
from livestreamer import Livestreamer
from experiments.test_detecting_in_lol_or_not import get_classifier, process_image
from ocr import ocr_image
logging.getLogger("libav.http").setLevel(logging.ERROR)
# Hide warnings from SKLearn from ... | ckcollab/twitch-experiments | src/stream_frame_identifier.py | Python | mit | 2,329 |
#!/usr/bin/python
import sys
import remote_core as core
import radio_lights
def main(argv):
config = core.load_config()
lights_config_names = {"1":"door_light", "2":"desk_light", "3": "shelf_light"}
if len(argv) == 1 and len(argv[0]) == 2:
if argv[0] == "an":
argv = ["1n", "2n", "3n"]
elif argv[0] == "af"... | sradevski/homeAutomate | scripts/lights_controller.py | Python | mit | 665 |
# Copyright (C) 2002-2007 Python Software Foundation
# Author: Ben Gertzfield
# Contact: email-sig@python.org
"""Base64 content transfer encoding per RFCs 2045-2047.
This module handles the content transfer encoding method defined in RFC 2045
to encode arbitrary 8-bit data using the three 8-bit bytes in four 7-bit
ch... | thonkify/thonkify | src/lib/future/backports/email/base64mime.py | Python | mit | 3,724 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
下载后的漫画整理模块
====================
请参考注释部分的整理步骤。
"""
from __future__ import print_function, unicode_literals
import os, re
import shutil
import random, string
from hcomic.lib.filetool.files import WinDir, FileCollection
from hcomic.lib.filetool.winzip import zip_everyt... | angoraking/hcomic-project | hcomic/manage.py | Python | mit | 6,153 |
from __future__ import print_function
import time, json
# Run this as 'watch python misc/dump-stats.py' against a 'wormhole-server
# start --stats-file=stats.json'
with open("stats.json") as f:
data_s = f.read()
now = time.time()
data = json.loads(data_s)
if now < data["valid_until"]:
valid = "valid"
else:
... | warner/magic-wormhole | misc/dump-stats.py | Python | mit | 421 |
from concurrent.futures import ThreadPoolExecutor
import grpc
import pytest
from crawler.services import Library
import crawler_pb2_grpc
@pytest.fixture(name='grpc_client', scope='session', autouse=True)
def setup_grpc_client():
server = grpc.server(ThreadPoolExecutor(max_workers=4))
crawler_pb2_grpc.add_L... | xavierdutreilh/robots.midgar.fr | services/crawler/tests/conftest.py | Python | mit | 564 |
#! /usr/bin/env python
import os
import sys
from IPython.terminal.embed import InteractiveShellEmbed
from mongoalchemy.session import Session
HERE = os.path.abspath(os.path.dirname(__file__))
ROOT = os.path.join(HERE, '..')
sys.path.append(ROOT)
from server.model.user import User # noqa
from server.model.notificat... | jf-parent/webbase | {{cookiecutter.project_name}}/scripts/query.py | Python | mit | 634 |
def suma(a, b):
return a+b
def resta(a, b):
return a+b
| LeonRave/Tarea_Git | a.py | Python | mit | 66 |
"""Mongodb implementations of repository sessions."""
# pylint: disable=no-init
# Numerous classes don't require __init__.
# pylint: disable=too-many-public-methods,too-few-public-methods
# Number of methods are defined in specification
# pylint: disable=protected-access
# Access to protected methods allow... | birdland/dlkit-doc | dlkit/mongo/repository/sessions.py | Python | mit | 237,798 |
# -*- coding: utf-8 -*-
"""
Created on Tue May 31 10:57:02 2016
@author: noore
"""
import bioservices.kegg
import pandas as pd
kegg = bioservices.kegg.KEGG()
cid2name = kegg.list('cpd')
cid2name = filter(lambda x: len(x) == 2, map(lambda l : l.split('\t'), cid2name.split('\n')))
cid_df = pd.DataFrame(cid2name, colum... | dmccloskey/component-contribution | component_contribution/kegg_database.py | Python | mit | 860 |
"""The tests for the Graphite component."""
import socket
import unittest
from unittest import mock
import blumate.core as ha
import blumate.components.graphite as graphite
from blumate.const import (
EVENT_STATE_CHANGED,
EVENT_BLUMATE_START, EVENT_BLUMATE_STOP,
STATE_ON, STATE_OFF)
from tests.common impo... | bdfoster/blumate | tests/components/test_graphite.py | Python | mit | 8,152 |
# -*- coding: utf-8 -*-
"""Init and utils."""
from zope.i18nmessageid import MessageFactory
_ = MessageFactory('dakhli.sitecontent')
def initialize(context):
"""Initializer called when used as a Zope 2 product."""
| a25kk/dakhli | src/dakhli.sitecontent/dakhli/sitecontent/__init__.py | Python | mit | 222 |
# Generated by Django 2.2.5 on 2019-09-25 17:40
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('testproducts', '0001_initial'),
]
operations = [
migrations.CreateModel(
na... | JamesRamm/longclaw | longclaw/contrib/productrequests/migrations/0001_initial.py | Python | mit | 886 |
from datasift import (
DataSiftUser,
DataSiftDefinition,
DataSiftStream,
DataSiftStreamListener
) | msmathers/datasift-python | __init__.py | Python | mit | 105 |
__author__ = 'bdeutsch'
import re
import numpy as np
import pandas as pd
# List cards drawn by me and played by opponent
def get_cards(filename):
# Open the file
with open(filename) as f:
mycards = []
oppcards = []
for line in f:
# Generate my revealed card list
... | aspera1631/hs_logreader | logreader.py | Python | mit | 4,183 |
"""
Created on 1 May 2019
@author: Bruno Beloff (bruno.beloff@southcoastscience.com)
https://www.sensirion.com/en/environmental-sensors/particulate-matter-sensors-pm25/
https://bytes.com/topic/python/answers/171354-struct-ieee-754-internal-representation
Firmware report:
89667EE8A8B34BC0
"""
import time
from scs_c... | south-coast-science/scs_dfe_eng | src/scs_dfe/particulate/sps_30/sps_30.py | Python | mit | 8,991 |
#Using the variable 'i' is restricted by polyphony's name scope rule
from polyphony import testbench
def loop_var01():
for i in range(10):
pass
return i
@testbench
def test():
loop_var01()
test()
| ktok07b6/polyphony | tests/error/loop_var01.py | Python | mit | 222 |
"""38. Count and Say
https://leetcode.com/problems/count-and-say/description/
The count-and-say sequence is the sequence of integers with the first five
terms as following:
1. 1
2. 11
3. 21
4. 1211
5. 111221
1 is read off as "one 1" or 11.
11 is read off as "two 1s" or 21.
21 is read off as "one ... | isudox/leetcode-solution | python-algorithm/leetcode/problem_38.py | Python | mit | 1,320 |
#!/usr/bin/env python
# convertAWT.py - Mass Table Conversion Utility
import os
massFile = 'AWTMass-2003.dat'
newFile = os.path.join('..', 'nmrfreq', 'masstable.py')
def main():
with open(massFile, 'r') as file:
massDict = extractMasses(file)
writeToFile(newFile, massDict, massFile)
def extractMa... | mmoran0032/NMRpy | data/AWTconvertTable.py | Python | mit | 1,558 |
import json
from django.test import TestCase
from rest_framework.test import APIRequestFactory
from rest_framework.test import force_authenticate
from rest_framework import status
from rest_framework.authtoken.models import Token
from core.models import Profile, User
from api.views import ProfileDetail
from api.se... | desenho-sw-g5/service_control | Trabalho_1/api/tests/views_test/profile_detail_view_test.py | Python | mit | 2,944 |
#!/usr/bin/env python2
# Copyright (c) 2014-2015 The Aureus Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
from test_framework.test_framework import AureusTestFramework
from test_framework.util import *
from bina... | hideoussquid/aureus-12-bitcore | qa/rpc-tests/getblocktemplate_proposals.py | Python | mit | 6,330 |
#!/usr/bin/env python
# import keystoneclient.v2_0.client as ksclient
# import glanceclient.v2.client as glclient
# import novaclient.client as nvclient
# import neutronclient.v2_0.client as ntclient
# import cinderclient.v2.client as cdclient
# import swiftclient.client as sftclient
__author__ = 'Yuvv'
OS_PROJECT_D... | Yuvv/LearnTestDemoTempMini | py-django/DataBackup/ops/credentials.py | Python | mit | 3,202 |
# -*- coding: utf-8 -*-
__author__ = 'Yacine Haddad'
__email__ = 'yhaddad@cern.ch'
__version__ = '2.0.0'
| yhaddad/Heppi | tests/__init__.py | Python | mit | 110 |
#!/usr/bin/env python
# Copyright 2007 The Closure Linter Authors. 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
#
#... | Gobie/gjslinter | tools/closure_linter/errors.py | Python | mit | 4,404 |
import pytest, sys, os
sys.path.append(os.path.dirname(os.path.realpath(__file__)) + "/../")
from unittest import TestCase
from pylogic.case import Case
class TestBaseOperand(TestCase):
def test_eq_case(self):
case1 = Case("parent", "homer", "bart")
case2 = Case("parent", "homer", "bart")
... | fran-bravo/pylogic-module | test/test_case_operands.py | Python | mit | 666 |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# Copyright (c) 2011 Chris D. Lasher & Phillip Whisenhunt
#
# This software is released under the MIT License. Please see
# LICENSE.txt for details.
"""A program to detect Process Linkage Networks using
Simulated Annealing.
"""
import collections
import itertools
impo... | gotgenes/BiologicalProcessNetworks | bpn/mcmc/sabpn.py | Python | mit | 3,485 |
# coding=utf-8
import os
import csv
import time
import random
import operator
import numpy as np
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data as mnist_input_data
def main():
# Test classification using the following code:
#
# classifier = Classifier("model.pb")
# dataset = ... | NoelDeMartin/Japanese-Character-Recognition | train_model.py | Python | mit | 11,858 |
from django.shortcuts import render
from django.views import View
class SiteUpdateNotifier(View):
def get(self, request):
pass
| k00n/site_update_notifier | siteUpdateNotifier/sun/views.py | Python | mit | 141 |
#!/usr/bin/env python
"""
make_a_star_cluster.py creates a model star cluster,
which can then be used in N-body simulations or for other purposes.
It requires AMUSE, which can be downloaded from http://amusecode.org or
https://github.com/amusecode/amuse.
Currently not feature-complete yet, and function/argument names... | rieder/MASC | src/amuse/ext/masc/cluster.py | Python | mit | 10,655 |
from setuptools import setup, find_packages
setup(
name="tomorrow",
version="0.2.4",
author="Madison May",
author_email="madison@indico.io",
packages=find_packages(
exclude=[
'tests'
]
),
install_requires=[
"futures >= 2.2.0"
],
description="""
... | madisonmay/Tomorrow | setup.py | Python | mit | 521 |
import os
import MySQLdb
import logging
_log = logging.getLogger('thanatos')
def execute_sql(sql, db_connection, fetch='all'):
"""
:param sql:
:param db_connection:
:param fetch: A string of either 'all' or 'one'.
:return:
"""
cursor = db_connection.cursor()
cursor.execute(sql)
... | evetrivia/thanatos | thanatos/database/db_utils.py | Python | mit | 3,157 |
__version__ = "0.0.2"
from .samplesubmod import *
| hwong/samplesubmod | __init__.py | Python | mit | 51 |
from w3lib.html import remove_tags
from requests import session, codes
from bs4 import BeautifulSoup
# Net/gross calculator for student under 26 years
class Student:
_hours = 0
_wage = 0
_tax_rate = 18
_cost = 20
def __init__(self, hours, wage, cost):
self._hours = hours
... | tomekby/miscellaneous | jira-invoices/calculator.py | Python | mit | 6,443 |
#!/usr/bin/env python3
"""
Automatically test a given treewidth solver:
./autotest-tw-solver.py path/to/my/solver
The test is run on some corner cases, and on graphs were past PACE submissions
exhibited bugs.
Optional argument:
--full run test on all graphs with min-degree 3 and at most 8 vertices
Require... | holgerdell/td-validate | autotest-tw-solver.py | Python | mit | 6,041 |
from common.persistence import from_pickle
NWORDS = from_pickle('../data/en_dict.pkl')
print(len(NWORDS))
print(NWORDS['word'])
print(NWORDS['spell'])
alphabet = 'abcdefghijklmnopqrstuvwxyz'
def edits1(word):
s = [(word[:i], word[i:]) for i in range(len(word) + 1)]
deletes = [a + b[1:] for a, b in s if b]
... | anderscui/spellchecker | simple_checker/checker_tests_google_dict.py | Python | mit | 17,844 |
"""
mpstest7.py
A test of manipulating matrix product states with numpy.
2014-08-25
"""
import numpy as np
import matplotlib.pyplot as plt
from cmath import *
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
def main():
test3()
def test3():
""" Test MPS conversion functions by computing fide... | ehua7365/RibbonOperators | TEBD/mpstest7.py | Python | mit | 5,808 |
# -*- coding: utf-8 -*-
from __future__ import (print_function, unicode_literals, absolute_import,
division)
import json
import re
import six
import sys
channel_name_re = re.compile('\A[-a-zA-Z0-9_=@,.;]+\Z')
app_id_re = re.compile('\A[0-9]+\Z')
pusher_url_re = re.compile('\A(http|htt... | hkjallbring/pusher-http-python | pusher/util.py | Python | mit | 1,209 |
import contextlib
import functools
import socket
import ssl
import tempfile
import time
from typing import (
Any,
Callable,
Container,
Dict,
Generic,
Hashable,
Iterable,
Iterator,
List,
Optional,
Set,
Tuple,
Type,
TypeVar,
Union,
cast,
)
import pytest
fr... | ProgVal/irctest | irctest/cases.py | Python | mit | 28,335 |
PLACES = ["Virginia", "Lexington", "Washington", "New York"]
| jl4ge/cs3240-labdemo | places.py | Python | mit | 61 |
from onlineticket.generated.ticket import Ticket
from onlineticket.section import SectionParser
class TicketParser:
def parse(self, filename):
parsed = self._parse_kaitai(filename)
return self._map(parsed)
def _parse_kaitai(self, filename):
return Ticket.from_file(filename)
def _m... | joushx/Online-Ticket-Code | onlineticket/ticketparser.py | Python | mit | 860 |
from __future__ import unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
import docker
@python_2_unicode_compatible
class DockerServer(models.Model):
name = models.CharField(max_length=255, unique=True)
version = models.CharField(max_length=255, defau... | sourcelair/castor | castor/docker_servers/models.py | Python | mit | 1,063 |
from flask import Blueprint
main = Blueprint('main', __name__)
from . import errors, views
from ..models import Permission
@main.app_context_processor
def inject_permissions():
return dict(Permission=Permission)
| caser789/xuejiao-blog | app/main/__init__.py | Python | mit | 219 |
from .models import Donor
from django.forms import ModelForm, TextInput
class DonorForm(ModelForm):
class Meta:
model = Donor
fields = [
"email",
"donation_date",
"phone_number",
"address",
"observations"
]
widgets = {
'donation_date': TextInput(attrs={'class': 'form-control'}),
... | amigos-do-gesiel/iespv-administrativo | users/forms.py | Python | mit | 597 |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.3 on 2016-12-16 12:59
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('courses', '0012_userlesson'),
]
operations = [
... | RubenSchmidt/giscademy | courses/migrations/0013_auto_20161216_1359.py | Python | mit | 845 |
import argparse, json
import boto3
from boto.mturk.connection import MTurkConnection
from boto.mturk.qualification import *
from jinja2 import Environment, FileSystemLoader
"""
A bunch of free functions that we use in all scripts.
"""
def get_jinja_env(config):
"""
Get a jinja2 Environment object that we can use... | choltz95/story-understanding-amt | simpleamt.py | Python | mit | 2,932 |
import json
import requests
import logging
logger = logging.getLogger(__name__)
import warnings
import time
import sys
from counterpartylib.lib import config
from counterpartylib.lib import util
from counterpartylib.lib import exceptions
from counterpartylib.lib import backend
from counterpartylib.lib import database
... | F483/counterparty-lib | counterpartylib/lib/check.py | Python | mit | 16,154 |
# -*- coding: utf-8 -*-
from django import forms
from giza.models import Giza
class GizaEditForm(forms.ModelForm):
"""Giza edit form"""
class Meta:
"""Meta for GizaEditForm"""
model = Giza
exclude = ('user',)
def __init__(self, *args, **kwargs):
"""Init"""
self.... | genonfire/portality | giza/forms.py | Python | mit | 412 |
#!/usr/bin/env python
"""
Project-wide application configuration.
DO NOT STORE SECRETS, PASSWORDS, ETC. IN THIS FILE.
They will be exposed to users. Use environment variables instead.
See get_secrets() below for a fast way to access them.
"""
import os
"""
NAMES
"""
# Project name to be used in urls
# Use dashes, n... | NathanLawrence/lunchbox | app_config.py | Python | mit | 2,936 |
# encoding: utf8 | CooperLuan/sasoup | examples/__init__.py | Python | mit | 16 |
import theano
import numpy as np
from sklearn.preprocessing import OneHotEncoder
from sklearn import cross_validation, metrics, datasets
from neupy import algorithms, layers, environment
environment.reproducible()
theano.config.floatX = 'float32'
mnist = datasets.fetch_mldata('MNIST original')
target_scaler = OneHo... | stczhc/neupy | examples/gd/mnist_mlp.py | Python | mit | 1,266 |
import numpy as np
import tensorflow as tf
from .module import Module
class RBFExpansion(Module):
def __init__(self, low, high, gap, dim=1, name=None):
self.low = low
self.high = high
self.gap = gap
self.dim = dim
xrange = high - low
self.centers = np.linspace(low... | atomistic-machine-learning/SchNet | src/schnet/nn/layers/rbf.py | Python | mit | 966 |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-10-15 08:06
from __future__ import unicode_literals
import django.contrib.auth.validators
from django.db import migrations, models
import users.managers
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0008... | spiralsyzygy/django-drf-base-app | users/migrations/0001_initial.py | Python | mit | 2,755 |
import os
DIRNAME = os.path.dirname(__file__)
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3"
}
}
INSTALLED_APPS = (
"django.contrib.auth",
"django.contrib.contenttypes",
"pqauth.pqauth_django_server"
)
SECRET_KEY = "chicken butt"
PQAUTH_SERVER_KEY = os.path.join(DIRNA... | teddziuba/pqauth | python/pqauth/pqauth_django_server/tests/settings.py | Python | mit | 495 |
from twitter import *
import simplejson
import serial
import datetime
import time
import threading
QUIT = 0
prevtweet = ""
def centerstring(string,width):
""" Pad a string to a specific width """
return " "*((width-len(string))/2)+string
def padstring(string,width):
"""pad a string to a maximum length"""
if... | tachijuan/python | myscripts/timeandtweet.py | Python | mit | 3,145 |
#encoding:utf-8
import pymongo
import yaml
import utils
from utils import SupplyResult
from utils.tech import get_dev_channel, short_sleep
subreddit = 'all'
t_channel = '@r_channels'
SETTING_NAME = 1
def send_post(submission, r2t):
config_filename = 'configs/prod.yml'
with open(config_filename) as confi... | Fillll/reddit2telegram | reddit2telegram/channels/tech_receiver/app.py | Python | mit | 2,506 |
def diff_int(d=0.01*u.cm,a=0.001*u.cm,wl=400*u.nm):
'''
function that returns the intensity of a double slit interference pattern
'''
theta = arange(-10,10,1e-5)*u.degree
x = pi*a*sin(theta)/wl*u.radian
xnew = x.decompose()
i_single = (sin(xnew)/xnew)**2
y = pi*d*sin(theta)/wl*u.ra... | kfollette/ASTR200-Spring2017 | Homework/diff_int.py | Python | mit | 441 |
# encoding: UTF-8
'''
本文件中包含的是CTA模块的回测引擎,回测引擎的API和CTA引擎一致,
可以使用和实盘相同的代码进行回测。
'''
from datetime import datetime, timedelta
from collections import OrderedDict
from itertools import product
import pymongo
# import MySQLdb
import json
import os
import cPickle
import csv
from ctaBase import *
from ctaSetting import *
... | kanchenxi04/vnpy-app | vn.trader/ctaAlgo/ctaBacktesting.py | Python | mit | 105,820 |
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import json
import time
def keys(filename):
with open(filename) as f:
secret_keys = json.load(f)
return secret_keys
def access_listpage(secret_keys, driver):
driver.get("https://wine.wul.waseda.ac.jp/patroninfo*jpn")
... | Accent-/WasedaU_Library | wine.py | Python | mit | 1,004 |
#!/usr/bin/python
from flask import Flask, session, render_template, url_for, redirect, request, flash, g
from flask.ext import assets
import pyxb
import json
import json
import os
import paypalrestsdk
app = Flask(__name__)
paypal_client_id = "AacMHTvbcCGRzaeuHY6i6zwqGvveuhN4X_2sZ2mZJi76ZGtSZATh7XggfVuVixzyrRuG-bJTLOJ... | IshavanBaar/railaid | app.py | Python | mit | 4,184 |
#!/usr/bin/env python3
from .proc_base import ProcBase
class ProcMaps(ProcBase):
'''Object represents the /proc/[pid]/maps file.'''
def __init__(self, pid):
'''
Read file by calling base class constructor
which populates self.content. This file is
already ASCII printable, so ... | EwanC/pyProc | proc_scraper/proc_maps.py | Python | mit | 600 |
#!/usr/bin/env python
"""
Reduce samples that have too high energies by comparing
between the same group of samples.
The group is defined according to the name of directory before the last 5 digits.
For example, the directory `smpl_XX_YYYYYY_#####` where `#####` is the
last 5 digits and the group name would be `smpl_XX... | ryokbys/nap | nappy/fitpot/reduce_high_energy_samples.py | Python | mit | 2,920 |
from os import makedirs
from os.path import join
from posix import listdir
from django.conf import settings
from django.core.management.base import BaseCommand
from libavwrapper.avconv import Input, Output, AVConv
from libavwrapper.codec import AudioCodec, NO_VIDEO
from 匯入.族語辭典 import 代碼對應
class Command(BaseComma... | sih4sing5hong5/hue7jip8 | 匯入/management/commands/族語辭典1轉檔.py | Python | mit | 1,474 |
import numpy as np
import numpy.random as rng
import theano
import theano.tensor as T
from theano.tensor.nnet import conv2d
minibatch = 3
image_height,image_width = 28,28
filter_height,filter_width = 3,3
n_filters = 1
n_channels = 1
n = 1/(np.sqrt(image_height*image_width))
X = T.tensor4(name='X')
X_shape = (minibat... | nzufelt/theano_nn | min_work_ex.py | Python | mit | 757 |
from .max import max
from pyramda.private.asserts import assert_equal
def max_test():
assert_equal(max([1, 3, 4, 2]), 4)
| jackfirth/pyramda | pyramda/relation/max_test.py | Python | mit | 127 |
import __settings__
from __settings__ import INSTALLED_APPS
assert hasattr(__settings__, 'BASE_DIR'), 'BASE_DIR required'
INSTALLED_APPS += (
'post',
)
| novafloss/django-compose-settings | tests/fixtures/my_app/settings/post.py | Python | mit | 161 |
import _plotly_utils.basevalidators
class MetaValidator(_plotly_utils.basevalidators.AnyValidator):
def __init__(self, plotly_name="meta", parent_name="surface", **kwargs):
super(MetaValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
array_ok=k... | plotly/python-api | packages/python/plotly/plotly/validators/surface/_meta.py | Python | mit | 480 |
from typing import List
from backend.common.cache_clearing import get_affected_queries
from backend.common.manipulators.manipulator_base import ManipulatorBase
from backend.common.models.cached_model import TAffectedReferences
from backend.common.models.media import Media
class MediaManipulator(ManipulatorBase[Media... | the-blue-alliance/the-blue-alliance | src/backend/common/manipulators/media_manipulator.py | Python | mit | 805 |
import _plotly_utils.basevalidators
class SeparatethousandsValidator(_plotly_utils.basevalidators.BooleanValidator):
def __init__(
self,
plotly_name="separatethousands",
parent_name="scattermapbox.marker.colorbar",
**kwargs
):
super(SeparatethousandsValidator, self).__i... | plotly/plotly.py | packages/python/plotly/plotly/validators/scattermapbox/marker/colorbar/_separatethousands.py | Python | mit | 487 |
# 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-servicefabric/azure/servicefabric/models/applications_health_evaluation.py | Python | mit | 2,699 |
import chainer
from chainer import cuda
import chainer.utils
class Send(chainer.Function):
"""Send elements to target process."""
def __init__(self, comm, peer_rank, peer_tag):
chainer.utils.experimental('chainermn.functions.Send')
self.comm = comm
self.peer_rank = peer_rank
s... | rezoo/chainer | chainermn/functions/point_to_point_communication.py | Python | mit | 7,375 |
from bottle import Bottle, run
app = Bottle()
@app.route('/')
def index():
return 'PService Running'
#
# Start a server instance
#
run(
app, # Run |app| Bottle() instance
host = '0.0.0.0',
port = 8080,
reloader = True, # restarts the server every ... | Kjuly/iPokeMon-Server | test.py | Python | mit | 417 |
from __future__ import absolute_import, print_function, division
from petl.test.helpers import ieq
from petl.util import expr, empty, coalesce
from petl.transform.basics import cut, cat, addfield, rowslice, head, tail, \
cutout, skipcomments, annex, addrownumbers, addcolumn, \
addfieldusingcontext, movefield,... | thatneat/petl | petl/test/transform/test_basics.py | Python | mit | 17,148 |
#! /usr/bin/python2.7
import os
import re
import sys
# some static resources
vowels = set(('a','e','i','o','u','A','E','I','O','U'))
#vowel_re
consonant_re = re.compile(r'([bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ]+)([a-zA-Z]*)(.*)?')
# input
original = sys.stdin.read()
# output
piglatin = []
# loop over the word... | mouckatron/Martyr2MegaProjectList | text/piglatin.py | Python | mit | 638 |
# ----------------------------------------------------------------------------------
# Electrum plugin for the Digital Bitbox hardware wallet by Shift Devices AG
# digitalbitbox.com
#
try:
import electrum_arg as electrum
from electrum_arg.bitcoin import TYPE_ADDRESS, var_int, msg_magic, Hash, verify_message, p... | argentumproject/electrum-arg | plugins/digitalbitbox/digitalbitbox.py | Python | mit | 20,399 |
# coding=utf-8
# Distributed under the MIT software license, see the accompanying
# file LICENSE or http://www.opensource.org/licenses/mit-license.php.
import argparse
import os
import simplejson as json
import grpc
from google.protobuf.json_format import MessageToJson
from qrl.core import config
from qrl.core.AddressS... | cyyber/QRL | src/qrl/grpcProxy.py | Python | mit | 9,400 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.