repo_name
stringlengths
5
104
path
stringlengths
4
248
content
stringlengths
102
99.9k
DailyActie/Surrogate-Model
01-codes/OpenMDAO-Framework-dev/openmdao.main/src/openmdao/main/pseudocomp.py
import ast import weakref from numpy import zeros from openmdao.main.array_helpers import flattened_size from openmdao.main.expreval import ConnectedExprEvaluator, _expr_dict from openmdao.main.interfaces import implements, IComponent, IAssembly from openmdao.main.mp_support import has_interface from openmdao.main.pri...
Kinnay/NintendoClients
nintendo/nex/settings.py
import pkg_resources class Settings: TRANSPORT_UDP = 0 TRANSPORT_TCP = 1 TRANSPORT_WEBSOCKET = 2 COMPRESSION_NONE = 0 COMPRESSION_ZLIB = 1 ENCRYPTION_NONE = 0 ENCRYPTION_RC4 = 1 field_types = { "nex.version": int, "nex.client_version": int, "nex.struct_header": int, "nex.pid_si...
emilbjorklund/django-template-shortcodes
shortcodes/parsers/youtube.py
from django.template import Template, Context from django.conf import settings def parse(attrs, tag_contents=None): tag_atts = {} if not 'src' in attrs.keys(): if 'idval' in attrs.keys() and attrs['idval'][:1] == '=': tag_atts['src'] = attrs['idval'][1:] else: tag_atts['src'] = attrs['src'] tag...
aarontuor/antk
antk/core/config.py
from __future__ import print_function import re from antk.core.node_ops import * from antk.lib import termcolor import sys import os import traceback NODE_GLOBALS = globals().copy() def ph_rep(ph): """ Convenience function for representing a tensorflow placeholder. :param ph: A `tensorflow`_ `placeholder...
attm2x/m2x-sample-cleverfaucet
main.py
#!/usr/bin/env python import os import glob import time from datetime import datetime import RPi.GPIO as GPIO from sensors import FlowMeter, OneWireTempSensor #from secrets import MASTER_API_KEY, DEVICE_ID from m2x.client import M2XClient from m2x.utils import to_iso # Initialize M2X Client, change MASTER_API_KEY and...
rossumai/keras-multi-gpu
keras_tf_multigpu/avolkov1/_patch_tf_backend.py
from __future__ import print_function import sys import numpy as np import tensorflow as tf from keras.backend import tensorflow_backend as tfb from keras.backend.tensorflow_backend import ( get_session, is_sparse) import atexit atexit.register(tfb.clear_session) # FIXME: The monkey patch of Function results in ...
gsarma/PyOpenWorm
PyOpenWorm/cell.py
from __future__ import print_function from string import Template import neuroml from .channel import Channel from .biology import BiologyType from .dataObject import DatatypeProperty, ObjectProperty, This from .cell_common import CELL_RDF_TYPE __all__ = ["Cell"] # XXX: Should we specify somewhere whether we have N...
srusskih/SublimeJEDI
dependencies/parso/tree.py
import sys from abc import abstractmethod, abstractproperty from parso._compatibility import utf8_repr, encoding from parso.utils import split_lines def search_ancestor(node, *node_types): """ Recursively looks at the parents of a node and returns the first found node that matches node_types. Returns ``N...
nelsyeung/bgwtools
tests/test_helpers.py
import os import stat from bgwgen import helpers def test_deep_merge(): """deep_merge function returns a single deep merged dictionary.""" original = { '&control': { 'calculation': 'bands', 'prefix': 'MoS2', 'pseudo_dir': '../pseudo', }, 'ATOMIC_SPEC...
085astatine/togetter
togetter/tweet.py
# -*- coding: utf-8 -*- import datetime as _datetime from collections import OrderedDict from typing import Any, Dict import lxml.etree class Tweet(object): def __init__(self, tweet: str, tweet_link: str, user_id: str, user_name: str, ...
7ws/django-setmagic
setmagic/migrations/0003_auto_20140709_1552.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('setmagic', '0002_setting_current_value'), ] operations = [ migrations.RemoveField( model_name='setting', ...
jmakov/market_tia
tia/trad/tools/net/socketio_mtgox.py
from threading import * import urllib2 import urllib import time import traceback import logging from tia.trad.tools.net.websocket_client import create_connection from tia.trad.tools.errf import eReport LOGGER_NAME = "rl." + __file__.split("/")[-1] logger = logging.getLogger(LOGGER_NAME) # don't change! class Sock...
saisai/algorithms_by_other
RMQ/RMQ.py
#!/usr/bin/env python def readNumbers(numberFile, queryFile): with open(numberFile, "r") as f: numbers = list(map(int, f.read().split(" "))) with open(queryFile, "r") as f: queries = list(map(lambda s: list(map(int, s.split(":"))), f.read().split("\n"))) return numbers, queries def execu...
Zing22/Moogle
moogle/moogle/settings.py
# -*- coding=utf8 -*- """ Django settings for moogle project. Generated by 'django-admin startproject' using Django 1.9. For more information on this file, see https://docs.djangoproject.com/en/1.9/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.9/ref/settings...
sunyihuan326/DeltaLab
Andrew_NG_learning/class_four/week_four/FR/fr_utils.py
#### PART OF THIS CODE IS USING CODE FROM VICTOR SY WANG: https://github.com/iwantooxxoox/Keras-OpenFace/blob/master/utils.py #### import tensorflow as tf import numpy as np import os # import cv2 from numpy import genfromtxt from keras.layers import Conv2D, ZeroPadding2D, Activation, Input, concatenate from keras.mod...
TheAlgorithms/Python
dynamic_programming/rod_cutting.py
""" This module provides two implementations for the rod-cutting problem: 1. A naive recursive implementation which has an exponential runtime 2. Two dynamic programming implementations which have quadratic runtime The rod-cutting problem is the problem of finding the maximum possible revenue obtainable from a rod of ...
Azure/azure-sdk-for-python
sdk/sql/azure-mgmt-sql/azure/mgmt/sql/aio/operations/_instance_pools_operations.py
# 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 may ...
rrodakowski/nibbler
nibbler/__main__.py
import argparse from nibbler.nibbler import run_nibbler def main(): parser = argparse.ArgumentParser(prog='nibbler', description='A simple RSS to email application.') parser.add_argument('to_email', metavar='to_email', help='Recipient email address; youremail@example.com') parser.add_argument('from_email...
django-webtest/django-webtest
setup.py
#!/usr/bin/env python import sys from setuptools import setup version = '1.9.9.dev0' def _read(name): if sys.version_info[0] < 3: with open(name) as f: return f.read() else: with open(name, encoding='utf8') as f: return f.read() def get_long_description(): retu...
htetmyet/keyword-extraction
get_summary.py
from nltk.corpus import wordnet as wn from itertools import product from collections import Counter import nltk, re, math def extractNouns(title): NOUNS = ['NN','NNS','NNP','NNPS','PRP','PRP$'] nouns = [] f_nouns = [] prettify_tit = re.sub(r'[^\w.]', ' ', title) text = nltk.word_tokenize(pretti...
jmgilman/Neolib
neolib/exceptions.py
""":mod:`exceptions` -- Provides all exceptions for Neolib .. module:: exceptions :synopsis: Provides all exceptions for Neolib .. moduleauthor:: Joshua Gilman <joshuagilman@gmail.com> """ # General class parseException(Exception): pass class invalidUser(Exception): pass class invalidType(Exception):...
mitschabaude/nanopores
nanopores/physics/pore_dna.py
''' provide default values and functions for calculating physical parameters for a specific physical set-up: nanopore with DNA inside, in this setup moleucle and DNA is the same!!! ''' import dolfin from nanopores.physics.params_physical import * from warnings import warn # 1. -- default values for direct parameter...
edubecks/vaidecaronaorg
caronasbrasilapp/djangoapp/apps/caronasbrasil/model/test.py
# coding: utf-8 __author__ = 'edubecks' from pprint import pprint # # oauth_access_token = facebook.get_app_access_token(config.DEV_FB_APP_ID, config.DEV_FB_APP_SECRET) # oauth_access_token = config.OAUTH_TOKEN # graph = facebook.GraphAPI(oauth_access_token) # profile = graph.get_object('me') # group = graph.get_obj...
mcs07/mongodb-chemistry
mchem/profile.py
# -*- coding: utf-8 -*- """ mchem.profile ~~~~~~~~~~~~~ Functions for benchmarking chemical searches in MongoDB. :copyright: Copyright 2014 by Matt Swain. :license: MIT, see LICENSE file for more details. """ from __future__ import print_function from __future__ import unicode_literals from __future__ import divisio...
PyAbel/PyAbel
examples/example_GUI.py
# -*- coding: iso-8859-1 -*- # Illustrative GUI driving a small subset of PyAbel methods import numpy as np import matplotlib; matplotlib.use('TkAgg') # avoids crash on OSX import matplotlib.pyplot as plt import abel from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg,\ ...
birdage/ooi_speed_checker
get_stats.py
# coding: utf-8 # In[118]: import requests import time import json import numpy as np import datetime # In[119]: def timeRequest(url_req): try: t0 = time.time() res = requests.get(url_req,timeout=20) print res.status_code t1 = time.time() time_seconds = t1-t0 exc...
3lnc/go.py
Vector2D.py
from math import hypot class Vector2d(object): def __init__(self, x, y): self._x = x self._y = y def __repr__(self): return "Vector2d({}, {})".format(self._x, self._y) def __add__(self, other): if not isinstance(other, Vector2d): return NotImplemented return Vector2d(self._x + other._x, self._y + oth...
Adriel-M/HackerRank
Learn/30-Days-Of-Code/Day 25/isprime.py
def is_prime(n): if n <= 1: return False elif n <= 3: return True elif n % 2 == 0 or n % 3 == 0: return False i = 5 while i * i <= n: if n % i == 0 or n % (i + 2) == 0: return False i += 6 return True T = int(input()) for _ in range(T): if...
alvaromorales/whoami
whoami/spacypos.py
from spacy import parts_of_speech as pos def is_adposition(node): return node.pos == pos.ADP def is_noun(node): return node.pos in [pos.NOUN, pos.PROPN] def is_adjective(node): return node.pos == pos.ADJ def is_verb(node): return node.pos == pos.VERB def is_number(node): return node.pos ==...
mattbarton/horla
books/process.py
from __future__ import division import nltk, codecs, re # use nltk.download() to install the nltk punkt package clause_re = re.compile('(.{30,}?), ') def pieces(s): if len(s) > 50: clauses = clause_re.split(s) clauses = [c for c in clauses if c != ''] return ',\n'.join(clauses) else: ...
Tigge/antfs-cli
scripts/40-upload_to_garmin_connect.py
#!/usr/bin/env python # # Code by Tony Bussieres <t.bussieres@gmail.com> # Updated by Bastien Abadie <bastien@nextcairn.com> # inspired by 40-convert_to_tcx.py by Gustav Tiger <gustav@tiger.name> # # This helper uses garmin-uploader to send the fit files to Garmin Connect # # To install garmin-uploader # # sudo pip ins...
anbangleo/NlsdeWeb
Python-3.6.0/Lib/test/test_exceptions.py
# Python test set -- part 5, built-in exceptions import os import sys import unittest import pickle import weakref import errno from test.support import (TESTFN, captured_stderr, check_impl_detail, check_warnings, cpython_only, gc_collect, run_unittest, no_tracing, ...
efiring/UTide
tests/test_periodogram.py
""" Tests for periodogram module. """ from __future__ import (absolute_import, division, print_function) import numpy as np import utide.periodogram as pgram def random_ts(ndays, dt_hours, complex=True): """Returns t (time in days) and x (random series).""" np.random.seed(1) npts = ndays * 24 / dt_hours...
dionysio/django_upwork_portfolio
base/utils.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import datetime import logging from django.core.cache import cache logger = logging.getLogger(__name__) pretty_names = {'amazon-web-services': 'Amazon Web Services', 'api-development': 'API Development', 'django-framework': 'Django', 'elasticsearch': 'E...
doylew/practice
python/l6/stats.py
import math def order(a_list, k): a_list.sort() return a_list[k] def median(a_list): a_list.sort() length = len(a_list) if length % 2 == 0: return a_list[length/2] return a_list[int(length/2 + 1)] def mode(a_list): myMode = {} for a in a_list: if str(a) in my...
triposorbust/masseuse
res/generate.py
#!/usr/bin/env python import datetime import numpy as np def standard(n): return np.random.normal(0,1,n) def main(number, length, density=0.05): offset = 0 values = standard(length) while number > 0: if np.random.random() <= density: date = datetime.date.today() + datetime.timedel...
ParrotPrediction/pyalcs
tests/lcs/agents/xncs/test_Effect.py
import pytest from lcs.agents.xncs import Effect class TestEffect: def test_init(self): ef = Effect("########") assert len(ef) == 8 assert all(item == "#" for item in ef) @pytest.mark.parametrize("cond1, cond2, result", [ ("1111", "1111", True), ("11##", "1111", True...
coll-gate/collgate
server/audit/history.py
# -*- coding: utf-8; -*- # # @file Value history for an entity # @brief collgate # @author Frédéric SCHERMA (INRA UMR1095) # @date 2017-11-14 # @copyright Copyright (c) 2017 INRA/CIRAD # @license MIT (see LICENSE file) # @details import json import validictory from django.contrib.contenttypes.models import ContentTy...
trentm/eol
test/test_eol.py
#!/usr/bin/env python # Copyright (c) 2010 ActiveState Software Inc. # License: MIT (http://www.opensource.org/licenses/mit-license.php) import os import sys from pprint import pprint import unittest import doctest from testlib import TestError, TestSkipped, tag class DocTestsTestCase(unittest.TestCase): def te...
lixxu/sanic
tests/test_exceptions_handler.py
from sanic import Sanic from sanic.response import text from sanic.exceptions import InvalidUsage, ServerError, NotFound from sanic.handlers import ErrorHandler from bs4 import BeautifulSoup exception_handler_app = Sanic("test_exception_handler") @exception_handler_app.route("/1") def handler_1(request): raise I...
axonchisel/ax_metrics
py/axonchisel/metrics/foundation/data/multi.py
""" Ax_Metrics - Container for multiple DataSeries ------------------------------------------------------------------------------ Author: Dan Kamins <dos at axonchisel dot net> Copyright (c) 2014 Dan Kamins, AxonChisel.net """ # ---------------------------------------------------------------------------- from axon...
ihidalgo/uip-prog3
Laboratorios/Quiz2.py
#CLASE 3 quiz 2 #Autor: Ivan Hidalgo monto=float(input("ingrese el valor del monto: ")) if monto>= 500: descuento = monto * 0.30 monto= monto - descuento elif monto>=200 and monto<500: descuento = monto * 0.20 monto=monto-descuento elif monto>=100 and monto<200: descuento = monto * 0.10 mon...
johnnytorres83/twitterlc
code/topics.py
# -*- coding: utf-8 -*- def processfile(inputfile, bUseWeights): # prepare tokens creator tokenizer = RegexpTokenizer(r'\w+') # create English stop words list es_stop = get_stop_words(language) # create p_stemmer of class PorterStemmer p_stemmer = SnowballStemmer(language) ...
Mikejinhua/UnitySocketProtobuf3Demo
Tools/TableCode/cs_file.py
from const import cs_table_file_dir def GenCSTableManagerFile(tableName, fieldsIndex, table): filePath = cs_table_file_dir + tableName + ".cs" fileContent = "" fileContent += \ 'using System.Collections.Generic;\n'\ 'using System.IO;\n'\ 'using System.Text;\n'\ 'using UnityEngine;\n'\ ...
TwigWorld/django-url-mapper
urlmapper/settings.py
from django.conf import settings from django.core.exceptions import ImproperlyConfigured _DEFAULT_URLMAPPER_ALLOWED_MAPPINGS = ['url', 'object', 'view_name'] URLMAPPER_RAISE_EXCEPTION = getattr(settings, 'URLMAPPER_RAISE_EXCEPTION', True) URLMAPPER_KEYS = getattr(settings, 'URLMAPPER_KEYS', []) URLMAPPER_FUNCTIONS...
AndreasMadsen/course-02456-sparsemax
benchmark/table.py
import itertools import numpy as np import scipy.stats class Table: def __init__(self, content, col_names, row_names): self.content = content self.col_names = col_names self.row_names = row_names def __str__(self): output = '' # print header format_header = ...
miguelgrinberg/python-engineio
src/engineio/static_files.py
content_types = { 'css': 'text/css', 'gif': 'image/gif', 'html': 'text/html', 'jpg': 'image/jpeg', 'js': 'application/javascript', 'json': 'application/json', 'png': 'image/png', 'txt': 'text/plain', } def get_static_file(path, static_files): """Return the local filename and conten...
fujy/ROS-Project
src/rbx1/rbx1_apps/nodes/object_tracker.py
#!/usr/bin/env python """ object_tracker.py - Version 1.1 2013-12-20 Rotate the robot left or right to follow a target published on the /roi topic. Created for the Pi Robot Project: http://www.pirobot.org Copyright (c) 2012 Patrick Goebel. All rights reserved. This program is free softw...
jumoconnect/openjumo
jumodjango/etc/templatetags/disqus_tags.py
from django import template from django.conf import settings from lib.disqus import get_sso_auth from issue.models import Issue from org.models import Org from users.models import User ''' required context for template: # general disqus config forum_shortname (settings) dev...
buntyke/GPy
GPy/plotting/matplot_dep/visualize.py
import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import GPy import numpy as np import matplotlib as mpl import time from GPy.core.parameterization.variational import VariationalPosterior try: import visual visual_available = True except ImportError: visual_available = False class d...
Sorsly/subtle
google-cloud-sdk/lib/googlecloudsdk/core/util/platforms.py
# Copyright 2013 Google Inc. 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 applicable law or ag...
yugangw-msft/azure-cli
src/azure-cli/azure/cli/command_modules/advisor/custom.py
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # --------------------------------------------------------------------...
GhostScientist/terminal_todo
todo.py
# This is a to-do application intended to be used on the command line. # This first iteration is merely a self-containing to-do program. # Once the program ends, all information is lost. # Created by Dakota Kim. import sys import sqlite3 import os import time from itertools import chain pwd = os.getcwd() # Returns t...
rickiepark/tfk-notebooks
urban-sound-classification/feature_merge.py
import glob import numpy as np X = np.empty((0, 193)) y = np.empty((0, 10)) groups = np.empty((0, 1)) npz_files = glob.glob('./urban_sound_?.npz') for fn in npz_files: print(fn) data = np.load(fn) X = np.append(X, data['X'], axis=0) y = np.append(y, data['y'], axis=0) groups = np.append(groups, dat...
fusionapp/documint
documint/extproc/neon.py
from functools import partial from tempfile import mkstemp from twisted.python.filepath import FilePath from documint.errors import RemoteExternalProcessError from documint.extproc.common import getProcessOutput, sanitizePaths, which _neonBinary = partial(which, 'clj-neon') def failingPDFSign(*a, **kw): """...
DalenWBrauner/FloridaDataOverlay
Website/Florida_Data_Overlay/Overlay/migrations/0001_initial.py
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Births' db.create_table(u'Overlay_births', ( ...
ClimateImpactLab/DataFS
datafs/config/helpers.py
from datafs.config.config_file import ConfigFile from datafs.config.constructor import APIConstructor from datafs._compat import open_filelike import os import re import click def _parse_requirement(requirement_line): # should we do archive name checking here? If the statement # doesn't split, the entire t...
zhangmhao/crawl-house
prototype/simpleSpider.py
from html.parser import HTMLParser from urllib.request import urlopen from urllib import parse # We are going to create a class called LinkParser that inherits some # methods from HTMLParser which is why it is passed into the definition class LinkParser(HTMLParser): # This is a function that HTMLParser normally h...
mattr555/AtYourService
main/management/commands/email_tasks.py
from django.core.management.base import NoArgsCommand from django.db import connection from django.utils import timezone from django.template.loader import render_to_string from django.conf import settings from django.core.mail import EmailMultiAlternatives from datetime import timedelta from main.models import Event f...
DailyActie/Surrogate-Model
01-codes/scikit-learn-master/benchmarks/bench_isolation_forest.py
""" ========================================== IsolationForest benchmark ========================================== A test of IsolationForest on classical anomaly detection datasets. """ print(__doc__) from time import time import matplotlib.pyplot as plt import numpy as np from sklearn.datasets import fetch_kddcup...
SurfasJones/icecream-info
icecream/lib/python2.7/site-packages/cms/utils/plugins.py
# -*- coding: utf-8 -*- from collections import defaultdict from itertools import groupby import operator import warnings from django.contrib.sites.models import Site, SITE_CACHE from django.shortcuts import get_object_or_404 from django.template import NodeList, VariableNode, TemplateSyntaxError from django.template....
wizyoung/workflows.kyoyue
ss.py
# coding: utf-8 import argparse from PIL import Image import qrcode import os import re parser = argparse.ArgumentParser() parser.add_argument('query', nargs='?', default=None) args = parser.parse_args() query = args.query.split('bound')[0] qr = qrcode.QRCode( version=1, error_correction=qrcode.constants.ERRO...
dajusc/trimesh
tests/test_off.py
""" Load all the meshes we can get our hands on and check things, stuff. """ try: from . import generic as g except BaseException: import generic as g class OFFTests(g.unittest.TestCase): def test_comment(self): # see if we survive comments m = g.get_mesh('comments.off', process=False) ...
HugoPouliquen/lzw-tools
menu_cli.py
# -*- coding: utf-8 -*- import curses from curses.textpad import Textbox, rectangle from libs.curses_browser import open_tty from libs.curses_browser import restore_stdio from libs.curses_browser import main from utils.compression import compress from utils.compression import fileCompression from utils.decompression im...
gsvic/fmriFlow
utils.py
import nibabel as nbl import pickle import ast import matplotlib.pyplot as plt def readNifti(path): return nbl.load(path).get_data() def visualizeNifti(path, t, slice): data = nbl.load(path).get_data() n = len(data[0,0,0,:]) series = [data[:,:,:,i] for i in range(0,n)] plt.imshow(series[t][sli...
Hornobster/Numpy-Neural-Net
gradient_check.py
#!/usr/local/bin/python import numpy as np from layers import * from nn import * # constants epsilon = 0.0001 ''' Tests the analytical gradient computed in the backward pass of the SoftmaxCrossEntropyLoss layer against the numerical gradient ''' def testSoftmaxCrossEntropyLoss(): # create input layers X = Inp...
ritashugisha/scrab
scrab/meta/serializable.py
#!/usr/bin/env python # -*- encoding: utf-8 -*- # # Copyright (c) 2016 Stephen Bunn <ritashugisha> # MIT License <https://opensource.org/licenses/MIT> """ serializable .. module:: meta :platform: Linux, MacOSX, Win32 :synopsis: :created: 2016-10-07T09:54:57-04:00 .. moduleauthor:: Stephen Bunn <ritashugish...
pdsteele/DES-Python
ssq2.py
# ------------------------------------------------------------------------- # * This program - an extension of program ssq1.c - simulates a single-server # * FIFO service node using Exponentially distributed interarrival times and # * Uniformly distributed service times (i.e. a M/U/1 queue). # * # * Name ...
smowden/b3ef-Battlefield-3-RCON-autoadmin-framework
handlers/announcer.py
import threading import time import uuid class Announcer(threading.Thread): def __init__(self, actionHandler): self.messageQueue=[] self.actionHandler=actionHandler self.currentMessageIndex=0 self.pause=False threading.Thread.__init__(self) def addMessages(self, mes...
patrick91/pycon
backend/pretix/tests/test_create_order.py
import pytest from django.test import override_settings from django.utils import timezone from pretix import ( CreateOrderHotelRoom, CreateOrderInput, CreateOrderTicket, CreateOrderTicketAnswer, InvoiceInformation, create_hotel_positions, create_order, ) from pretix.exceptions import PretixE...
thoas/i386
src/milkshape/application/internals/profiles/models.py
from django.db import models from django.contrib.auth.models import User from django.utils.translation import ugettext_lazy as _ from django.conf import settings from django.db.models.signals import post_save class Profile(models.Model): user = models.ForeignKey(User, unique=True, verbose_name=_('user'), related_...
bellowsj/aiopogo
aiopogo/connector.py
from aiohttp.connector import Connection, helpers, TCPConnector, _TransportPlaceholder, ClientConnectorError class TimedConnection(Connection): def __init__(self, *args, time=None, **kwargs): super().__init__(*args, **kwargs) self._time = time or self._loop.time() def release(self): s...
elijweiss/Tn-seq
python/process_map.py
#!/usr/bin/env python # Purpose: Run the Tn-seq mapping pipeline. Produces files # listing reads per location. The output files can be fed # to the annotation script for analysis. # # Copyright (c) 2014 University of Washington #----------------------------------------------------- # modules #-------------------------...
thespacedoctor/sherlock
sherlock/imports/ifs.py
#!/usr/local/bin/python # encoding: utf-8 """ *Import Multi Unit Spectroscopic Explorer (MUSE) IFS galaxy stream into sherlock-catalogues database* :Author: David Young """ from __future__ import print_function import sys import os os.environ['TERM'] = 'vt100' import readline import glob import pickle import codec...
danieljohnlewis/pisces
pisces/asn1.py
"""A parser for ASN1 object encoded using BER The doc string just sketches the names of objects in the module. Consult the documentation for more details. Burton S. Kaliski Jr. wrote a helpful introduction to ASN.1 and the BER encoding titled 'A Layman's Guide to a Subset of ASN.1, BER, and DER.' It is available fro...
freeitaly/Trading-System
vn.trader/ctaAlgo/uiStrategyWindow.py
# encoding: UTF-8 import psutil import uiBasicWidget from PyQt4 import QtGui uiBasicWidget.BASIC_FONT = QtGui.QFont(u'微软雅黑', 10) from uiBasicWidget import * # from ctaAlgo.uiCtaWidget import CtaEngineManager from ctaAlgo.uiCtaWidget import CtaEngineManager2 # from dataRecorder.uiDrWidget import DrEngineManager from r...
kdechant/eamon
adventure/migrations/0009_adventure_slug.py
# -*- coding: utf-8 -*- # Generated by Django 1.9.2 on 2016-03-24 06:15 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('adventure', '0008_auto_20160320_2237'), ] operations = [ migrations.AddField...
MalloyPower/parsing-python
front-end/testsuite-python-lib/Python-3.6.0/Lib/test/test_site.py
"""Tests for 'site'. Tests assume the initial paths in sys.path once the interpreter has begun executing have not been removed. """ import unittest import test.support from test.support import captured_stderr, TESTFN, EnvironmentVarGuard import builtins import os import sys import re import encodings import urllib.re...
pandeylab/pyquant
pyquant/reader.py
import copy import numpy as np from datetime import datetime, timedelta from multiprocessing import Process from pythomics.proteomics.parsers import GuessIterator from .logger import logger class Reader(Process): def __init__(self, incoming, outgoing, raw_file=None, spline=None, rt_window=None, timeout_minutes=5...
laulysta/nmt_transformer
transformer/Modules.py
import torch import torch.nn as nn import torch.nn.init as init import numpy as np __author__ = "Yu-Hsiang Huang" class Linear(nn.Module): ''' Simple Linear layer with xavier init ''' def __init__(self, d_in, d_out, bias=True): super(Linear, self).__init__() self.linear = nn.Linear(d_in, d_out...
ewels/genomics-status
status/production.py
""" Handlers related to data production. """ from collections import OrderedDict import cStringIO from datetime import datetime import json from dateutil import parser import matplotlib.pyplot as plt from matplotlib.backends.backend_agg import FigureCanvasAgg import tornado.web from status.util import dthandler, Saf...
mkobos/tree_crawler
concurrent_tree_crawler/abstract_cmdln_navigators_creator.py
import argparse class AbstractCmdLnNavigatorsCreator: def fill_parser(self, parser): """ Fill the given parser object with command-line arguments needed to initialize navigators which are created in L{create} method. @type parser: L{argparse.ArgumentParser} """ raise NotImplementedError() def create(s...
linsalrob/PhageHosts
code/blast_hits.py
''' Report either the best hits, best equal hits or all hits from a blast search. FOR THIS VERSION WE ARE USING THE BLAST WITH TAXID ADDED AT THE END OF THE LINE (e.g. from GI to TAX) Note that we use the HIGHEST bit score here for this calculation. We generate a table of [phage NC_ id, host tax id]. We need to r...
piotroxp/scibibscan
scib/lib/python3.5/site-packages/astropy/io/fits/verify.py
# Licensed under a 3-clause BSD style license - see PYFITS.rst from __future__ import unicode_literals import warnings from ...extern.six import next from ...utils import indent from ...utils.exceptions import AstropyUserWarning class VerifyError(Exception): """ Verify exception class. """ class Verif...
ajing/SIFTS.py
PDBInfo/DSSPTest.py
''' Just for testing ''' from Bio.PDB import PDBParser from Bio.PDB import DSSP def TestDSSP(model, pdbfile): dssp = DSSP(model, pdbfile) resinfo = [] #for res in model.get_residues(): # print res for residue in dssp: resinfo = residue[0] second_str = residue[1] ssa ...
pauldeden/benchline
benchline/jaxrs_ws_counter.py
#!/usr/bin/env python # # Author: Paul D. Eden <paul@benchline.org> # Created: 2014-05-13 """ Script to count the number of JAX-RS web services defined in .java files in a directory. """ import re import os import fnmatch import six import benchline.args def read_in_file(file_name): """Return the contents of fi...
eblot/miscripts
Python/hardware/spirit1/hparse.py
#!/usr/bin/env python3 """Simple C header file parser to extract useful constants from ST mess.""" from re import compile as recompile from sys import argv CRE = recompile(r'^#define\s+(?P<name>\w+)\s+\(+(?P<value>0x[0-9A-F]{2})\)+' r'(?:\s/\*\!<\s*(?P<comment>.*?)\s*(?:\*/)?)?$') CRE = recompile(...
7digital/grafana-graphite-server-cookbook
files/default/graphite-web-configs/local_settings.py
## Graphite local_settings.py # Edit this file to customize the default Graphite webapp settings # # Additional customizations to Django settings can be added to this file as well ##################################### # General Configuration # ##################################### # Set this to a long, random unique s...
marcwebbie/pycis
pycis/items.py
""" This module represent the base classes for wrappers sending information to interfaces classes: Stream Media """ class Stream(object): """ Stream objects contains info to extracting downloading stream """ def __init__(self, id, host, url): self.id = id self.host = host se...
mattgrogan/ledmatrix
image_processing.py
from PIL import Image im = Image.open("C:\Users\Matt\Documents\GitHub\ledmatrix\icons\moma_emoji.jpg") pix = im.load() w, h = im.size y = 564 x_step = 5 y_step = 5 color = (0, 0, 0) for x in range(w): for y in range(h): if x / x_step % 4 == 0 and y / y_step % 4 == 0: color = (255, 0, 0) else: ...
arnavd96/Cinemiezer
myvenv/lib/python3.4/site-packages/music21/demos/smt2010.py
# -*- coding: utf-8 -*- #------------------------------------------------------------------------------- # Name: smt2010.py # Purpose: Demonstrations for the SMT 2010 poster session # # Authors: Christopher Ariza # Michael Scott Cuthbert # # Copyright: Copyright © 2009-10, 2014 Michae...
meraki-analytics/cassiopeia
examples/leagues.py
import cassiopeia as cass from cassiopeia.data import Queue, Position from cassiopeia.core import Summoner def print_leagues(summoner_name: str, region: str): summoner = Summoner(name=summoner_name, region=region) print("Name:", summoner.name) print("ID:", summoner.id) # entries = cass.get_league_ent...
embotech/forcesnlp-examples
path_planning/ipopt/pathplanning.py
import sys sys.path.append(r"/home/andrea/casadi-py27-np1.9.1-v2.4.3") from casadi import * from numpy import * from scipy.linalg import * import matplotlib matplotlib.use('Qt4Agg') import matplotlib.pyplot as plt from math import atan2, asin import pdb N = 50 # Control discretization T = 5.0 # End time nx = ...
jiadaizhao/LeetCode
0601-0700/0690-Employee Importance/0690-Employee Importance.py
# Employee info class Employee: def __init__(self, id, importance, subordinates): # It's the unique id of each node. # unique id of this employee self.id = id # the importance value of this employee self.importance = importance # the id of direct subordinates ...
IdeaSolutionsOnline/ERP4R
core/objs/caixa.py
# !/usr/bin/env python3 # -*- encoding: utf-8 -*- """ ERP+ """ __author__ = 'António Anacleto' __credits__ = [] __version__ = "1.0" __maintainer__ = "António Anacleto" __status__ = "Development" __model_name__ = 'caixa.Caixa' import auth, base_models from orm import * from form import * try: from my_terminal import...
nicksergeant/finisht
urls.py
from django.views.generic.simple import direct_to_template from django.contrib.auth.views import * from django.conf.urls.defaults import * from django.conf import settings from django.contrib import admin from finisht.views import * admin.autodiscover() urlpatterns = patterns('', url(r'^admin/', include(admin.sit...
plotly/plotly.py
packages/python/plotly/plotly/graph_objs/table/_legendgrouptitle.py
from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType import copy as _copy class Legendgrouptitle(_BaseTraceHierarchyType): # class properties # -------------------- _parent_path_str = "table" _path_str = "table.legendgrouptitle" _valid_props = {"font", "text"} #...
Azure/azure-sdk-for-python
sdk/machinelearning/azure-mgmt-guestconfig/azure/mgmt/guestconfig/aio/operations/_guest_configuration_hcrp_assignments_operations.py
# 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 may ...
okfde/handelsregister-backup
config.py
# encoding: utf8 # The path/file name of our local SQLite database. # If it doesn't exist, the database file will be # generated upon startup. # DB_PATH = 'orgdata.db' # The number range to be searched # MIN_REGISTER_NUMBER = 1 MAX_REGISTER_NUMBER = 500000 # minimum and maximum time to wait between requests # WAIT_M...
jonathf/chaospy
chaospy/distributions/collection/trunc_normal.py
"""Truncated normal distribution.""" import numpy from scipy import special from scipy.stats import truncnorm import chaospy from .normal import normal from ..baseclass import SimpleDistribution, ShiftScaleDistribution class trunc_normal(SimpleDistribution): def __init__(self, lower=-1, upper=1, mu=0, sigma=1):...