repo_name stringlengths 5 104 | path stringlengths 4 248 | content stringlengths 102 99.9k |
|---|---|---|
rtyler/urlenco.de | Urlencode/controllers/api.py | #!/usr/bin/env python
import time
import urllib
try:
import yajl as json
except ImportError:
import json
from MicroMVC import controller
from redis import Redis
from Urlencode import logic
class api(controller.BaseController):
redis = None
not_found = -988887
def __init__(self, *args, **kwargs)... |
jcairo/391_project | project_391/main/migrations/0001_initial.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='GroupLists',
fields=[
('id', models.AutoField(s... |
radiocosmology/alpenhorn | alpenhorn/client/group.py | """Alpenhorn client interface for operations on `StorageGroup`s."""
import click
import peewee as pw
import alpenhorn.storage as st
from .connect_db import config_connect
@click.group(context_settings={"help_option_names": ["-h", "--help"]})
def cli():
"""Commands operating on storage groups. Use to create, mo... |
codefisher/tbutton_web | tbutton_maker/migrations/0002_auto_20141019_2034.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('tbutton_maker', '0001_initial'),
]
... |
harris-helios/helios-sdk-python | helios/__init__.py | """Use the Helios APIs in Python"""
import logging
# Load configuration first.
from .core.config import CONFIG
from . import core
from . import utilities
from .alerts_api import Alerts
from .cameras_api import Cameras
from .collections_api import Collections
from .core.session import Session
from .observations_api imp... |
laserson/hdfs | hdfs/client.py | #!/usr/bin/env python
# encoding: utf-8
"""HDFS clients."""
from .util import Config, HdfsError, InstanceLogger, temppath
from getpass import getuser
from itertools import repeat
from multiprocessing.pool import ThreadPool
from random import sample
from shutil import move, rmtree
from urllib import quote
from warning... |
atlefren/beerdatabase | dbupdate/db.py | # -*- coding: utf-8 -*-
import urlparse
from datetime import datetime
import psycopg2
psycopg2.extensions.register_type(psycopg2.extensions.UNICODE)
psycopg2.extensions.register_type(psycopg2.extensions.UNICODEARRAY)
class Database(object):
def __init__(self, conn_str=None):
self.conn_str = conn_str
... |
CanopyIQ/gmail_client | gmail_client/models/history_message_added.py | # coding: utf-8
"""
Gmail
Access Gmail mailboxes including sending user email.
OpenAPI spec version: v1
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re
class HistoryMessageAdded(object):
"""
NOTE: Thi... |
FujiMakoto/AgentML | agentml/parser/init/__init__.py | from lxml import etree
from agentml.common import attribute
from agentml.parser import Element
class Init(Element):
"""
AgentML Initialization
"""
def __init__(self, agentml, element, file_path, **kwargs):
"""
Initialize a new Init instance
"""
super(Init, self).__init_... |
paperreduction/fabric-bolt | setup.py | #!/usr/bin/env python
from setuptools import setup, find_packages
setup_requires = []
install_requires = [
'django==1.8.4',
'pillow==2.9.0',
'django-stronghold==0.2.7',
'django-crispy-forms==1.5.1',
'django-authtools==1.2.0',
'django-tables2==1.0.4',
'django-braces==1.8.1',
'django-se... |
llloret/sc_patches | osc_control/osc.py | import argparse
import time
from pythonosc import osc_message_builder
from pythonosc import udp_client
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--ip", default="127.0.0.1",
help="The ip of the OSC server")
parser.add_argument("--port", typ... |
Vervious/imagetospreadsheet | imagetospreadsheet.py | #!/usr/bin/env python
from PIL import Image
import numpy as np
from scipy import ndimage
import xlsxwriter
im = Image.open("images/pusheen.png")
print "Image size: " + str(im.size) # Get the width and hight of the image for iterating over
SPREADSHEET_SIZE = (50, 50)
CELL_WIDTH_RATIO = 2.5 # ratio of cell width to... |
DonaldWhyte/deep-learning-with-rnns | workshop/code/solutions/2d.py | # ==============================================================================
# Deep Learning with Recurrent Neural Networks Workshop
# By Donald Whyte and Alejandro Saucedo
#
# Step 2d:
# Building a Basic Neural Network
# ==============================================================================
import csv
imp... |
gmwils/cihui | migrations/versions/1d8e0b3b949_add_description_to_list.py | """Add description to list
Revision ID: 1d8e0b3b949
Revises: 594033d136f
Create Date: 2014-07-20 13:37:41.064387
"""
# revision identifiers, used by Alembic.
revision = '1d8e0b3b949'
down_revision = '594033d136f'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_column('list', sa.Column('de... |
dbservice/dbservice | dbservice/apps/homes/views.py | import datetime
from dateutil.relativedelta import relativedelta
from rest_framework import status, viewsets
from rest_framework.decorators import link, list_route
from rest_framework.exceptions import ParseError
from rest_framework.fields import ValidationError
from rest_framework.response import Response
from dbser... |
nikitanovosibirsk/valeera | tests/test_number_validator.py | import unittest
import warnings
from district42 import json_schema as schema
from .validator_testcase import ValidatorTestCase
class TestNumberValidator(ValidatorTestCase):
def setUp(self):
warnings.simplefilter('ignore')
def test_it_validates_type(self):
self.assertValidationPasses(-3.14, schema.numb... |
WikiEducationFoundation/WikiEduDashboard | setup.py | #!/usr/bin/env python3
import platform
import subprocess
print ("WARNING! This is a work in progress script. It has been tested to work for Fedora and debian-based systems. \
There are individual operating system dependent scripts being called from this one. \
You can find them in setup directory. The script for w... |
pezy/AutomateTheBoringStuffWithPython | practice_projects/TestPrintTable.py | #! python3
'''TestPrintTable.py - Test print_table function'''
TABLE_DATA = [['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']]
def print_table(str_list):
'''print the table'''
col_widths = [0] * len(str_list)
f... |
jeeyoungk/exercise | python/buysell.py | # Determine best time to buy and sell a given item.
# input - time series [v_0, v_1 ... v_n]
# input - k >= 1 - # of times you can buy / sell. you cannot buy again if you've already bought one.
# output - total profit with k trades.
# The solution is O(n) given quickselect.
import pprint
DEBUG = False
class Node(obje... |
wiktorski/opentsdb_pandas | test_opentsdb_pandas.py | """
This module provides tests (pytest) for methods in opentsdb_pandas module (to fetch data from OpenTSDB HTTP interface and convert them into Pandas Timeseries object)
(Most of) these tests rely on an external installation of OpenTSDB with a very specific set of data,
if you test this in a different environment you... |
tell-k/django-modelsdoc | modelsdoc/constants.py | #! -*- coding:utf-8 -*-
"""
modelsdoc.constants
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:author: tell-k <ffk2005@gmail.com>
:copyright: tell-k. All Rights Reserved.
"""
from __future__ import division, print_function, absolute_import, unicode_literals # NOQA
from django.conf import settings
D... |
Pazitos10/TNT | webapp/app/tntapp/migrations/0003_auto_20160616_2016.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2016-06-16 20:16
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('tntapp', '0002_auto_20160527_1234'),
]
operations = [
migrations.RenameField... |
ngovindaraj/Python | leetcode/ds_string_group_anagrams.py | # @file Group Anagrams
# @brief Given an array of strings, group anagrams together.
# https://leetcode.com/problems/group-anagrams/
'''
Given an array of strings, group anagrams together.
For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"],
Return:
[
["ate", "eat","tea"],
["nat","tan"],
["bat"]
]
... |
plotly/plotly.py | packages/python/plotly/plotly/graph_objs/surface/legendgrouptitle/_font.py | from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType
import copy as _copy
class Font(_BaseTraceHierarchyType):
# class properties
# --------------------
_parent_path_str = "surface.legendgrouptitle"
_path_str = "surface.legendgrouptitle.font"
_valid_props = {"color",... |
eladnoor/equilibrator-api | equilibrator_api/bounds.py | #!/usr/bin/python
import logging
import csv
import numpy
import os
from copy import deepcopy
from equilibrator_api.concs import ConcentrationConverter
from equilibrator_api import settings
class InvalidBounds(Exception):
pass
class BaseBounds(object):
"""A base class for declaring bounds on things."""
... |
swearu/flasky | user.py | from sqlalchemy import Column,String,create_engine,Integer
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
engine = create_engine('mysql://root:zhuyan@localhost/hibernate')
DBsession = sessionmaker(bind=engine)
class User(Base):
__tablena... |
bblais/Classy | classy/datasets.py | from __future__ import print_function
import numpy as np
import sklearn.datasets
from .Struct import Struct
from sklearn.feature_extraction import DictVectorizer
from copy import deepcopy as copy_data
def make_dataset(**kwargs):
from numpy import array
feature_names=kwargs.pop('feature_names',None)
... |
lmazuel/azure-sdk-for-python | azure-batch/azure/batch/models/compute_node_reboot_options.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 ... |
voxie-viewer/voxie | lib/python/nbt/nbt/region.py | """
Handle a region file, containing 32x32 chunks.
For more information about the region file format:
https://minecraft.gamepedia.com/Region_file_format
"""
from .nbt import NBTFile, MalformedFileError
from struct import pack, unpack
from collections import Mapping
import zlib
import gzip
from io import BytesIO
impor... |
ethers/btcrelay | test/test_btcChain.py | from ethereum import tester
from datetime import datetime, date
import math
import pytest
slow = pytest.mark.slow
from utilRelay import dblSha256Flip, disablePyethLogging
disablePyethLogging()
class TestBtcChain(object):
CONTRACT_DEBUG = 'test/btcChain_debug.se'
ETHER = 10 ** 18
ANC_DEPTHS = [1, 4, 1... |
reetawwsum/Machine-Translation | utils/batchGenerator.py | from __future__ import print_function
from __future__ import absolute_import
import random
import numpy as np
import config
from utils.dataset import Dataset
class BatchGenerator():
'''Generate Batches'''
def __init__(self):
self.batch_size = config.FLAGS.batch_size
self.buckets = buckets = config.BUCKETS
se... |
wikilinks/nel | nel/features/context.py | #!/usr/bin/env python
import math
from collections import Counter
from .feature import Feature
from ..model.disambiguation import EntityContext
from nel import logging
log = logging.getLogger()
def sparse_cosine_distance(a, b, norm=True):
if norm:
a_sq = 1.0 * math.sqrt(sum(val * val for val in a.iterval... |
ActiveState/code | recipes/Python/577737_Public_Key_Encryption_RSA/recipe-577737.py | from fractions import gcd
from random import randrange
from collections import namedtuple
from math import log
from binascii import hexlify, unhexlify
def is_prime(n, k=30):
# http://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test
if n <= 3:
return n == 2 or n == 3
neg_one = n - 1
# ... |
PyAbel/PyAbel | abel/tests/test_hansenlaw.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from numpy.testing import assert_allclose
import abel
def test_hansenlaw_shape():
n = 21
x = np.ones((n, n), dtype='float32')
recon = abel.hansenlaw.hansenlaw_transform(x, dir... |
xju2/HZZ_llvv_ws | HZZ_llvv_ws/interpolate_acceptance.py | # -*- coding: utf-8 -*-
import sys
import os
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(os.path.realpath(__file__))), '..')))
from HZZ_llvv_ws import helper
import matplotlib.pyplot as plt
plt.rc('text', usetex=True)
plt.rc('font', family='serif')
from scipy import interpolate
i... |
mutalyzer/description-extractor | extractor/__init__.py | """
extractor: Extract a list of differences between two sequences.
Copyright (c) 2013 Leiden University Medical Center <humgen@lumc.nl>
Copyright (c) 2016 Jonathan K. Vis <j.k.vis@lumc.nl>
Licensed under the MIT license, see the LICENSE file.
"""
from __future__ import (absolute_import, division, print_function,
... |
nparley/mylatitude | lib/Crypto/Random/OSRNG/rng_base.py | #
# Random/OSRNG/rng_base.py : Base class for OSRNG
#
# Written in 2008 by Dwayne C. Litzenberger <dlitz@dlitz.net>
#
# ===================================================================
# The contents of this file are dedicated to the public domain. To
# the extent that dedication to the public domain is not availa... |
fc-thrisp-hurrata-dlm-graveyard/flack | tests/test_app/__init__.py | from flask import Flask, render_template, current_app
from werkzeug.local import LocalProxy
ds = LocalProxy(lambda: current_app.extensions['security'].datastore)
def create_app(config):
app = Flask(__name__)
app.debug = True
app.config['SECRET_KEY'] = 'secret'
app.config['TESTING'] = True
for ke... |
guineawheek/spock | spock/mcmap/mapdata.py | from spock.utils import BoundingBox
#Materials
MCM_MAT_ROCK = 0x00
MCM_MAT_DIRT = 0x01
MCM_MAT_WOOD = 0x02
MCM_MAT_WEB = 0x03
MCM_MAT_WOOL = 0x04
MCM_MAT_VINE = 0x05
MCM_MAT_LEAVES = 0x06
#Gate
MCM_GATE_SOUTH = 0x00
MCM_GATE_WEST = 0x01
MCM_GATE_NORT... |
SOM-Research/Gitana | importers/instant_messaging/slack/querier_slack.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'valerio cosentino'
import re
from slacker import Slacker
from util.date_util import DateUtil
class SlackQuerier():
"""
This class collects the data available on the Eclipse forum viw Web scraping
"""
def __init__(self, token, logger):
... |
mofei2816/mervinz | core/management/commands/compress.py | # -*- coding: utf-8 -*-
"""
The MIT License (MIT)
Copyright (c) 2016 Mervin <mofei2816@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 Software without restriction, including without limitation... |
markEarvin/sl-contest-tracker | plugins/settings/__init__.py | from ferris.core import plugins
import threading
import logging
from .models.setting import Setting as SettingsModel
plugins.register('settings')
local_cache = threading.local()
def activate(settings):
if not hasattr(local_cache, 'overrides'):
local_cache.overrides = SettingsModel.get_settings()
se... |
wukawitz/ghostacid | ghostacid.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
GhostAcid - A very simple callback script
GhostAcid is a very simple callback script designed to work with a ncat
listener. It should allow the user to get a foothold onto a system and allow
for further recon and enumeration.
########################################... |
BigEgg/LeetCode | Python/LeetCode.Test/_001_050/Test_030_SubstringWithConcatenationOfAllWords.py | import unittest
import sys
sys.path.append('LeetCode/_001_050')
sys.path.append('LeetCode.Test')
from _030_SubstringWithConcatenationOfAllWords import Solution
import AssertHelper
class Test_030_SubstringWithConcatenationOfAllWords(unittest.TestCase):
def test_findSubstring_haveMatch(self):
solution = S... |
derricw/pysentech | pysentech/examples/low_level_mpl.py | # -*- coding: utf-8 -*-
"""
Created on Mon Dec 07 22:08:13 2015
@author: derricw
Demonstrates use of the Sentech DLL using ctypes.
1) Loads the header file and dll.
2) Checks for available cameras.
3) Gets a camera handle.
4) Gets image properties from the camera.
5) Sets up a buffer for the image.
6) Copies the cam... |
nitsas/codejamsolutions | Senate Evacuation/runme.py | #!/usr/bin/env python3
"""
Senate Evacuation problem
for Google Code Jam 2016
Round 1C
Link to problem description:
https://code.google.com/codejam/contest/4314486/dashboard#s=p0
Author:
Chris Nitsas
(nitsas)
Language:
Python 3(.4)
Date:
May, 2016
Usage:
python3 runme.py input_file
"""
import sys
impor... |
CackboneML/KebabParty | launcher.py | import pygame as pg
import lib.inputbox as textbox
import pyglet, os, json, time
import main
pg.init()
clock = pg.time.Clock()
global player_name, FULLSCREEN, levels_number, view, menu
view = "main"
menu = True
player_name = ""
FULLSCREEN = "True"
levels_number = 0
pg.mixer.init()
pg.mixer.music.load... |
CMU-ARM/sphero_sprk | sphero_sprk/util.py | #!/usr/bin/python3
from bluepy.btle import Scanner
def search_for_sphero(second_time=1):
scanner = Scanner()
devices = scanner.scan(second_time)
sphero_list = []
for dev in devices:
#get the complete local name
local_name = dev.getValueText(9)
if local_name != None:
if local_name.startswith('SK-'):
... |
softformance/django-twitter-photo-api | django_twitter_photo_api/admin.py | import os
import random
import string
import requests
from django import forms
from datetime import datetime
from django.urls import reverse
from django.contrib import admin
from django.conf.urls import url
from django.core.files.base import ContentFile
from django.forms.models import ModelForm
from .utils import get... |
javgh/arduino-bitcoin-candy | greenaddresscheck/greenaddresscheck.py | import asyncore
from minimalnode import MinimalBitcoinNode
from bitcointools.deserialize import extract_public_key
from PyQt4.Qt import QThread
# note: apparently we need to use a QThread if we want to
# safely communicate with other QT threads.
class GreenAddressCheck(QThread):
def __init__(self, green_add... |
Stbot/PyCrypt | stbot64_breaker.py |
###
# StBot Base 64 Coder
#
# Filename: stbot64_breaker
# Author: StBot
# Date: June 27, 2013
# Version: 1.0
#
###
# Revisions
#
# 1. total over haul. better optimization and integration
#
#
#
#
###
# TODO S and FIXME S
#
#
#
#
#####... |
avkhadiev/bbtoDijet | CRAB/crab_config_bTagDijetV11_lowlumi.py | ############################
# #
# JetHT Run 2016B #
# #
############################
from CRABClient.UserUtilities import config, getUsernameFromSiteDB
config = config()
name = 'eff_bTagDijetV11_lowlumi' # will be part of the work area name and the storage s... |
semitki/semitki | api/sonetworks/buckets/facebook.py | import os
import sys
import logging
import json
from django.conf import settings
from django.db import migrations, models
from requests_oauthlib import OAuth2Session
from requests_oauthlib.compliance_fixes import facebook_compliance_fix
from oauthlib.oauth2 import WebApplicationClient
class Facebook:
def __ini... |
viblo/pymunk | examples/using_sprites.py | """Very basic example of using a sprite image to draw a shape more similar
how you would do it in a real game instead of the simple line drawings used
by the other examples.
"""
__version__ = "$Id:$"
__docformat__ = "reStructuredText"
import math
import random
from typing import List
import pygame
import pymunk
... |
yuun/aws-apigateway-exporter | aws-apigateway-exporter.py | import sys
import os
import base64
import datetime
import hashlib
import hmac
import requests
import ConfigParser
import config
# Read args
if len(sys.argv) != 7:
print 'Usage: python aws-apigateway-exporter.py [aws-profile-name] [rest-api-id] [stage] [output-format] [extensions] [output-file-name]'
print ' ... |
fmrchallenge/fmrbenchmark-website | manage.py | #!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'fmrweb.settings')
try:
from django.core.management import execute_from_command_line
except Impor... |
FedericoV/SysBio_Modeling | project/base_project.py | from collections import OrderedDict, defaultdict
import warnings
import copy
import numpy as np
import pandas as pd
from . import utils
from loss_functions.squared_loss import SquareLossFunction
class Project(object):
"""Class to simulate experiments with a given model
Attributes
----------
model :... |
Azure/azure-sdk-for-python | sdk/media/azure-mgmt-media/azure/mgmt/media/aio/operations/_jobs_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 ... |
commaai/panda | tests/pedal/test_pedal.py | import os
import time
import subprocess
import unittest
from panda import Panda, BASEDIR
from panda_jungle import PandaJungle # pylint: disable=import-error
from panda.tests.pedal.canhandle import CanHandle
JUNGLE_SERIAL = os.getenv("PEDAL_JUNGLE")
PEDAL_SERIAL = 'none'
PEDAL_BUS = 1
class TestPedal(unittest.TestCa... |
edushare-at/py-etd | classes/equalitypolicy.py | from classes.attribdict import AttribDict
EQ_NO_POLICY = 0
EQ_CASE_INSENSITIVE = 1
EQ_INTEGER = 2
class EqualityPolicy(object):
def __init__(self,policy):
self.policy = AttribDict(policy)
def of_attribute(self,attname):
if attname in self.policy.keys():
return self.policy[attname]... |
markmuetz/stormtracks | stormtracks/ibtracsdata.py | import os
from glob import glob
import datetime as dt
from collections import Counter
import numpy as np
import netCDF4 as nc
from load_settings import settings
DATA_DIR = os.path.join(settings.DATA_DIR, 'ibtracs')
class IbtracsData(object):
'''Class used for accessing IBTrACS data
Wraps the underlying Ne... |
rizaon/limbo | limbo/plugins/map.py | # -*- coding: utf-8 -*-
"""!map <place> return a map of place. Optional "zoom" and "maptype" parameters are accepted."""
# example queries:
# !map new york city
# !map united states zoom=4
# !map united states zoom=4 maptype=satellite
try:
from urllib import quote
except ImportError:
from urllib.request import... |
shibu/pyspec | spec/behavior_pyspec_project.py | # -*- coding: ascii -*-
import sys, os
parent_path = os.path.split(os.path.abspath("."))[0]
if parent_path not in sys.path:
sys.path.insert(0, parent_path)
from pyspec import *
import StringIO
import pyspec.project
sample_project_file = """
[Config]
auto_run = True
auto_reload = False
fail_activate = False
succ... |
m0baxter/tic-tac-toe-AI | pyVers/qlearn/tictactoe.py |
import board as brd
import tttAI as ai
import subprocess as sp
class TicTacToe(object):
def __init__(self, path):
#Hold neural net AIs for when they are needed:
self.AI = ai.NNAI.fromFile(path)
#Current game AIs:
self.player1 = None
self.player2 = None
... |
andres-liiver/IAPB13_suvendatud | Kodutoo_16/Tund16gen.py | """
Module to generate lists and random numbers.
"""
import random
def __gimme_a_generator(max_number, seed):
"""
Generator to use for generating random numbers.
"""
r = random.Random(seed)
while True:
yield r.randrange(1, max_number)
def __gimme_a_list(generator, size):
"""
... |
jpgneves/hojehatransportes | hojehatransportes/fabfile.py | from fabric.api import local, settings, cd, run, env
import fabric.colors
REPO_URL = "git://github.com/jpgneves/hojehatransportes.git"
env.user = "hagreve"
def _deploy(path, branch):
print(fabric.colors.green("Deploying branch %s into %s" % (branch, path)))
with settings(warn_only=True):
local(... |
theoriginalgri/django-mssql | sqlserver_ado/operations.py | from __future__ import absolute_import, unicode_literals
import datetime
import django
from django.conf import settings
from django.db.backends import BaseDatabaseOperations
try:
from django.utils.encoding import smart_text
except:
from django.utils.encoding import smart_unicode as smart_text
try... |
keisukefukuda/mpienv | mpienv/openmpi.py | # coding: utf-8
import os.path
import re
from subprocess import check_output
import mpienv.mpibase as mpibase
from mpienv.ompi import parse_ompi_info
import mpienv.util as util
def _call_ompi_info(bin):
if not os.path.exists(bin):
raise RuntimeError("ompi_info does not exist: {}".format(bin))
out = c... |
michaelwnelson/mls-standings-scraper | mls.py | #!/usr/bin/python
import argparse
from util import scrape
parser = argparse.ArgumentParser(description='''A simple web scraper to retrieve
the standings from mlssoccer.com. The output will provide the MLS standings in a
markdown format. If no club abbreviation is provided, it will generate both
conference tables. Othe... |
rezoo/chainer | examples/chainermn/seq2seq/europal.py | from __future__ import unicode_literals
import collections
import gzip
import io
import os
import re
import numpy
import progressbar
split_pattern = re.compile(r'([.,!?"\':;)(])')
digit_pattern = re.compile(r'\d')
def split_sentence(s):
s = s.lower()
s = s.replace('\u2019', "'")
s = digit_pattern.sub(... |
H0neyBadger/cmdb | cmdb/urls.py | """cmdb 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-based... |
beckjake/python3-hglib | tests/test-summary.py | from . import common
import hglib
class test_summary(common.basetest):
def test_empty(self):
d = {'parent' : [(-1, '000000000000', 'tip', None)],
'branch' : 'default',
'commit' : True,
'update' : 0}
self.assertEquals(self.client.summary(), d)
def test_ba... |
kinpa200296/cmdpy | cmdpy.py | from cmd2 import Cmd
import logging
import sys
import os
from core import inspect_package
class CmdPy(Cmd):
ruler = '-'
default_to_shell = True
no_prompt = False
Cmd.init_done = False
Cmd.shortcuts.update({"$": 'var'})
def __init__(self, *args, **kwargs):
self.__logger = logging.get... |
katerina7479/pypdflite | pypdflite/tests.py | import unittest
import math
from unittest.mock import Mock
from session import _Session
from pdfobjects.pdfarc import PDFArc
from pdfobjects.pdfcursor import PDFCursor
from pdfobjects.pdflinegraph import PDFLineGraph
from pdfobjects.pdfpage import PDFPage
class TestPDFArc(unittest.TestCase):
def setUp(self):
... |
Widdershin/CodeEval | challenges/011-sumofintegersfromfile.py | """
https://www.codeeval.com/browse/24/
Sum of Integers from File
Challenge Description:
Print out the sum of integers read from a file.
Input Sample:
The first argument to the program will be a text file containing
a positive integer, one per line. E.g.
5
12
Output Sample:
Print out t... |
jwodder/permutation | docs/conf.py | from permutation import __version__
project = "permutation"
author = "John T. Wodder II"
copyright = "2017-2021 John T. Wodder II"
extensions = [
"sphinx.ext.autodoc",
"sphinx.ext.intersphinx",
"sphinx.ext.mathjax",
"sphinx.ext.todo",
"sphinx.ext.viewcode",
"sphinx_copybutton",
]
autodoc_defa... |
swayf/doit | doit/tools.py | """extra goodies to be used in dodo files"""
import os
import time as time_module
import datetime
import hashlib
import operator
import subprocess
from . import exceptions
from .dependency import UptodateCalculator
from .action import CmdAction, PythonAction
# action
def create_folder(dir_path):
"""create a fol... |
pyannote/pyannote-metrics | pyannote/metrics/matcher.py | #!/usr/bin/env python
# encoding: utf-8
# The MIT License (MIT)
# Copyright (c) 2012-2019 CNRS
# 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 limita... |
Azure/azure-sdk-for-python | sdk/network/azure-mgmt-network/azure/mgmt/network/v2019_11_01/aio/operations/_virtual_hubs_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 ... |
Lanceolata/code-problems | python/leetcode/Question_0015_3Sum.py | #!/usr/bin/python
# coding: utf-8
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
res = []
nums.sort()
for k in range(len(nums)):
if nums[k] > 0:
break
if k > 0 an... |
yayoiukai/signalserver | fileuploads/migrations/0037_auto_20170106_1358.py | # -*- coding: utf-8 -*-
# Generated by Django 1.10.dev20160107235441 on 2017-01-06 18:58
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('groups', '0005_auto_20161209_2103'),
('fileuploads', '0036_auto_2017... |
andrewyoung1991/supriya | supriya/tools/ugentools/PV_MagAbove.py | # -*- encoding: utf-8 -*-
from supriya.tools.ugentools.PV_ChainUGen import PV_ChainUGen
class PV_MagAbove(PV_ChainUGen):
r'''Passes magnitudes above threshold.
::
>>> pv_chain = ugentools.FFT(
... source=ugentools.WhiteNoise.ar(),
... )
>>> pv_mag_above = ugentools.PV... |
Aigrefin/py3learn | learn/tests/tests_views/tests_comeback.py | from unittest import TestCase
from unittest.mock import MagicMock, patch, call
from django.contrib.auth.models import AnonymousUser
from django.test import RequestFactory
from learn.infrastructure.database import Database
from learn.views.comeback import come_back
class ComebackTests(TestCase):
@patch("learn.vi... |
agundy/BusinessCardReader | server/app.py | import os, sys
sys.path.insert(0, os.path.abspath(".."))
from cardscan.core import processCard
from pymongo import MongoClient
from bson.objectid import ObjectId
from flask import Flask, render_template, request, redirect, url_for, abort, jsonify
from flaskext.uploads import (UploadSet, configure_uploads, IMAGES,
... |
shaun-h/PyDoc | Views/TransferManagementView.py | import ui
import console
import objc_util
class TransferManagementView (object):
def __init__(self, install_action, refresh_main_view, delete_action, refresh_transfer_action, theme_manager, transfer_manager, tv):
self.data = refresh_transfer_action()
self.delete_action = delete_action
self.install_action = insta... |
kytvi2p/torbrowser-launcher | torbrowser_launcher/settings.py | """
Tor Browser Launcher
https://github.com/micahflee/torbrowser-launcher/
Copyright (c) 2013-2014 Micah Lee <micah@micahflee.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
restrict... |
nealchenzhang/Py4Invst | Market_Analysis/untitled1.py | # -*- coding: utf-8 -*-
"""
Created on Thu Aug 10 11:01:46 2017
@author: Aian Fund
"""
import os
os.chdir('D:/Neal/Py4Invst')
from Backtest_Futures.Analyzers import Analyzer
x = Analyzer("D:/Neal/Quant/PythonProject/ValuesFile/values1.csv")
from Backtest_Futures.Analyzers import Draw_Down
x = Draw_Down("D:/Neal/Qu... |
daimon99/santicms | src/mycms/migrations/0001_initial.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2016-05-22 18:39
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migration... |
california-civic-data-coalition/django-calaccess-downloads-website | calaccess_website/management/commands/createlatestlinks.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Copy files to latest/ in the project's default file storage.
"""
import os
import re
import boto3
import random
import logging
from django.conf import settings
from calaccess_raw.models import RawDataVersion
from django.core.management.base import BaseCommand
logger = l... |
yeleman/snisi | snisi_core/models/PeriodicTasks.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: ai ts=4 sts=4 et sw=4 nu
from __future__ import (unicode_literals, absolute_import,
division, print_function)
import logging
from py3compat import implements_to_string
from django.db import models
from django.utils import timezone
from djang... |
pytorch/fairseq | fairseq/data/multilingual/sampled_multi_epoch_dataset.py | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import hashlib
import logging
import math
import numpy as np
from fairseq.data import SampledMultiDataset
from .sampled_multi_dataset impor... |
halfak/Difference-Engine | diffengine/tests/test_configuration.py | from nose.tools import eq_
from .. import configuration
def test_propagate_defaults():
input = {
'foos': {
'defaults': {
'herp': 0,
'derp': 0
},
'bar': {
'herp': 1
},
'foo': {
}
... |
v-ek/euler-sols | p1_to_p100/p7_py.py | from __future__ import division
def find_largest_factor(num):
i=1
while True:
i += 1
if num % i == 0:
if num == i:
return num
remainder = num // i
next = find_largest_factor(remainder)
return next
primes = []
num_of_primes = 10001... |
paulgb/BarbBlock | src/generate_blacklist.py | import argparse
import os
import yaml
import jinja2
def run_template_engine(blacklist_file, template_file, output_file):
template_path, template_file = os.path.split(template_file)
with open(blacklist_file) as bf:
context = yaml.load(bf)
context['domains'] = [d for blockset in context['bla... |
MalloyPower/parsing-python | front-end/testsuite-python-lib/Python-2.5/Lib/SocketServer.py | """Generic socket server classes.
This module tries to capture the various aspects of defining a server:
For socket-based servers:
- address family:
- AF_INET{,6}: IP (Internet Protocol) sockets (default)
- AF_UNIX: Unix domain sockets
- others, e.g. AF_DECNET are conceivable (see <socket.h>
... |
ConservationInternational/ldmp-earthengine-scripts | gee/time_series/src/main.py | """
Code for calculating vegetation productivity trajectory.
"""
# Copyright 2017 Conservation International
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from . import __version__
import random
import re
import json
import ee
from landdegradation impo... |
Azure/azure-sdk-for-python | sdk/cognitivelanguage/azure-ai-language-conversations/samples/sample_analyze_orchestration_app_luis_response.py | # coding=utf-8
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------
"""
FILE: sample_analyze_orchestration_app_luis_response.py
DESCRIPTION:
This sample demonstrates how to analyze user query using an orchestration p... |
buzzfeed/phonon | test/test_client.py | import unittest
import mock
from phonon.client import ShardedClient
class TestShardedClient(unittest.TestCase):
def setUp(self):
self.client = ShardedClient(hosts=['localhost1', 'localhost2'])
def test_route(self):
assert self.client.route('d') is self.client.clients[0]
assert self.... |
zhaostu/gibbon | pc/demo.py | # demo.py
# Get Arduino serial data of IMU and visualize it.
# Author: Yanglei Zhao
#############################
import traceback
import sys
from gibbon import *
class Demo(object):
def __init__(self, database=None, gesture=None, visualizer=True, record_db=None,
gesture_sample_interval = 0.05):... |
Tanych/CodeTracking | 43-Multiply-Strings/solution.py | class Solution(object):
def multiply(self, num1, num2):
"""
:type num1: str
:type num2: str
:rtype: str
"""
# not using int or str to convert
if num1=='0' or num2=='0':
return '0'
n1=len(num1)
n2=len(num2)
num1_in=... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.