repo_name stringlengths 5 104 | path stringlengths 4 248 | content stringlengths 102 99.9k |
|---|---|---|
thatguyandy27/advent-of-code-2016 | problem10.py | import md5
puzzle_input = 'ffykfhsq'
def get_hash(index):
return md5.new(puzzle_input + str(index)).hexdigest()
def get_code():
index = 0
current_code = ['0','0','0','0','0','0','0','0']
codes = set()
while len(codes) < 8:
hash_code = get_hash(index)
index += 1
if hash_code[:5] == '00000':
... |
vandegu/umich | modify_pop2_rst.py | # This script is to replace the missing values in a modified paleogeography.
import netCDF4 as nc
import numpy as np
import matplotlib.pyplot as plt
import os
import pyproj as proj4
import scipy.interpolate as si
# The CoordinateSystem and GeographicSystem classes are hereby used courtesy of Dr. Eric Bruning; his
# re... |
jttyeung/investable | server.py | """ Investable Server """
from flask import Flask, render_template, redirect, flash, request, jsonify, json
from flask_debugtoolbar import DebugToolbarExtension
import jinja2
import os
import geocoder
from zillow_utilities import *
from account_utilities import *
from mortgage_calculator import *
from db_queries imp... |
xeroc/python-graphenelib | tests/test_block_aio.py | # -*- coding: utf-8 -*-
import aiounittest
from graphenecommon.utils import parse_time
from .fixtures_aio import fixture_data, Block, BlockHeader
class Testcases(aiounittest.AsyncTestCase):
def setUp(self):
fixture_data()
async def test_block(self):
block = await Block(1)
self.assertE... |
eschloss/FluFuture | openpds/wsgi.py | """
WSGI config for openPDS project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` ... |
MooseDojo/apt2 | modules/action/exploit_msf_javarmi.py | import re
from core.actionModule import actionModule
from core.keystore import KeyStore as kb
from core.mymsf import myMsf
from core.utils import Utils
class exploit_msf_javarmi(actionModule):
def __init__(self, config, display, lock):
super(exploit_msf_javarmi, self).__init__(config, display, lock)
... |
JasonLC506/CollaborativeFiltering | old_version/TDMultiClass.py | """
Multiclass dyadic data learning
here Tucker Decomposition (TD) for tensor decomposition is employed
in context of facebook emoticon rating, rating classes are fixed, given and small
"""
import numpy as np
import matrixTool
from MFMultiClass import ppl
SCALE = 0.1
class TD(object):
def __init__(self):
... |
xanthics/gw2craft-python3 | auto_gen/Scribe.py | # -*- coding: utf-8 -*-
# Created: 2018-01-04T19:46:58 PST
recipes = {
19679: {'min': 0, 'max': 25, 'recipe': {19697: 10, 19704: 1}},
19680: {'min': 0, 'max': 25, 'recipe': {19697: 2}},
19681: {'min': 225, 'max': 250, 'recipe': {19702: 2, 19924: 1}},
19682: {'min': 150, 'max': 175, 'recipe': {19698: 2}},
19683: {'... |
drusk/pml-applications | student_records/util.py | """
Some functions useful for a variety of analysis scripts.
"""
# Python standard library imports
import sys
import inspect
from pml.api import load
def print_line_break():
print "*" * 50
def load_data():
"""
Loads data from the file whose name/path is passed in when calling
the script.
"""... |
bgarnaat/codewars_katas | src/python/6kyu/arrays_and_hex_color_codes/arrays_and_hex_color_codes.py | """
DESCRIPTION:
Given an array with 3 subarrays, which each contain a number of hexadecimal color codes loosely defining red, green and blue colors based on their predominant byte value, return a string description of which of the three colors each array contains.
Input is an array that holds 3 arrays each of lengt... |
terryyin/pybook | py_book/markdown_file_loader.py | '''
All the file operations.
'''
__all__ = ["load_folder"]
import os
import codecs
def _compare_filename(a, b):
return (a > b) - (a < b) if a.startswith('_') == b.startswith('_') else [1, -1][a.startswith('_')]
_sort_dir_entries = lambda direntries: direntries.sort(cmp=_compare_filename)
try:
# Python 2.... |
syllog1sm/TextBlob | text/nltk/corpus/reader/conll.py | # Natural Language Toolkit: CONLL Corpus Reader
#
# Copyright (C) 2001-2013 NLTK Project
# Author: Steven Bird <sb@ldc.upenn.edu>
# Edward Loper <edloper@gradient.cis.upenn.edu>
# URL: <http://www.nltk.org/>
# For license information, see LICENSE.TXT
"""
Read CoNLL-style chunk fileids.
"""
from __future__ imp... |
frol/flask-restplus-server-example | tasks/app/boilerplates.py | # pylint: disable=line-too-long
"""
Boilerplates
"""
from __future__ import print_function
import logging
import os
import re
try:
from invoke import ctask as task
except ImportError: # Invoke 0.13 renamed ctask to task
from invoke import task
log = logging.getLogger(__name__) # pylint: disable=invalid-na... |
syscoin/syscoin | test/functional/interface_syscoin_cli.py | #!/usr/bin/env python3
# Copyright (c) 2017-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 syscoin-cli"""
from decimal import Decimal
import re
from test_framework.blocktools import COINB... |
Encrylize/flask-blogger | migrations/versions/2751777b30e_.py | """empty message
Revision ID: 2751777b30e
Revises: 3ecc9b116c2
Create Date: 2015-12-17 17:15:58.890303
"""
# revision identifiers, used by Alembic.
revision = '2751777b30e'
down_revision = '3ecc9b116c2'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - plea... |
Alex-Rose/SomeScripts | ski.py | from bs4 import BeautifulSoup
from urllib import quote_plus
import urllib2
import re
import MySQLdb
import unicodedata
import json
import argparse
parser = argparse.ArgumentParser(prog="Ski")
parser.add_argument('-v', dest='verbose', default=False, action='store_true', help='verbose')
parser.add_argument('-... |
JeffpanUK/NuPyTools | ferup_homos_labler.py | #-*- coding:utf-8 -*-
#!\usr\bin\env py3
import os
import re
import codecs
"""
Program: ferup_homos_labeler.py
Function: modify auto file
Author: Junjie Pan (junjie.pan@nuance.com)
"""
class HmogrpyAuto(object):
'''
Modify auto file, insert polyphone LHP
'''
def __init__(self, options, logger):
self.optio... |
daniellawrence/30second-devops | fabric/fabfile.py | #!/usr/bin/env python
# ----------------------
from fabric.api import task, local
def install_hello():
" Install the hello package on the system "
local("apt-get install -y hello")
def helloworld_file():
" Create a file /tmp/helloworld that greets the world"
local("echo 'Hello World!' > /tmp/hellowo... |
2Checkout/2checkout-python | twocheckout/api_request.py | import urllib
import urllib2
import json
from error import TwocheckoutError
class Api:
username = None
password = None
private_key = None
seller_id = None
version = '1'
@classmethod
def credentials(cls, credentials):
Api.username = credentials['username']
Api.password = c... |
damouse/rabric | exec/server.py | '''
There is no distinction between client and server here. Names used here as
files to keep them seperate.
'''
from twisted.internet.defer import inlineCallbacks, returnValue, Deferred
from autobahn.twisted.wamp import ApplicationSession, ApplicationRunner
from autobahn.wamp.types import RegisterOptions, Subscrib... |
haesemeyer/RegionSelector | utilities.py | import pyqtgraph as pg
import matplotlib.path as mpath
import h5py
import numpy as np
import warnings
class RegionContainer:
"""
Container for saving and loading RegionROI information
"""
def __init__(self, positions, region_name: str, z_index: int):
"""
Create a new RegionContainer
... |
yasyf/bcferries | bcferries/abstract.py | import json, datetime
from fuzzydict import FuzzyDict
from geopy.location import Location
from geopy.distance import Distance
def try_with_kwargs(f, **kwargs):
try:
return f(**kwargs)
except TypeError:
return f()
def clean_special_types(x):
if isinstance(x, Location):
return list(x)
if isinstance(... |
dreipol/djangocms-spa | djangocms_spa/renderer_pool.py | from .cms_plugins import SPAPluginMixin
from .renderer import BaseSPARenderer, MixinPluginRenderer
class RendererPool(object):
def __init__(self):
self.renderers = {}
def register_renderer(self, renderer: BaseSPARenderer.__class__):
self._register_renderer(renderer())
def _register_rende... |
danche354/Sequence-Labeling | chunk_all/senna-hash-pos-128-64-rmsprop5.py | from keras.models import Model
from keras.layers import Input, Masking, Dense, LSTM
from keras.layers import Dropout, TimeDistributed, Bidirectional, merge
from keras.layers.embeddings import Embedding
from keras.utils import np_utils
from keras.optimizers import RMSprop
import numpy as np
import pandas as pd
import ... |
kgaughan/neuemux | neuemux/frames.py | """
Support for basic EPP frame construction and parsing.
"""
import uuid
from neuemux import xmlutils
ROOT = 'urn:ietf:params:xml:ns:epp-1.0'
HELLO = (
'<?xml version="1.0" encoding="UTF-8"?>'
'<epp xmlns="urn:ietf:params:xml:ns:epp-1.0"><hello/></epp>'
)
def login(uname, pwd, objs=(), exts=(), lang='en... |
crossin/yuan-xin | base.py | # -*- coding: utf-8 -*-
import os,logging
import re
from functools import wraps
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.ext.webapp import template
from google.appengine.api import memcache
from google.appengine.api... |
MickMack1983/multicastclient | test/tiipclienttester.py | from tiipbusclient.tiipclient import TiipClient
from pytiip.tiip import TIIPMessage
class A:
def __init__(self, name):
self.tc = TiipClient(name)
self.tc.registerBusInterface("hepp", self.hepp)
self.tc.subscribe("nisse", self.happ)
self.tc.subscribe("nisse", self.hipp)
sel... |
lukpueh/uptane_banners | uptane_sounds.py | #!/usr/bin/env python
"""
<Program Name>
uptane_sounds.py
<Author>
Lukas Puehringer <lukas.puehringer@nyu.edu>
<Started>
Jan 12, 2017
<Copyright>
See LICENSE for licensing information.
<Purpose>
Provides function to to find command line player and play sounds.
"""
import os
from subprocess import Popen, ... |
iromli/flask-flywheel | test_flywheel.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import pytest
@pytest.fixture(scope="session")
def app(request):
from flask import Flask
app = Flask(__name__)
app.config["TESTING"] = True
app.config[... |
francisar/ticket | common/sns_network.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
import socket
import copy
import urllib,urllib2
from urllib2 import Request
from random import choice
import httplib
try:
import json
except ImportError:
import simplejson as json
#from sns_sig import hmac_sha1_sig
class SNSNetwork(object):
_iplist = ['172.27.... |
fintura/pyPaaS | pypaas/logging_wrapper.py | import os
import shlex
import subprocess
import sys
import time
from contextlib import suppress
from queue import Queue
from threading import Thread
from .options import main
def logging_wrapper():
"""
Wraps the a process and copies it's log output to a logger process.
The logger process is specified in... |
beatorizu/tekton | backend/appengine/routes/cards/home.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from config.template_middleware import TemplateResponse
from gaecookie.decorator import no_csrf
from gaepermission.decorator import login_not_required
from routes.cards import rest, rev
from tekton.router import to_path
__author__ = 'bea'... |
minneron/minneron | sql2pas.py | # this is a quick hack to generate a pascal include file
# from the database schema for nodak. i will probably
# clean it up and use it for minneron too when i get to
# that point.
#
# usage:
# python3 sql2pas.py sql/minneron.sql > .gen/minneron-sql2pas.inc
import os, sys
def main(sqlpath:str)->None:
nospace = lam... |
ashm2/josephus_problem | josephus.py | import sys
import argparse
def josephus(n, k):
""" Function that calculates the last person location
of the josephus problem
Args:
n(int): number of people in circle
k(int): step rate
Returns:
int: index value of the winner
"""
# special case, k = 1
if k == 1... |
Cladis/wikilabels | wikilabels/util/tsv.py | import json
def read(f, header=False):
if header:
headers = decode_row(f.readline())
else:
headers = None
for line in f:
yield decode_row(line, headers=headers)
def encode(value):
return json.dumps(value)
def encode_row(values, headers=None):
if headers is None:
... |
alceubissoto/gp-tcc | treep3.py | import random, math, copy
import numpy as np
class BinaryNode(object):
def __init__(self, value = None, arity = 2, children = []):
self.value = value
self.arity = arity
self.children = children
def __repr__(self, level=0):
ret = "\t"*level+repr(self.value)+"\n"
for chil... |
adakasky/CNN-QA | src/utils.py | """
utility functions
@author: Ao Liu, Zhuodong Huang, Zitao Wang
"""
from __future__ import division
from __future__ import print_function
import json
import gzip
import codecs
import numpy as np
from nltk import word_tokenize as wt
# from gensim.models import Word2Vec
# embeddings = Word2Vec.load("../data/word2v... |
Mitali-Sodhi/CodeLingo | Dataset/python/forms.py |
from django import forms
from django.conf import settings
from django.core.mail import send_mail
from django.utils.translation import ugettext_lazy
class EmailForm(forms.Form):
sender = forms.EmailField(max_length=100, initial=settings.POSTMARK_SENDER)
to = forms.CharField(initial='bill@averline.c... |
MasterOdin/Connect4-AI | main.py | """
main game logic
"""
from __future__ import print_function
from board import Board
from human import Human
from ai import AI
__author__ = "Matthew 'MasterOdin' Peveler"
__license__ = "The MIT License (MIT)"
def run_game():
"""
runs the game :D
"""
game_board = Board()
player1 = Human("1")
... |
mythmon/dove | dove/rtorrent.py | import shlex
import socket
import xmlrpclib
from subprocess import Popen, PIPE
from time import sleep
from dove.config import config
class ConnectionManager(object):
def __init__(self):
self.xmlrpc = None
def connect(self):
self.xmlrpc = xmlrpclib.ServerProxy(config['rpc_url'])
def dis... |
ngannguyen/aimseqtk | tests/stat_common_test.py | #!/usr/bin/env python
#Copyright (C) 2013 by Ngan Nguyen
#
#Released under the MIT license, see LICENSE.txt
'''
Testing aimseqtk.lib.statcommon functions
'''
import os
import sys
import unittest2 as unittest
import aimseqtk.lib.statcommon as stat
import aimseqtk.lib.common as lcommon
import aimseqtk.lib.sample as l... |
albertaleksieiev/zpy | Zpy/modules/some_module.py |
import math
def square(a):
return a * a
def square_from_pipe(zpy_input):
return square(zpy_input)
def power(base, exponent=None):
if exponent is None:
def currying_function(zpy_input):
return math.pow(base, zpy_input)
return currying_function
else:
return math.p... |
diego-carvalho/FAiR | app/src/qualityAnalysis.py | # -*- coding: utf-8 -*
from __future__ import division
import numpy as np
import os
import sys
from plotGraphs import plot_graphs
from precisionRecall import precision_recall
from distributionPR import distribution_pr
from distributionCumulative import distribution_cumulative
def quality_analysis(dic_u_test, dic_... |
medav/yatml | l2-nn-basics/p1-hello-tf.py | import numpy as np
import tensorflow as tf
# First, let's create a "placeholder", which is
# the value we as the user supply to the graph.
x = tf.placeholder(tf.float32, shape=None)
# Here we create two variables: a and b. We can
# give them default values.
a = tf.Variable(1, dtype=tf.float32, name="weight"... |
djevans071/Rebalancing-Citibike | cleanup.py | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 7 16:19:11 2017
@author: psamtik071
"""
from workflow.data import trip_data
import os
for year in xrange(2017,2018):
for month in xrange(1,13):
basepath = 'tripdata/'
to_filename = '{}{:02}-citibike-tripdata.csv'.format(year... |
0/Boltzmannizer | boltzmannizer/science/boltzmann_distribution.py | from __future__ import division
from json import load
from math import exp, log
from os.path import basename, splitext
import numpy as N
from boltzmannizer.tools.misc import memoized
class InvalidFormat(Exception): pass
class NonIncreasingEnergies(Exception): pass
class BoltzmannDistribution(object):
"""
Util... |
Azure/azure-sdk-for-python | sdk/keyvault/azure-keyvault-keys/azure/keyvault/keys/crypto/_internal/algorithms/rsa_signing.py | # ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding, utils
from ..algorithm import SignatureAlgorithm
from .... |
reinout/reinout-arduino | doc/source/conf.py | # -*- coding: utf-8 -*-
# Note that not all possible configuration values are present in this
# autogenerated file.
# All configuration values have a default; values that are commented out
# serve to show the default.
import datetime
project = "reinout_arduino"
author = ""
version = ""
release = ""
this_year = dateti... |
renhaocui/Social_Conversation_Connector | astute_social_cert/wechatProcess.py | # -*- coding: utf-8 -*-
import utilities
from flask import Flask, jsonify, make_response, request
from wechat_sdk import WechatConf
from wechat_sdk import WechatBasic
from wechat_sdk.exceptions import ParseError
from threading import Thread
from langid.langid import LanguageIdentifier, model
from datetime import dateti... |
ivanyu/rosalind | algorithmic_heights/bins/bins.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
def main(argv):
from search_logic import search
if len(argv) < 2:
print("Input file isn't specified. Using test values:")
print('n = 5')
n = 5
print('m = 6')
n = 6
print('A = [10, 20, 30, 40, 50]')
arr = [1... |
Torvaney/chainplot | chainplot/core/plot.py | import matplotlib.cm
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import scipy.optimize as op
from adjustText import adjust_text
from scipy.stats.kde import gaussian_kde
import chainplot.core.style as plot_style
from chainplot.utils.dict_tools import replace_dict, split_kwargs, britishdict, c... |
ArcherSys/ArcherSys | Lib/test/test_json/test_recursion.py | <<<<<<< HEAD
<<<<<<< HEAD
from test.test_json import PyTest, CTest
class JSONTestObject:
pass
class TestRecursion:
def test_listrecursion(self):
x = []
x.append(x)
try:
self.dumps(x)
except ValueError:
pass
else:
self.fail("didn't r... |
jthurst3/MemeCaptcha | models_cnn_lstm/im2txt/im2txt/ops/image_embedding.py | # Copyright 2016 The TensorFlow 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
#
# Unless required by applica... |
VikParuchuri/ownerchange | scrape_data.py | import requests
import bs4
import os
import time
import logging
import sys
import traceback
import settings
log = logging.getLogger(__name__)
class TeamInfo(object):
def __init__(self, team):
self.team = team
self.team_name = settings.teams[team]
self.exec_url = "http://www.pro-football-ref... |
Einsteinish/PyTune3 | apps/static/views.py | import os
import yaml
import redis
from django.conf import settings
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.template import RequestContext
from apps.rss_feeds.models import Feed, MStory
from apps.search.models import SearchFeed
from utils import log as logging
d... |
mozman/ezdxf | src/ezdxf/path/commands.py | # Copyright (c) 2021-2022, Manfred Moitzi
# License: MIT License
import enum
from typing import NamedTuple, Union
from ezdxf.math import Vec3
__all__ = [
"Command",
"AnyCurve",
"PathElement",
"LineTo",
"Curve3To",
"Curve4To",
"MoveTo",
]
@enum.unique
class Command(enum.IntEnum):
LI... |
cordery/django-countries-plus | countries_plus/migrations/0005_auto_20160224_1804.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('countries_plus', '0004_auto_20150616_1242'),
]
operations = [
migrations.AlterField(
model_name='country',
... |
PyCQA/pydocstyle | src/tests/test_cases/sections.py | """A valid module docstring."""
from .expected import Expectation
expectation = Expectation()
expect = expectation.expect
_D213 = 'D213: Multi-line docstring summary should start at the second line'
_D400 = "D400: First line should end with a period (not '!')"
@expect(_D213)
@expect("D405: Section name should be ... |
mrmmm/gdgapi | gdgapi/gdgapi/wsgi.py | """
WSGI config for gdgapi project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` s... |
algorhythms/LeetCode | 520 Detect Capital.py | #!/usr/bin/python3
"""
Given a word, you need to judge whether the usage of capitals in it is right or
not.
We define the usage of capitals in a word to be right when one of the following
cases holds:
All letters in this word are capitals, like "USA".
All letters in this word are not capitals, like "leetcode".
Only t... |
glwagner/py2Periodic | tests/twoLayerQG/testTwoLayerTopography.py | import time, sys
import numpy as np
import matplotlib.pyplot as plt
sys.path.append('../../')
from py2Periodic.physics import twoLayerQG
from numpy import pi
params = {
'f0' : 1.0e-4,
'Lx' : 1.0e6,
'beta' : 1.5e-11,
'defRadius' : 1.5e4,
'H1' : 500.0,
'H2' ... |
keisukefukuda/mpienv | mpienv/command/rename.py | # coding: utf-8
import argparse
from mpienv import mpienv
parser = argparse.ArgumentParser(
prog='mpienv rename', description='Rename an environment.')
parser.add_argument('name_from', type=str)
parser.add_argument('name_to', type=str)
def main():
args = parser.parse_args()
mpienv.rename(args.name_from... |
owenwater/alfred-cal | src/base.py | #!/usr/bin/python
# encoding: utf-8
from util import DEFAULT_SETTINGS
from workflow import Workflow
import sys
class Base(object):
def __init__(self, args):
self.args = unicode(args.strip(), 'utf-8')
def execute(self):
wf = Workflow(default_settings=DEFAULT_SETTINGS)
self.wf = wf
... |
vb64/django.common | tests/test/test_tzone.py | # python tests.py ../source test.test_tzone
from datetime import datetime
from babel.dates import UTC
from tzone import dump, make_timezone, to_local, from_local
from . import TestCase
class TestCaseTZ(TestCase):
def setUp(self):
super(TestCaseTZ, self).setUp()
self.dt = datetime(2017, 8, 24, 0,... |
pyvim/barbot | setup.py | # coding=utf-8
from os import path
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
VERSION = '1.2.2'
here = path.abspath(path.dirname(__file__))
packages = [
'barbot'
]
requires = [
'configobj',
'lxml',
'randua',
'requests',
'dotmap',
'urlt... |
MalloyPower/parsing-python | front-end/testsuite-python-lib/Python-3.1/Lib/distutils/util.py | """distutils.util
Miscellaneous utility functions -- anything that doesn't fit into
one of the other *util.py modules.
"""
__revision__ = "$Id: util.py 70787 2009-03-31 00:34:54Z georg.brandl $"
import sys, os, string, re
from distutils.errors import DistutilsPlatformError
from distutils.dep_util import newer
from d... |
rawenihcam/BER-SERKR | ber_serkr/urls.py | """ber_serkr URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-... |
volpino/Yeps-EURAC | lib/galaxy/model/orm/ext/assignmapper.py | """
This is similar to the assignmapper extensions in SQLAclhemy 0.3 and 0.4 but
with some compatibility fixes. It assumes that the session is a ScopedSession,
and thus has the "mapper" method to attach contextual mappers to a class. It
adds additional query and session methods to the class to support the
SQLAlchemy 0.... |
ahjulstad/mathdom-python3 | mathml/pmathml/mrow.py | from .element import *
from . import mtoken
class MRow(Element):
class Strategy:
def layout(self, elements):
"""Set positions of elements in a row;
Returns (width, height, axis) of row"""
global_axis = 0
max_height_non_stretchy = 0
max_height_stretchy = 0
max_dep... |
laborautonomo/opps | opps/fields/widgets.py | #!/usr/bin/env python
# -*- coding: utf-8 -*
import json
from django import forms
from django.template.loader import render_to_string
from .models import Field, FieldOption
from opps.core.widgets import CONFIG
class JSONField(forms.TextInput):
model = Field
def render(self, name, value, attrs=None):
... |
bjarnoldus/randomcab | src/randomcab/backends/test.py | """
test.py
Copyright 2015 Jeroen Arnoldus <jeroen@repleo.nl>
THIS SOFTWARE IS SUPPLIED WITHOUT WARRANTY OF ANY KIND, AND MAY BE
COPIED, MODIFIED OR DISTRIBUTED IN ANY WAY, AS LONG AS THIS NOTICE
AND ACKNOWLEDGEMENT OF AUTHORSHIP REMAIN.
"""
from django.test import TestCase
from randomcab.backends import ... |
silverlogic/blockhunt-back | blockhunt/hunts/models.py | from django.db import models
from model_utils.models import TimeStampedModel
from blockhunt.users.models import User
class Hunter(User):
balance = models.DecimalField(
max_digits=12, decimal_places=8, default=0,
help_text='The number of bitoins the hunter owns.'
)
coinbase_account_id = m... |
tonygalmiche/is_plastigray | wizard/is_liste_servir_wizard.py | # -*- coding: utf-8 -*-
from openerp.osv import osv, fields
import datetime
import time
#TODO :
# - Creer la table 'is_liste_servir_client
# - Créer une requete pour lister les clients ayant des commandes à livrer sur la periode indiquée
# - Remplir la table avec les données de la requetes
# - Depuis chaque ligne d... |
73VW/AutomaBot | docs/conf.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# automabot documentation build configuration file, created by
# sphinx-quickstart on Thu Jun 8 09:35:26 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# ... |
woutdenolf/spectrocrunch | spectrocrunch/utils/integerbase.py | # -*- coding: utf-8 -*-
class integerbase:
def __init__(
self,
digs=[
"0",
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"A",
"B",
"C",
... |
ryfeus/lambda-packs | pytorch/source/caffe2/python/layers/fc.py | ## @package fc
# Module caffe2.python.layers.fc
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.python import schema
from caffe2.python.layers.layers import ModelLayer
from caffe2.python.layers.sampling_tra... |
sidnarayanan/PandaCore | Tools/python/models.py | from re import sub
from sys import stdout,stderr
from os import getenv
from PandaCore.Utils.logging import logger
from collections import namedtuple
ModelParams = namedtuple('ModelParams',
['m_V','m_DM','gV_DM','gA_DM',
'gV_q','gA_q','sigma','delta'])
def read_nr_mod... |
thombashi/pytablewriter | test/writer/text/test_csv_writer.py | """
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
import collections
import itertools
from textwrap import dedent
import pytest
import pytablewriter as ptw
from ..._common import print_test_result
from ...data import (
float_header_list,
float_value_matrix,
headers,
mix_header_... |
bradkav/AntiparticleDM | calc/CompareNgrid.py | """
CompareNgrid.py
Code for checking the convergence of the grid-based
maximum likelihood calculation.
BJK - 23/06/2017
"""
import sys
import matplotlib.pyplot as pl
from scipy.stats import chi2, norm
import CalcParamPoint as CPP
from CalcLikelihood import *
from WIMpy.Experiment import Experiment
print " "
print ... |
DailyActie/Surrogate-Model | 01-codes/scikit-learn-master/sklearn/metrics/tests/test_classification.py | from __future__ import division, print_function
import warnings
from functools import partial
from itertools import product
import numpy as np
from scipy import linalg
from scipy.spatial.distance import hamming as sp_hamming
from sklearn import datasets
from sklearn import svm
from sklearn.datasets import make_multil... |
rfancn/wxgigo | contrib/admin/core/management/commands/_params.py | #!/usr/bin/env python
# coding=utf-8
"""
Copyright (c) 2010-2015, Ryan Fan <reg_info@126.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the ... |
fadado/shed | tests/turbogears/helloworld/setup.py | # -*- coding: utf-8 -*-
try:
from setuptools import setup, find_packages
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
setup(
name='helloworld',
version='0.1',
description='',
author='',
author_email='',
#url... |
bluestemscott/librarygadget | librarygadget/librarybot/fixtures/testhorizon.py | import unittest
from librarybot import horizon
import datetime
from librarybot import util
from BeautifulSoup import BeautifulSoup
class TestCheckedOut(unittest.TestCase):
def testdesmoines(self):
print "*** Des Moines ***"
f = open("librarybot/fixtures/horizon/desmoines.html", "r")
... |
beetbox/beets | test/test_metasync.py | # This file is part of beets.
# Copyright 2016, Tom Jaspers.
#
# 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, mod... |
rsm5139/learning-bowtie | build/src/server.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import traceback
from functools import wraps
from builtins import bytes
import click
import msgpack
import flask
from flask import Flask, render_template, copy_current_request_context
from flask import request, Response
from flask_socketio import Sock... |
L3K0V/lifebelt | server/api/assignments/models.py | import uuid
from django.db import models
from django.utils import timezone
class CourseAssignment(models.Model):
A = 'A'
B = 'B'
V = 'V'
G = 'G'
ALL = 'ALL'
ASSIGNMENT_TARGET = (
(A, 'A class'),
(B, 'B class'),
(V, 'V class'),
(G, 'G class'),
(ALL, 'ALL... |
Jverma/fastAQ | fastAQ/fastaInfo.py | # -*- coding: utf-8 -*-
# Parsing a fasta file.
# Author - Janu Verma
# jv367@cornell.edu
import sys
from sequenceOperations import SequenceManipulation
from trimming import Trimming
class FastaParser:
"""
Parses a FASTA file to extract the sequences and header information, if any.
Parameters
----------
fasta... |
gdgand/Festi | festi/festi/settings/common.py | """
Django settings for festi project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
import os
from os.path import dirname, join
BASE_DIR = dirname(dirname(dirna... |
Healdb/CoinGoldBot | src/fileHelpers.py | #coding: utf-8
import os
import csv
def delete_line(bad_words, fn):
with open(fn+'.txt') as oldfile, open(fn + '2.txt', 'w+') as newfile:
for line in oldfile:
if not all(bad_word in line for bad_word in bad_words):
newfile.write(line)
newfile.close()
with open(fn + '... |
danblick/robocar | scripts/inotify_example.py | # Alternative:
# $ inotifywait -e CLOSE_WRITE -m /tmp
# Setting up watches.
# Watches established.
# /tmp/ CLOSE_WRITE,CLOSE ok
# /tmp/ CLOSE_WRITE,CLOSE ok
# /tmp/ CLOSE_WRITE,CLOSE ok
import logging
import argparse
import os
import signal
import sys
import inotify.adapters
def handler(signum, frame):
sys.exit(... |
ueg1990/pypoker | pypoker/player.py | '''
This module defines a class for a Player who will play poker in the game engine
'''
from utils import get_player_index, progress, get_max_bet
class Player(object):
'''
This class creates Player objects to play the game
'''
def __init__(self, player_name, chips, table):
self.player_name = player_name
self... |
nikwin/ecsCompiler | compileEcs.py | import click
import os
import re
import json
import csv
import pyparsing
from parseCsv import parseCsvToken
from parseToken import parseToken, DirectEcsRef, DirectConditionEcs
from compileBase import *
class Ecs(object):
def __init__(self, ecs, inherits, asserts, commandHolders, key, calcInherit):
self.e... |
xesscorp/skidl | tests/test_network.py | # -*- coding: utf-8 -*-
# The MIT License (MIT) - Copyright (c) 2016-2021 Dave Vandenbout.
import pytest
from skidl import TEMPLATE, Net, Network, Part, tee
from .setup_teardown import setup_function, teardown_function
def test_ntwk_1():
"""A common-emitter amplifier."""
r1, r2 = Part("Device", "R", dest=... |
auag92/n2dm | Asap-3.8.4/Projects/NanoparticleMC/surface_end.py | #!/usr/bin/env python
#PBS -N Cu1000_se
#PBS -e se.err
#PBS -o se.log
#PBS -m ae
#PBS -q long
#PBS -l nodes=1:ppn=1:opteron4
"""Prepares a finished surface MC simulation for atoms MC by filtering and symmetry elimination.
Usage: cd simparentfolder
python surface_end.py direc Tmc Nleft smc_log_file
where Tmc is the te... |
vahtras/util | util/full.py | """
Matrix utility module based on numpy
"""
import math
import numpy
import scipy.linalg
from . import subblocked, blocked
class Matrix(numpy.ndarray):
"""
A subclass of numpy.ndarray for matrix syntax and better printing
"""
fmt = "%14.8f"
order = "F"
columnsperblock = 5
def __new__(c... |
jajcayn/pyclits | examples/6-mutual_inf_and_surrogates.py | """
Examples for pyCliTS -- https://github.com/jajcayn/pyclits
"""
from datetime import date
import matplotlib
# import modules
import pyclits as clt
import pyclits.mutual_inf as MI
# change for your favourite backend
matplotlib.use('TKAgg')
import numpy as np
## WARNING runs approximately 45min, depending on your... |
nephila/python-taiga | tests/test_search.py | import unittest
from unittest.mock import patch
from taiga import TaigaAPI
from taiga.models import Epic, Issue, Task, UserStory, WikiPage
from .tools import MockResponse, create_mock_json
class TestSearch(unittest.TestCase):
@patch("taiga.requestmaker.RequestMaker.get")
def test_single_user_parsing(self, m... |
xuechong87/JQsimpleWeather | gaepythonCallBack/WeatherProxy.py | from google.appengine.ext import webapp
import urllib2
import logging
class WeatherProxy(webapp.RequestHandler):
def get(self):
logging.info("get")
self.response.headers['Content-Type'] = 'text/javascript'
param = self.request.get
write = self.response.out.write
callBac... |
SGenheden/Scripts | Gromacs/gmx_glycampairs.py | # Author: Samuel Genheden samuel.genheden@gmail.com
"""
Program to make proper Glycam pair parameters for 1-4 neighbours that
acpype.py cannot hanndle
"""
import argparse
import math
from sgenlib import gmx
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Program make Glycam pair params... |
icometrix/dicom2nifti | tests/test_dicom.py | # -*- coding: utf-8 -*-
"""
dicom2nifti
@author: abrys
"""
import os
import shutil
import tempfile
import unittest
import nibabel
import tests.test_data as test_data
import dicom2nifti.convert_dicom as convert_dicom
import dicom2nifti.settings as settings
from dicom2nifti.common import read_dicom_directory
from te... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.