code
stringlengths
2
1.05M
repo_name
stringlengths
5
104
path
stringlengths
4
251
language
stringclasses
1 value
license
stringclasses
15 values
size
int32
2
1.05M
from pprint import pprint from django import forms from base.forms.custom import O2BaseForm from base.forms.fields import ( O2FieldCorForm, O2FieldModeloForm, O2FieldRefForm, ) class InfAdProdForm(forms.Form): pedido = forms.CharField( label='Pedido', widget=forms.TextInput(attrs={'t...
anselmobd/fo2
src/contabil/forms.py
Python
mit
4,534
from pprint import pprint import lotes.models def where_ende_disponivel(campo): filter_local = "" end_disp = list(lotes.models.EnderecoDisponivel.objects.filter(disponivel=True).values()) if len(end_disp) != 0: filter_end = """-- AND l.local ~ '^(""" filter_sep = "" f...
anselmobd/fo2
src/cd/queries/functions.py
Python
mit
898
from dataclasses import dataclass import io import typing as T import numpy as np @dataclass(frozen=True) class PolygonShape: vertices: T.Tuple[T.Tuple[float]] color: T.Text @dataclass(frozen=True) class Body: x: float y: float angle: float shapes: T.Tuple[PolygonShape] @dataclass(frozen=...
DouglasOrr/Snippets
hover/hover/render.py
Python
mit
1,552
""" progressbar2 related utils""" from codekit.codetools import warn from public import public from time import sleep import progressbar import functools @public def setup_logging(verbosity=0): """Configure progressbar sys.stderr wrapper which is required to play nice with logging and not have strange format...
lsst-sqre/sqre-codekit
codekit/progressbar.py
Python
mit
2,070
import os import shutil def pre_read(dir): try: filelist = os.listdir(dir) for file in filelist: if os.path.isdir(file): # exception directory if str(file) == 'webMager' or str(file) == '_site': continue ...
MaximumRoot/MaxRootWeb
webMaker/maxrootweb.py
Python
mit
718
#!/usr/bin/env python from sys import argv, stderr usage = \ """ Usage: {program} <sample rate> <A4 freq.> [octaves=8] e.g.: {program} 64000 442.0 5 """.format(program=argv[0]) if len(argv) < 3 or len(argv) > 4 : print(usage, file = stderr) exit(1) A4 = 0 sample_rate = 0 octaves = 8 try: A4 = float(argv...
bardes/sonitus
tools/tone_gen.py
Python
mit
1,271
from __future__ import print_function __author__ = 'breddels' # import astropy.vo.samp as sampy import platform import vaex.utils import sys import threading import vaex.export import vaex.utils import vaex.promise import vaex.settings import vaex.remote import psutil from vaex.parallelize import parallelize from vae...
maartenbreddels/vaex
packages/vaex-ui/vaex/ui/main.py
Python
mit
89,877
# -*- coding: utf-8 -*- # Get rid of "FormatSerializer:Method 'create' is abstract in class 'BaseSerializer' but is not overridden" # FormatSerializer is read only anyway # pylint: disable=abstract-method from __future__ import unicode_literals from rest_framework import serializers from rest_framework.reverse import...
hsr-ba-fs15-dat/opendatahub
src/main/python/hub/serializers.py
Python
mit
6,460
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'reactiongameui.ui' # # Created by: PyQt5 UI code generator 5.8.2 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_Form(object): def setupUi(self, Form): Form.setObject...
tabsoverspaces/ReactionGame
scripts/bracket_ui.py
Python
mit
32,901
"""Tornado handlers for kernel specifications. Preliminary documentation at https://github.com/ipython/ipython/wiki/IPEP-25%3A-Registry-of-installed-kernels#rest-api """ # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. import glob import json import os pjoin = os.p...
bdh1011/wau
venv/lib/python2.7/site-packages/notebook/services/kernelspecs/handlers.py
Python
mit
2,798
#!/usr/bin/env python """Test template support in VTK-Python VTK-python decides which template specializations to wrap according to which ones are used in typedefs and which ones appear as superclasses of other classes. In addition, the wrappers are hard-coded to wrap the vtkDenseArray and vtkSparseArray classe...
timkrentz/SunTracker
IMU/VTK-6.2.0/Common/DataModel/Testing/Python/TestTemplates.py
Python
mit
4,490
import tornado.ioloop #!! this example requires the file /test/setting.py with the folowing constants is created from awsutils.tornado.sqsclient import SQSClient from test.settings import access_key, secret_key sqsclient = SQSClient(endpoint='sqs.us-east-1.amazonaws.com', access_key=access_key, secret_key=secret_key...
sanyi/awsutils
examples/tornado-sqs.py
Python
mit
536
# -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # http://doc.scrapy.org/en/latest/topics/items.html import scrapy class TripadItem(scrapy.Item): # define the fields for your item here like: # name = scrapy.Field() pass
acehanks/projects
tripadvisor_scrapy/tripad/items.py
Python
mit
285
import os from qmpy import * from django.test import TestCase peak_locations = [] class MiedemaTestCase(TestCase): def setUp(self): read_elements() def test_methods(self): ## test that it generally works self.assertEqual(Miedema("FeNi").energy, -0.03) self.assertEqual(Miedem...
wolverton-research-group/qmpy
qmpy/analysis/tests.py
Python
mit
1,996
#!/usr/bin/env python # -*- coding:utf-8 -*- import sys import argparse import collections from functools import wraps import logging # We are assuming, that there is an already configured logger present logger = logging.getLogger(__name__) class CommandLine(object): """Create a command line interface for the...
hastern/jelly
cli.py
Python
mit
3,654
import re from .common import InfoExtractor class GamekingsIE(InfoExtractor): _VALID_URL = r'http://www\.gamekings\.tv/videos/(?P<name>[0-9a-z\-]+)' _TEST = { u"url": u"http://www.gamekings.tv/videos/phoenix-wright-ace-attorney-dual-destinies-review/", u'file': u'20130811.mp4', # MD5 ...
Grassboy/plugin.video.plurkTrend
youtube_dl/extractor/gamekings.py
Python
mit
1,331
import collections import re #imports class Jison:#extends symbols = {} terminals = {} productions = {} table = {} default_actions = {} version = '0.3.12' debug = False action_none = 0 action_shift = 1 action_deduce = 2 action_accept = 3 unput_stack = [] def trace(self): """trace""" def __init__(s...
Bovid/Bovid.python
template.py
Python
mit
7,644
class Printer: def __init__(self): self._output = '' def print_output(self, output): self._output += output def print_line(self, x1, y1, x2, y2, color=0, width=1): self.print_output(_svg_line(x1, y1, x2, y2, color=color, width=width)) def print_circle(self, x, y, r, color=0, ...
adaptive-learning/proso-apps
proso/svg.py
Python
mit
2,180
import pytest from flask_httpauth import HTTPBasicAuth from kapsi_git_manager.kgm import app from kapsi_git_manager import authentication as auth password = "password" username = "username" def test_auth_simple(): """ this is the idiot test to check whether anything in you auth system works. """ assert is...
hanshoi/kapsi-git-manager
tests/test_authentication.py
Python
mit
761
# -*- coding: iso-8859-1 -*- ur"""AsyncIO objects wrap the Win32 Overlapped API. They are instantiated by passing a handle which has been opened for Overlapped IO. They can be waited on by the functions in the :mod:`ipc` module and are True when complete, False otherwise. """ import pywintypes import winerror i...
one2pret/winsys
winsys/asyncio.py
Python
mit
2,311
import asyncio import demjson from bot import user_steps, sender, get, downloader from message import Message client_id = ''#YOUR CLIENT ID async def search(query): global guest_client_id search_url = 'https://api.soundcloud.com/search?q=%s&facet=model&limit=30&offset=0&linked_partitioning=1&client_id='+c...
siyanew/Siarobo
plugins/soundcloud.py
Python
mit
3,323
""" Anonymous token-based surveys """
nmoutschen/tsurvey
src/tsurvey/__init__.py
Python
mit
38
# coding=utf-8 """ moderation plugin for DecoraterBot. """ import regex import discord from discord.ext import commands from DecoraterBotUtils import utils # This module's warn, and mute commands do not work for now. # I would like it if someone would help me fix them and pull # request the fixtures to this file to ...
DecoraterBot-devs/DecoraterBot-cogs
moderation.py
Python
mit
12,660
__all__ = ['pwnedapi', 'utils'] from .pwnedapi import HaveIBeenPwnedApi
ericfourrier/pwnedapi
pwnedapi/__init__.py
Python
mit
72
# -*- coding: utf-8 -*- __version__ = '0.0.1' __license__ = 'MIT'
adebarbara/olpy
olpy/__init__.py
Python
mit
67
from twisted.trial import unittest from twistedchecker.checkers.docstring import DocstringChecker class DocstringTestCase(unittest.TestCase): """ Test for twistedchecker.checkers.docstring """ def test_getLineIndent(self): """ Test of twistedchecker.checkers.docstring._getLineIndent...
twisted/twistedchecker
twistedchecker/test/test_docstring.py
Python
mit
678
from tilequeue.query.fixture import make_fixture_data_fetcher from tilequeue.query.pool import DBConnectionPool from tilequeue.query.postgres import make_db_data_fetcher from tilequeue.query.rawr import make_rawr_data_fetcher from tilequeue.query.split import make_split_data_fetcher from tilequeue.process import Source...
mapzen/tilequeue
tilequeue/query/__init__.py
Python
mit
6,789
"""empty message Revision ID: 4986e64643f4 Revises: 175003d01257 Create Date: 2015-04-15 12:16:41.965765 """ # revision identifiers, used by Alembic. revision = '4986e64643f4' down_revision = '175003d01257' from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql def upgrade(): ...
justinwp/croplands
migrations/versions/4986e64643f4_.py
Python
mit
1,023
from django.db.backends.mysql.compiler import SQLCompiler as BaseSQLCompiler from django.db.backends.mysql.compiler import SQLInsertCompiler, \ SQLDeleteCompiler, SQLUpdateCompiler, SQLAggregateCompiler, \ SQLDateCompiler, SQLDateTimeCompiler class SQLCompiler(BaseSQLCompiler): STRAIGHT_INNER = 'STRAIGHT_...
frol/django-mysql-fix
django_mysql_fix/backends/mysql/compiler.py
Python
mit
5,170
#!/usr/bin/env python3 # https://www.hackerrank.com/challenges/class-2-find-the-torsional-angle import io import math import sys import unittest class Vector: def __init__(self, x, y, z): self.x = x self.y = y self.z = z def subtract(self, other): x = self.x - other.x ...
altermarkive/Coding-Interviews
algorithm-design/hackerrank/class_2_find_the_torsional_angle/test_class_2_find_the_torsional_angle.py
Python
mit
2,023
from app import create_app app = create_app() if __name__ == "__main__": app.run(host="0.0.0.0", port=5000, debug=True)
defshine/cleanblog
run.py
Python
mit
127
# -*- coding: utf-8 -*- from __future__ import print_function from collections import OrderedDict import numpy as np import six from acq4.devices.DAQGeneric.taskGUI import DAQGenericTaskGui from acq4.devices.Device import Device, DeviceTask from pyqtgraph import siFormat from pyqtgraph.debug import Profiler from acq...
acq4/acq4
acq4/devices/DAQGeneric/DAQGeneric.py
Python
mit
25,249
from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from django.http import Http404, JsonResponse, HttpResponseForbidden from django.shortcuts import render, redirect, get_object_or_404 from .forms import PlaylistForm from .models import Playlist def form_data(user, f...
chaocodes/playlist-manager-django
manager/playlist/views.py
Python
mit
2,983
import uctypes ACCEL_CONFIG = { 'x_self_test' : uctypes.BFUINT8 | 0 | 7 << uctypes.BF_POS | 1 << uctypes.BF_LEN, 'y_self_test' : uctypes.BFUINT8 | 0 | 6 << uctypes.BF_POS | 1 << uctypes.BF_LEN, 'z_self_test' : uctypes.BFUINT8 | 0 | 5 << uctypes.BF_POS | 1 << uctypes.BF_LEN, 'range' : ucty...
dhylands/upy-examples
uctypes_test.py
Python
mit
763
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "like.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
bartTC/like
manage.py
Python
mit
245
import math import time # Retry decorator with exponential backoff def retry(tries, delay=1, backoff=2): """Retries a function or method until it returns True. delay sets the initial delay, and backoff sets how much the delay should lengthen after each failure. backoff must be greater than 1, or else it isn'...
Heipiao/weibo
retry.py
Python
mit
1,243
import unittest, tempfile, uuid, os, shutil, sys class Test_CreateRemoveTempLocation(unittest.TestCase): def __init__(self, *args, **kwargs): super(Test_CreateRemoveTempLocation, self).__init__(*args, **kwargs) self._tmpTestFolder = None def setUp(self): self._tmpTestFolder = os.pa...
yukioSatoh/ysPyCommon
tests/test_ysPyCommon/__init__.py
Python
mit
941
#/usr/bin/env python from fsm import Machine states = ["q1", "q2", "q3"] alphabet = ["0","1"] transitions = { "q1": {"0": "q1", "1": "q2"}, "q2": {"0": "q3", "1": "q2"}, "q3": {"0": "q2", "1": "q2"}, } start = "q1" end = ["q2"] machine = Machine.from_arguments(states, alphabet, transitions, start, end)...
bnookala/fsm
example.py
Python
mit
448
''' Ugly - will be improved soon ''' from datetime import datetime,timedelta def archive_timestamp(timestamp): ''' ''' _d=datetime.strptime(timestamp, '%Y%m%d%H%M%S') return _d.strftime('%Y%m%d') def way_date(date_input): ''' ''' if isinstance(date_input, str): return datetime.st...
VulcanoAhab/waybackeess
date.py
Python
mit
4,845
# Import the JModelica.org Python packages import pymodelica from pymodelica.compiler_wrappers import ModelicaCompiler # Create a compiler and compiler target object mc = ModelicaCompiler() # Build trees as if for an FMU or Model Exchange v 1.0 #target = mc.create_target_object("me", "1.0") source = mc.parse_model("C...
michael-okeefe/soep-sandbox
src/python2/dump_source.py
Python
mit
815
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file '.\taskTemplate.ui' # # Created: Thu Oct 08 16:48:34 2015 # by: PyQt4 UI code generator 4.10.4 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except...
mgraupe/acq4
acq4/devices/Laser/taskTemplate.py
Python
mit
6,745
# https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/ from TreeNode import TreeNode class Solution(object): def sortedArrayToBST(self, nums): if not nums : return None n = len(nums) if n == 1: return TreeNode(nums[0]) mid = TreeNode(nums[n // 2]) ...
menghanY/LeetCode-Python
Tree/ConvertSortedArrayToBinarySearchTree.py
Python
mit
452
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Fri Jan 27 16:23:07 2017 @author: user """ ## FOUND HERE http://www.nltk.org/howto/sentiment.html ## Source code http://www.nltk.org/_modules/nltk/sentiment/vader.html ## http://www.nltk.org/api/nltk.sentiment.html ## Hutto, C.J. & Gilbert, E.E. (2014). VAD...
SatoshiNakamotoGeoscripting/SatoshiNakamotoGeoscripting
Final_assignment/lib/sentimentAnalyzerVader.py
Python
mit
1,401
''' The following is from http://stackoverflow.com/a/2022629 Thanks to Longpoke ''' import types class Event(list): """Event subscription. A list of callable objects. Calling an instance of this will cause a call to each item in the list in ascending order by index. Example Usage: >>> def f(x): ...
willemneal/CallMe
callMe.py
Python
mit
2,823
import time import psycopg2 import os import sys if __name__ == "__main__": try: conn = psycopg2.connect("dbname='master' user='postgres' host='localhost' password='postgres'") except Exception, e: print "unable to connect" sys.exit() cur = conn.cursor() for x in xrange(1,1000): print x cur.execute("...
btrihatmaja/AutoSlony
testing/test_insert.py
Python
mit
443
from item import Item class Merchant: def __init__(self, markup=1.2, markdown=0.8): self.inventory = [] self.markup = markup self.markdown = markdown def add_item(self, item): # Adds an item to the merchant's inventory if (not isinstance(item, Item)): ...
henrik645/txt-rpg
merchant.py
Python
mit
1,919
from django.core.management.base import BaseCommand, CommandError import __future__ from ModelTracker.models import History import datetime from django.apps import apps def getModel(table_name): return next((m for m in apps.get_models() if m._meta.db_table==table_name), None) class Command(BaseCommand): help =...
mkalioby/ModelTracker
ModelTracker/management/commands/restoreObject.py
Python
mit
1,770
# Define a new directive `code-block` (aliased as `sourcecode`) that uses the # `pygments` source highlighter to render code in color. # # Incorporates code from the `Pygments`_ documentation for `Using Pygments in # ReST documents`_ and `Octopress`_. # # .. _Pygments: http://pygments.org/ # .. _Using Pygments in Re...
faircloth-lab/data-theme
_plugins/jekyll-rst/directives.py
Python
mit
3,665
import urllib2 import lxml.html import numpy import scipy import scipy.misc import scipy.cluster import urlparse import struct import operator import gzip import datetime import requests import httplib from PIL import BmpImagePlugin, PngImagePlugin, Image from socket import error as SocketError from boto.s3.key import ...
mihaip/NewsBlur
apps/rss_feeds/icon_importer.py
Python
mit
13,810
# coding=utf-8 """ Binary class deconstruct, reconstruct packet """ import copy class Binary(object): @staticmethod def deconstruct_packet(packet): """ Replaces every bytearray in packet with a numbered placeholder. :param packet: :return: dict with packet and list of buffers ...
shuoli84/gevent_socketio2
socketio/binary.py
Python
mit
2,907
# Under MIT license, see LICENSE.txt from enum import Enum """ Constantes concernant les tactiques. """ class Flags(Enum): INIT = 0 WIP = 1 FAILURE = 2 SUCCESS = 3 PASS_TO_PLAYER = 4 def is_complete(p_status_flag): return p_status_flag == Flags.FAILURE or p_status_flag == Flags.SUCCESS
RoboCupULaval/StrategyIA
ai/STA/Tactic/tactic_constants.py
Python
mit
317
import os from datetime import timedelta basedir = os.path.abspath(os.path.dirname(__file__)) class Config: ########################################################################### # [ Application ] ########################################################################### APP_TITLE = 'WebApp' ...
richgieg/flask-now
config.py
Python
mit
4,539
""" merged implementation of the cache provider the name cache was not chosen to ensure pluggy automatically ignores the external pytest-cache """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import json import os from collections import OrderedDict imp...
hackebrot/pytest
src/_pytest/cacheprovider.py
Python
mit
13,931
#!/usr/bin/env python """ This module contains input, output and algorithms for creating texture atlases. """
Ezphares/TextureAtlas
atlas/__init__.py
Python
mit
110
#!/usr/bin/python # Copyright 2014 BitPay, Inc. # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. from __future__ import division,print_function,unicode_literals import os import bctest import buildenv if __name__ == '__main__': bc...
navcoindev/navcoin-core
src/test/navcoin-util-test.py
Python
mit
410
import pylogging import os # Logs Dir Absolute Path logs_path = os.path.dirname(os.path.abspath(__file__)) + '/logs/' # Create Logger Instance logger = pylogging.PyLogging(LOG_FILE_PATH = logs_path) def customAction1(type, msg): # Custom Action Goes Here pass # Add Action actionIden1 = logger.addAction(customActio...
Clivern/PyLogging
examples/custom_actions.py
Python
mit
773
from .utils import ShellParser class Parser(ShellParser): """Extract text from postscript files using ps2ascii command. """ def extract(self, filename, **kwargs): stdout, _ = self.run(['ps2ascii', filename]) return stdout
deanmalmgren/textract
textract/parsers/ps_parser.py
Python
mit
253
class Node: def __init__(self,data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def push(self, newdata): #in front newnode = Node(newdata) newnode.next = self.head self.head = newnode def insertAfter(self, prevnode, newdata): newnode = Node(newdata) n...
singhjaideep/Stuff
linkedlist_2.py
Python
mit
1,494
# Generated by Django 2.1.4 on 2018-12-21 14:08 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('mainapp', '0016_auto_20181202_2205'), ('mainapp', '0016_auto_20181221_1432'), ] operations = [ ]
meine-stadt-transparent/meine-stadt-transparent
mainapp/migrations/0017_merge_20181221_1508.py
Python
mit
272
from multiprocessing import Process import pytest from .mock_server.server import start server_process = None @pytest.hookimpl def pytest_sessionstart(session): global server_process server_process = Process(target=start) server_process.start() @pytest.hookimpl def pytest_sessionfinish(session): if ...
pirate/bookmark-archiver
tests/conftest.py
Python
mit
417
############################################################################## # Clinical trials parser # # eg 2013-2016 ############################################################################## import cPickle, os, re def main(): #base_dir = "../data/ct/" base_dir = "/home/eguney/data/ct/" file_name ...
quimaguirre/diana
diana/toolbox/parse_clinical_trials.py
Python
mit
12,367
import peewee import tornado.web import tornado.gen from windseed.settings import env, db from windseed.base import handler from windseed.apps.admin import urls from windseed.apps.admin.models import User from windseed.apps.web.models import Record class Handler(handler.Handler): def get_current_user(self): ...
embali/windseed
windseed/apps/admin/handlers.py
Python
mit
7,638
##### 텐서 딥러닝 1장 import tensorflow as tf hello = tf.constant('Hello, Tensorflow') sess = tf.Session() print(sess.run(hello)) # 'b'는 bytes literals라는 뜻이다. node1 = tf.constant(3.0, tf.float32) # 숫자, 데이터타입 node2 = tf.constant(4.0) # 숫자, 데이터타입 node3 = tf.add(node1, node2) # 숫자, 데이터타입 # node3 = node1 + node2 # 이렇게도 사용가...
ghost9023/DeepLearningPythonStudy
DeepLearning/DeepLearning/02_Deep_ChoTH/tensorflow_prac.py
Python
mit
18,788
import numpy as np import matplotlib.pyplot as plt from scipy.constants import c, e, m_p import matplotlib.pyplot as plt plt.switch_backend('TkAgg') plt.ion() from PyCOBRA_accelerator import TwissMap from PyCOBRA_beam import Bunch, gaussian_generator R = 6911./(2*np.pi) energy = 26e9 gamma = np.sqrt(1 + (e*energy/(...
like2000/PyCOBRA
PyCOBRA_run.py
Python
mit
1,736
import numpy as np import pytoolkit as tk def test_print_classification_multi(): y_true = np.array([0, 1, 1, 1, 2]) prob_pred = np.array( [ [0.75, 0.00, 0.25], [0.25, 0.75, 0.00], [0.25, 0.75, 0.00], [0.25, 0.00, 0.75], [0.25, 0.75, 0.00], ...
ak110/pytoolkit
pytoolkit/evaluations/classification_test.py
Python
mit
808
from readSVCsig import readSVCdata from readSVCsig import readSVCheader from readSVCsig import readSVCsig
pavdpr/svcread
python/__init__.py
Python
mit
106
# mako/cmd.py # Copyright 2006-2021 the Mako authors and contributors <see AUTHORS file> # # This module is part of Mako and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php from argparse import ArgumentParser from os.path import dirname from os.path import isfile import sys from...
sqlalchemy/mako
mako/cmd.py
Python
mit
2,814
#!/usr/bin/env python # A python script to take targets from a google spreadsheet and run a # Nessus vulnerability scan. import json import gspread from oauth2client.service_account import ServiceAccountCredentials from nessrest import ness6rest import getpass # Login with your Google account's API key scopes = ['ht...
mokuso/scan-gspread-targets
scan-gspread-targets.py
Python
mit
1,952
""" Django-environ allows you to utilize 12factor inspired environment variables to configure your Django application. """ import json import logging import os import re import sys import warnings from django.core.exceptions import ImproperlyConfigured from six.moves import urllib_parse as urlparse from six import st...
ei-grad/django-environ
environ/environ.py
Python
mit
22,397
""" run tests against a webserver running in the same reactor NOTE: this test uses port 8888 on localhost """ import os import ujson as json import cyclone.httpclient from twisted.internet import defer from twisted.application import internet from twisted.trial.unittest import TestCase from twisted.python import log ...
stackdump/txbitwrap
txbitwrap/test/__init__.py
Python
mit
2,474
# Exercise 3 # creating a simple loop # print out 1 thru 10 #set the start value i = 0 upper_range=10 for i in range(upper_range): print(str(i+1)+ " this is a loop")
paulcockram7/paulcockram7.github.io
10python/l05/Exercise 3.py
Python
mit
171
# -*- coding: utf-8 -*- import re import requests import base64 import struct import random from sklearn.cluster import KMeans from sklearn.preprocessing import scale from dateutil.parser import parse class Tweet(object): def __init__(self, status): self.screen_name = status['screen_name'] self.tex...
uwekamper/flutterspark
flutterbrain_web/mapview/clustering.py
Python
mit
3,178
import logging from amqpstorm import Connection from amqpstorm import Message logging.basicConfig(level=logging.INFO) with Connection('localhost', 'guest', 'guest') as connection: with connection.channel() as channel: # Declare a queue called, 'simple_queue'. channel.queue.declare('simple_queue')...
eandersson/amqpstorm
examples/publish_message_with_expiration.py
Python
mit
624
import ctypes class C_struct: """Decorator to convert the given class into a C struct.""" # contains a dict of all known translatable types types = ctypes.__dict__ @classmethod def register_type(cls, typename, obj): """Adds the new class to the dict of understood types.""" cls.types[typename] = obj def __...
ActiveState/code
recipes/Python/576734_C_struct_decorator/recipe-576734.py
Python
mit
1,507
#!/usr/bin/env python # integeral.py import numpy as num def integral(x,y): """ ROUTINE: INTEGRAL USEAGE: RESULT = INTEGRAL( X, Y ) PURPOSE: Integrate tabulated data using Simpson's rule with 3-point Lagragian interpolation. Data may be regularly sampled in X, ...
graziano-giuliani/pythoncode
pyuwphysret/common/pyfiles/atmos/integral.py
Python
mit
2,891
# !/usr/bin/env python # -*- coding: utf-8 -*- # created by restran on 2016/1/2 from __future__ import unicode_literals, absolute_import from django import forms from django.utils.translation import ugettext_lazy as _ from .models import * from common.forms import BaseModelForm logger = logging.getLogger(__name__) ...
restran/api-gateway-dashboard
dashboard/forms.py
Python
mit
3,021
import gdsfactory as gf yaml = """ instances: mmi1: component: mmi1x2 settings: width_mmi: 4.5 length_mmi: 10 mmi2: component: mmi1x2 settings: width_mmi: 4.5 length_mmi: 5 straight: component: straight placements: mmi2: x: 100 ...
gdsfactory/gdsfactory
fixme/netlist.py
Python
mit
766
class Repository(object): def __init__(self, obj): self._wrapped_obj = obj self.language = obj[u'language'] or u'unknown' self.name = obj[u'full_name'] def __getattr__(self, attr): if attr in self.__dict__: return getattr(self, attr) else: return ...
Rustem/toptal-blog-celery-toy-ex
celery_uncovered/toyex/models.py
Python
mit
353
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Deleting model 'Positions' db.delete_table(u'positions_positions') # Adding model 'Position' ...
Hackfmi/Diaphanum
positions/migrations/0002_auto__del_positions__add_position.py
Python
mit
1,927
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Utilities for getting directory tree.""" import os from pathlib import Path import crayons from nuke.utils import parse_ignore_file def fg(text, color): """Set text to foregound color.""" return "\33[38;5;" + str(color) + "m" + text + "\33[0m" def bg(tex...
varunagrawal/nuke
nuke/dirtree.py
Python
mit
3,107
#!/usr/bin/env python # -*- coding: utf-8 -*- from collections import Counter import numpy as np STARTING_LABEL = '*' # Label of t=-1 STARTING_LABEL_INDEX = 0 def default_feature_func(_, X, t): """ Returns a list of feature strings. (Default feature function) :param X: An observation vector...
lancifollia/laon_crf
feature.py
Python
mit
8,052
""" Functions to spot hemy regions """ import os.path as op import datetime from collections import defaultdict, Counter from tabulate import tabulate from scipy import stats import numpy as np import pybedtools import pysam import vcf from bcbio.distributed.transaction import file_transaction from bcbio.provenance ...
lpantano/ASMfinder
asm/select.py
Python
mit
16,220
#import logging #logging.basicConfig(level=logging.INFO, datefmt='%H:%M:%S', # format='%(asctime)s %(levelname)s: %(message)s') import unittest import SocketServer, socket import random, time import threading import cStringIO from datetime import datetime from shapy import register_settings registe...
praus/shapy
tests/emulation/test_shaping.py
Python
mit
3,245
import urllib from urllib2 import urlopen, quote import urllib2 import json import time import datetime import csv import unicodedata import sys timestring = time.time() formatted_timestring = datetime.datetime.fromtimestamp(timestring).strftime('%Y_%m_%d') search = sys.argv[1] api_key = 'YOUR_API_KEY' def query_th...
JburkeRSAC/PizzaCat-Web
threat_recon_to_CSV.py
Python
mit
2,231
#!/usr/bin/env python3 # Copyright (c) 2014-2016 The Sarielsaz Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test behavior of headers messages to announce blocks. Setup: - Two nodes, two p2p connections to n...
sarielsaz/sarielsaz
test/functional/sendheaders.py
Python
mit
24,054
""" Git Parent model """ from django.db import models class GitParentEntry(models.Model): """ Git Parent """ project = models.ForeignKey('gitrepo.GitProjectEntry', related_name='git_parent_project') parent = models.ForeignKey('gitrepo.GitCommitEntry', related_name='git_parent_commit') son = models.For...
imvu/bluesteel
app/logic/gitrepo/models/GitParentModel.py
Python
mit
713
from character import Trait, Perk __author__ = "Johannes Hackbarth" ALL_RACES = {"Deathclaw", "Dog", "Ghoul", "Half Mutant", "Human", "Robot", "Super Mutant"} ANIMALS = {"Deathclaw", "Dog"} ROBOTS = {"Robot"} # TODO: Add all effects to traits TRAIT_LIST = [ Trait("Fast Metabolism", "Your metabolic rate...
DarthBubi/fallout-pnp-character-creator
character-creator/config.py
Python
mit
11,633
from gdsfactory.port import csv2port def test_csv2port(data_regression): import gdsfactory as gf name = "straight" csvpath = gf.CONFIG["gdsdir"] / f"{name}.ports" ports = csv2port(csvpath) data_regression.check(ports)
gdsfactory/gdsfactory
gdsfactory/tests/test_port_from_csv.py
Python
mit
241
import logging import struct import threading import serial import serial.tools.list_ports COMMAND_TO_CHANNEL = { 'F': 0x00, 'W': 0x01, 'H': 0x02, 'C': 0x03 } class SerialPort(object): def __init__(self, port_name): self.port_name = port_name self.serial_port = None self.serial_lock = None self.log_thr...
j-be/vj-control-server
vj_serial.py
Python
mit
2,458
import json from jaspyx.visitor import BaseVisitor class Types(BaseVisitor): def visit_Num(self, node): self.output(json.dumps(node.n)) def visit_Str(self, node): self.output(json.dumps(node.s)) def visit_List(self, node): self.group(node.elts, prefix='[', infix=', ', suffix=']')...
iksteen/jaspyx
jaspyx/visitor/types.py
Python
mit
351
import sys import gc import pygame from pygame.locals import * from input import * import snd TICKS_PER_SECOND = 25 GAMETICKS = 1000 / TICKS_PER_SECOND def set_game_speed( slowdown ): global TICKS_PER_SECOND global GAMETICKS TICKS_PER_SECOND = int( 25 * slowdown ) GAMETICKS = 100...
koonsolo/MysticMine
monorail/koon/app.py
Python
mit
4,111
# Electrum - lightweight Bitcoin client # Copyright (C) 2015 Thomas Voegtlin # # 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 t...
romanz/electrum
lib/wallet.py
Python
mit
85,717
import asyncio import aiohttp import async_timeout import atexit import re import json from .. import exception from ..api import _methodurl, _which_pool, _fileurl, _guess_filename _loop = asyncio.get_event_loop() _pools = { 'default': aiohttp.ClientSession( connector=aiohttp.TCPConnector(limit...
nickoala/telepot
telepot/aio/api.py
Python
mit
5,062
import argparse import os import sys import numpy as np import matplotlib.pyplot as plt from perf.errsim import * def plot_x_vs_pmf(params, show=True, fpath=None): def plot(ax, x, param, **plotargs): if param['pb'] is None: param['pb'] = param['pe'] label = 'BSC pe={pe} m={m} n={n}...
r-rathi/error-control-coding
perf/perf_plots.py
Python
mit
11,256
#!/usr/bin/env python3 """ Unit tests for the Grammar class and for the GrammarAnalyzer class. Tests each grammar in the "grammars" folder against a variety of strings. """ import unittest from grammar import Grammar from grammaranalyzer import GrammarAnalyzer class TestGrammar(unittest.TestCase): def test_nonexis...
JVMartin/grammar-analyzer
tests.py
Python
mit
7,593
import re import datetime from pymongo import MongoClient from bson import ObjectId from .exception import RecorderException, StructureException __all__ = ['get_database', 'Recorder', 'Structure'] def get_database(db_name, host, port=27017): return MongoClient(host, port)[db_name] class Structure(dict): __...
teitei-tk/ice-pick
icePick/recorder.py
Python
mit
4,310
import graphene from graphene_django.types import DjangoObjectType from django.contrib.auth import (get_user_model, authenticate, login as auth_login, logout as auth_logout, update_session_auth_hash) from django.contrib.auth.forms import (UserCreationFor...
pshrmn/cryptonite
cryptonite/user_auth/schema.py
Python
mit
3,906
#!/usr/bin/env python3 # This script prints a new "servers.json" to stdout. # It prunes the offline servers from the existing list (note: run with Tor proxy to keep .onions), # and adds new servers from provided file(s) of candidate servers. # A file of new candidate servers can be created via e.g.: # $ ./electrum_ltc/...
pooler/electrum-ltc
electrum_ltc/scripts/update_default_servers.py
Python
mit
2,380
# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*- ### BEGIN LICENSE # Copyright (C) 2014 Frederic Branczyk fbranczyk@gmail.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 ...
flower-pot/xf-indicator
xf_indicator/__init__.py
Python
mit
1,347
from django.http import JsonResponse from user.models import User from django.db.models import Q from django.apps import apps def user_filter(request, *args, **kwargs): # 将来的にはpostで、結果に含めるタグを選択できるようにしたい。 query = Q() user = request.user tags = user.follow_tag.all() if len(tags) > 0: Tag = a...
internship2016/sovolo
app/user/api.py
Python
mit
1,184