repo_name stringlengths 5 104 | path stringlengths 4 248 | content stringlengths 102 99.9k |
|---|---|---|
MarcoBuster/OrarioTreniBot | src/updates/global_messages.py | # Copyright (c) 2016-2017 The OrarioTreniBot Authors (see AUTHORS)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, cop... |
IronJew/mc-pop-log | poplog.py | import sys, datetime, os, time
from mcstatus import MinecraftServer
# GLOBALS
# List containing all the mcstatus server objects
serverList = []
# appendLog() polls the server for population data and appends it to the log
# In: The hostname and population of a server, as well as the timestamp for its retrieval time
# ... |
dotKom/onlineweb4 | apps/profiles/filters.py | import django_filters
from django.contrib.auth.models import Group
from apps.authentication.models import OnlineUser as User
class PublicProfileFilter(django_filters.FilterSet):
year = django_filters.NumberFilter(field_name="year", method="filter_year")
group = django_filters.CharFilter(method="filter_group"... |
luispedro/imread | imread/ijrois.py | # Copyright: Luis Pedro Coelho <luis@luispedro.org>, 2012-2018
# License: MIT
import numpy as np
def read_roi(fileobj):
'''
points = read_roi(fileobj)
Read ImageJ's ROI format
Parameters
----------
fileobj: should be a file-like object
Returns
-------
points: a list of points
... |
ByStudent666/XsCrypto | XsCrypto/zhanzhuanxc.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'ByStudent'
def zhanzhuanxc(p,q,e):
def egcd(a, b):
x,y, u,v = 0,1, 1,0
while a != 0:
q, r = b//a, b%a
m, n = x-u*q, y-v*q
b,a, x,y, u,v = a,r, u,v, m,n
gcd = b
return gcd, x, y
def mod... |
rbardaji/oceanobs | mooda/waterframe/plot/plot_timebar.py | """ Implementation of WaterFrame.plot_bar(key, ax=None, average_time=None)"""
import datetime
def plot_timebar(self, keys, ax=None, time_interval_mean=None):
"""
Make a bar plot of the input keys.
The bars are positioned at x with date/time. Their dimensions are given by height.
Parameters
... |
eiri/nixie | tests/test_nixie_errors.py | import unittest, uuid
from nixie.core import Nixie, KeyError
class NixieErrorsTestCase(unittest.TestCase):
def test_read_missing(self):
nx = Nixie()
self.assertIsNone(nx.read('missing'))
def test_update_missing(self):
nx = Nixie()
with self.assertRaises(KeyError):
nx.update('missing')
de... |
kagenZhao/cnBeta | CnbetaApi/CnbetaApi/urls.py | #!/usr/bin/env python3
"""CnbetaApi 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.h... |
Eylesis/Botfriend | Cogs/GameTime.py | import discord
from discord.ext import commands
import time
import datetime
import pytz
class GameTime(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command(pass_context=True)
async def time(self, ctx):
"""Displays current game time."""
locationName = self.bo... |
mhmurray/cloaca | cloaca/test/tests.py | #!/usr/bin/env python
import unittest
import logging
import logging.config
import sys
import argparse
DESCRIPTION="""
Harness for tests in the cloaca/tests/ directory.
Run all tests with '--all' or provide a list dotted names
of specific tests (eg. legionary.TestLegionary.test_legionary).
"""
# Set up logging. See l... |
rajarahulray/iDetector | tests_and_ References/table_view_text_box.py | import tkinter as tk
class ExampleApp(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
t = SimpleTable(self, 10,2)
t.pack(side="top", fill="x")
t.set(0,0,"Hello, world")
class SimpleTable(tk.Frame):
def __init__(self, parent, rows=10, columns=2):
# use black background ... |
zayfod/pyfranca | pyfranca/ast.py | """
Franca abstract syntax tree representation.
"""
from abc import ABCMeta
from collections import OrderedDict
class ASTException(Exception):
def __init__(self, message):
super(ASTException, self).__init__()
self.message = message
def __str__(self):
return self.message
class Pack... |
sampathweb/game_app | card_games/test/test_blackjack.py | #!/usr/bin/env python
"""
Test code for blackjack game. Tests can be run with py.test or nosetests
"""
from __future__ import print_function
from unittest import TestCase
from card_games import blackjack
from card_games.blackjack import BlackJack
print(blackjack.__file__)
class TestRule(TestCase):
def setUp(se... |
WyllVern/AutomaBot | setup.py | """Automabot bot for Discord."""
from os import path
from setuptools import setup, find_packages
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.rst'), 'r', encoding='utf-8') as f:
long_description = f.read()
setup(
name='automabot',
version='0.0.1.dev20170604', # see PEP... |
unbracketed/tipi | tipi/commands/base.py | """
Base classes for writing management commands (named commands which can
be executed through ``tipi.py``).
"""
import os
import sys
from ConfigParser import ConfigParser
from optparse import make_option, OptionParser
from virtualenv import resolve_interpreter
class CommandError(Exception):
"""
Exception cl... |
adamtiger/NNSharp | PythonUtils/LSTM.py | from keras.models import Sequential
from keras.layers import LSTM
import numpy as np
model = Sequential()
ly = LSTM(2, activation='tanh', recurrent_activation='relu',implementation = 1, stateful=False, batch_input_shape=(5, 3, 3))
model.add(ly)
model.compile(optimizer='sgd', loss='mse')
kernel = np.ones((3, 8))
rec_k... |
DayGitH/Python-Challenges | DailyProgrammer/DP20150401B.py | """
[2015-04-01] Challenge #208 [Intermediate] ASCII Gradient Generator
https://www.reddit.com/r/dailyprogrammer/comments/3104wu/20150401_challenge_208_intermediate_ascii/
# [](#IntermediateIcon) _(Intermediate)_: ASCII Gradient Generator
A linear colour gradient is where an image transitions through a range of colou... |
convexengineering/gplibrary | gpkitmodels/SP/aircraft/tail/tail_boom_flex.py | " tail boom flexibility "
from numpy import pi
from gpkit import Model, parse_variables, SignomialsEnabled
class TailBoomFlexibility(Model):
""" Tail Boom Flexibility Model
Variables
---------
Fne [-] tail boom flexibility factor
deda [-] wing downwash deriva... |
MacHu-GWU/elementary_math-project | start-a-project/init_project.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This script can generate automate scripts for open source python project.
Scroll to ``if __name__ == "__main__":`` for more info.
"""
from __future__ import print_function
import sys
import datetime
from os import walk, mkdir
from os.path import join, abspath, dirnam... |
cgomezfandino/Project_PTX | API_Connection_Oanda/PTX_oandaInfo.py | from configparser import ConfigParser
import v20
# Create an object config
config = ConfigParser()
# Read the config
config.read("../API_Connection_Oanda/pyalgo.cfg")
ctx = v20.Context(
'api-fxpractice.oanda.com',
443,
True,
application = 'sample_code',
token = config['oanda_v20']['access_token'],... |
mtskelton/huawei-4g-stats | stats/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='Stat',
fields=[
('id', models.AutoField(verbose... |
ggilestro/majordomo | listeners/pipe.py | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
#
# pipe.py
#
# Copyright 2014 Giorgio Gilestro <gg@kozak>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the Licen... |
azer/jsbuild | jsbuild/manifest.py | from jsbuild.attrdict import AttrDict
from time import strftime
class Manifest(AttrDict):
def __init__(self,*args,**kwargs):
super(AttrDict, self).__init__(*args,**kwargs)
self._buffer_ = None
self._parent_ = None
if not self.__contains__('_dict_'):
self['_dict_'] = {}
self['_dict_']... |
Tunous/StringSheet | setup.py | import os
from io import open
from setuptools import setup
about = {}
here = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(here, 'stringsheet', '__init__.py'), encoding='utf-8') as f:
for line in f:
if line.startswith('__'):
(key, value) = line.split('=')
about[... |
jdevesa/gists | gists/gists.py | # Copyright (c) 2012 <Jaume Devesa (jaumedevesa@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 the rights
# to use, copy, modi... |
lycheng/leetcode | tests/test_linked_list.py | # -*- coding: utf-8 -*-
import unittest
from linked_list import (delete_node, list_cycle, remove_elements,
reverse_list)
from public import ListNode
class TestLinkedList(unittest.TestCase):
def test_delete_node(self):
so = delete_node.Solution()
head = ListNode(1)
... |
pascalgutjahr/Praktikum-1 | Fourier/rechteck.py | import numpy as np
import uncertainties.unumpy as unp
from uncertainties.unumpy import (nominal_values as noms, std_devs as stds)
import matplotlib.pyplot as plt
import matplotlib as mpl
from scipy.optimize import curve_fit
plt.rcParams['figure.figsize'] = (12, 8)
plt.rcParams['font.size'] = 13
plt.rcParams['lines.line... |
lmazuel/azure-sdk-for-python | azure-mgmt-network/azure/mgmt/network/v2017_11_01/models/virtual_network_gateway_connection_list_entity_py3.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 ... |
1065865483/0python_script | test/imag_test.py | # -*- coding: utf-8 -*-
# python+selenium识别验证码
#
import re
import requests
import pytesseract
from selenium import webdriver
from PIL import Image,Image
import time
#
driver = webdriver.Chrome()
driver.maximize_window()
driver.get("https://higo.flycua.com/hp/html/login.html")
driver.implicitly_wait(30)
# 下面用户名和密码涉及到我个... |
alphagov/backdropsend | backdropsend/argumentsparser.py | import argparse
import select
def no_piped_input(arguments):
inputs_ready, _, _ = select.select([arguments.file], [], [], 0)
return not bool(inputs_ready)
def parse_args(args, input):
parser = argparse.ArgumentParser()
parser.add_argument('--url', help="URL of the target data-set",
... |
giantas/minor-python-tests | Operate List/operate_list.py | # Define a function sum() and a function multiply()
# that sums and multiplies (respectively) all the numbers in a list of numbers.
# For example, sum([1, 2, 3, 4]) should return 10,
# and multiply([1, 2, 3, 4]) should return 24.
def check_list(num_list):
"""Check if input is list"""
if num_list is Non... |
lancezlin/ml_template_py | lib/python2.7/site-packages/IPython/core/completerlib.py | # encoding: utf-8
"""Implementations for various useful completers.
These are all loaded by default by IPython.
"""
#-----------------------------------------------------------------------------
# Copyright (C) 2010-2011 The IPython Development Team.
#
# Distributed under the terms of the BSD License.
#
# The full ... |
osmanbaskaya/text-entail | run/entail_utils.py | #! /usr/bin/python
# -*- coding: utf-8 -*-
__author__ = "Osman Baskaya"
"""
Some utility functions for entailment project
"""
from collections import defaultdict as dd
from metrics import *
def get_eval_metric(metric_name):
if metric_name == "jaccard":
return jaccard_index
elif metric_name == "1":
... |
Tianyi94/EC601Project_Somatic-Parkour-Game-based-on-OpenCV | Old Code/ControlPart/FaceDetection+BackgroundReduction.py | import numpy as np
import cv2
from matplotlib import pyplot as plt
face_cascade = cv2.CascadeClassifier('/home/tianyiz/user/601project/c/haarcascade_frontalface_alt.xml')
cap = cv2.VideoCapture(0)
fgbg = cv2.createBackgroundSubtractorMOG2()
while 1:
ret, img = cap.read()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY... |
Fogapod/VKBot | bot/plugins/plugin_stop.py | # coding:utf8
class Plugin(object):
__doc__ = '''Плагин предназначен для остановки бота.
Для использования необходимо иметь уровень доступа {protection} или выше
Ключевые слова: [{keywords}]
Использование: {keyword}
Пример: {keyword}'''
name = 'stop'
keywords = (u'стоп', name, '!')
pr... |
IgniparousTempest/py-minutiae-viewer | pyminutiaeviewer/gui_editor.py | import math
from pathlib import Path
from tkinter import W, N, E, StringVar, PhotoImage
from tkinter.ttk import Button, Label, LabelFrame
from overrides import overrides
from pyminutiaeviewer.gui_common import NotebookTabBase
from pyminutiaeviewer.minutia import Minutia, MinutiaType
class MinutiaeEditorFrame(Notebo... |
p-morais/rl | rl/utils/plotting.py | """This screws up visualize.py"""
"""
import numpy as np
from matplotlib import pyplot as plt
from matplotlib.lines import Line2D
from torch.autograd import Variable as Var
from torch import Tensor
class RealtimePlot():
def __init__(self, style='ggplot'):
plt.style.use(style)
plt.ion()
se... |
lmazuel/azure-sdk-for-python | azure-mgmt-relay/tests/test_azure_mgmt_wcfrelay.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.
#---------------------------------------------------------------------... |
ACBL-Bridge/Bridge-Application | Home Files/LoginandSignupV10.py | from tkinter import *
import mysql.connector as mysql
from MySQLdb import dbConnect
from HomeOOP import *
import datetime
from PIL import Image, ImageTk
class MainMenu(Frame):
def __init__(self, parent): #The very first screen of the web app
Frame.__init__(self, parent)
w, h = parent.winfo_screen... |
devopshq/youtrack | youtrack/import_helper.py | # -*- coding: utf-8 -*-
from youtrack import YouTrackException
def utf8encode(source):
if isinstance(source, str):
source = source.encode('utf-8')
return source
def _create_custom_field_prototype(connection, cf_type, cf_name, auto_attached=False, additional_params=None):
if additional_params is ... |
ianlini/flatten-dict | src/flatten_dict/flatten_dict.py | import inspect
try:
from collections.abc import Mapping
except ImportError:
from collections import Mapping
import six
from .reducers import tuple_reducer, path_reducer, dot_reducer, underscore_reducer
from .splitters import tuple_splitter, path_splitter, dot_splitter, underscore_splitter
REDUCER_DICT = {
... |
bumshakabum/Kim_CSCI2270_FinalProject | websiteParser.py | from IPython.display import HTML
from bs4 import BeautifulSoup
import urllib
f = open('chars.txt', 'w')
r = urllib.urlopen('http://www.eventhubs.com/tiers/ssb4/').read()
soup = BeautifulSoup(r, "lxml")
characters = soup.find_all("td", class_="tierstdnorm")
count = 1
tierCharList=[]
for element in characters:
if ... |
beetbox/beets | beets/util/__init__.py | # This file is part of beets.
# Copyright 2016, Adrian Sampson.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, ... |
CSC591ADBI-TeamProjects/Product-Search-Relevance | build_tfidf.py | import pandas as pd
import numpy as np
import re
from gensim import corpora, models, similarities
from gensim.parsing.preprocessing import STOPWORDS
def split(text):
'''
Split the input text into words/tokens; ignoring stopwords and empty strings
'''
delimiters = ".", ",", ";", ":", "-", "(", ")", " ", "\t"
... |
holdlg/PythonScript | Python2/bak_2014/sys3_process.py | # -*- coding: utf-8 -*-
import win32process
import win32api
import win32con
import ctypes
import os, sys, string
TH32CS_SNAPPROCESS = 0x00000002
class PROCESSENTRY32(ctypes.Structure):
_fields_ = [("dwSize", ctypes.c_ulong),
("cntUsage", ctypes.c_ulong),
("th32P... |
Zertifica/evosnap | evosnap/merchant_applications/pos_device.py | from evosnap import constants
class POSDevice:
def __init__(self,**kwargs):
self.__order = [
'posDeviceType', 'posDeviceConnection', 'posDeviceColour', 'posDeviceQuantity',
]
self.__lower_camelcase = constants.ALL_FIELDS
self.pos_device_type = kwargs.get('pos_device_ty... |
andycasey/snob | sandbox_mixture_slf.py | import numpy as np
from snob import mixture_slf as slf
n_samples, n_features, n_clusters, rank = 1000, 50, 6, 1
sigma = 0.5
true_homo_specific_variances = sigma**2 * np.ones((1, n_features))
rng = np.random.RandomState(321)
U, _, _ = np.linalg.svd(rng.randn(n_features, n_features))
true_factor_loads = U[:, :rank]... |
kapadia/geoblend | setup.py |
import os
import shutil
from codecs import open as codecs_open
import numpy as np
from setuptools import setup, find_packages
from distutils.core import Distribution, Extension
from distutils.command.build_ext import build_ext
from distutils import errors
from Cython.Build import cythonize
from Cython.Compiler.Errors ... |
msoulier/tftpy | tftpy/TftpContexts.py | # vim: ts=4 sw=4 et ai:
"""This module implements all contexts for state handling during uploads and
downloads, the main interface to which being the TftpContext base class.
The concept is simple. Each context object represents a single upload or
download, and the state object in the context object represents the curr... |
arek125/remote-GPIO-control-server | tsl2561.py | #!/usr/bin/python
# Code sourced from AdaFruit discussion board: https://www.adafruit.com/forums/viewtopic.php?f=8&t=34922 and https://github.com/seanbechhofer/raspberrypi/blob/master/python/TSL2561.py
import sys
import time
import re
import smbus
class Adafruit_I2C(object):
@staticmethod
def getPiRevision():
... |
graingert/alembic | alembic/operations/ops.py | from .. import util
from ..util import sqla_compat
from . import schemaobj
from sqlalchemy.types import NULLTYPE
from .base import Operations, BatchOperations
import re
class MigrateOperation(object):
"""base class for migration command and organization objects.
This system is part of the operation extensibi... |
APSL/puput-demo | config/settings/common.py | # -*- coding: utf-8 -*-
"""
Django settings for puput_demo project.
For more information on this file, see
https://docs.djangoproject.com/en/dev/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/dev/ref/settings/
"""
from __future__ import absolute_import, unicode_... |
semk/iDiscover | idiscover/discover.py | # -*- coding: utf-8 -*-
#
# Discover the target host types in the subnet
#
# @author: Sreejith Kesavan <sreejithemk@gmail.com>
import arp
import oui
import ipcalc
import sys
class Discovery(object):
""" Find out the host types in the Ip range (CIDR)
NOTE: This finds mac addresses only within the subnet.
... |
denverfoundation/storybase | apps/storybase_geo/migrations/0004_auto.py | # encoding: 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):
# Adding index on 'Place', fields ['place_id']
db.create_index('storybase_geo_place', ['place_id'])
... |
EvaErzin/DragonHack | DragonHack/management/commands/dolocanjeGostisc.py | import csv
#import datetime
import numpy as np
import HackApp.models as database
from django.core.management.base import BaseCommand, CommandError
class Command(BaseCommand):
def handle(self, *args, **options):
percentageAfterNine = 0.05
percentage3to50 = 0.7
longBound = [13.375556, 16.61... |
wagoodman/bridgy | tests/test_inventory_set.py | import os
import mock
import pytest
import bridgy.inventory
from bridgy.inventory import InventorySet, Instance
from bridgy.inventory.aws import AwsInventory
from bridgy.config import Config
def get_aws_inventory(name):
test_dir = os.path.dirname(os.path.abspath(__file__))
cache_dir = os.path.join(test_dir, '... |
ac769/continuum_technologies | software/ble_live_read_graphical.py | from bluepy.btle import *
import time
import serial
from pyqtgraph.Qt import QtGui, QtCore
import pyqtgraph as pg
start_time = time.time()
data = []
data2 = []
data3 = []
data4 = []
angles = []
pg.setConfigOption('background', 'w')
pg.setConfigOption('foreground', 'k')
pen = pg.mkPen('k', width=8)
app = QtGui.QAppl... |
XKNX/xknx | xknx/io/gateway_scanner.py | """
GatewayScanner is an abstraction for searching for KNX/IP devices on the local network.
* It walks through all network interfaces
* and sends UDP multicast search requests
* it returns the first found device
"""
from __future__ import annotations
import asyncio
from functools import partial
import logging
from ty... |
ciechowoj/minion | output.py | import sublime, sublime_plugin
def clean_layout(layout):
row_set = set()
col_set = set()
for cell in layout["cells"]:
row_set.add(cell[1])
row_set.add(cell[3])
col_set.add(cell[0])
col_set.add(cell[2])
row_set = sorted(row_set)
col_set = sorted(col_set)
rows =... |
yeleman/uninond | uninond/tools.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 re
import unicodedata
import datetime
import subprocess
from py3compat import string_types, text_type
from django.utils impo... |
marceloomens/appointments | appointments/apps/common/views.py | from django.conf import settings
from django.contrib import messages
from django.forms import Form
from django.http import Http404, HttpResponse, HttpResponseBadRequest
from django.shortcuts import get_object_or_404, redirect, render
from django.views.decorators.csrf import csrf_exempt
from django.utils import timezone... |
the-blue-alliance/the-blue-alliance | src/backend/common/queries/dict_converters/event_details_converter.py | from collections import defaultdict
from typing import cast, Dict, List, NewType
from backend.common.consts.api_version import ApiMajorVersion
from backend.common.models.event_details import EventDetails
from backend.common.models.keys import TeamKey
from backend.common.queries.dict_converters.converter_base import Co... |
jbradberry/django-diplomacy | setup.py | import setuptools
with open("README.rst") as f:
long_description = f.read()
setuptools.setup(
name='django-diplomacy',
version="0.8.0",
author='Jeff Bradberry',
author_email='jeff.bradberry@gmail.com',
description='A play-by-web app for Diplomacy',
long_description=long_description,
... |
brunosmmm/hdltools | hdltools/patterns/__init__.py | """Signal pattern matching."""
import re
from typing import Union
class PatternError(Exception):
"""Pattern error."""
class Pattern:
"""Signal pattern representation."""
PATTERN_REGEX = re.compile(r"[01xX]+")
PATTERN_REGEX_BYTES = re.compile(b"[01xX]+")
def __init__(self, pattern: Union[str, ... |
rawrgulmuffins/presentation_notes | pycon2016/tutorials/measure_dont_guess/handout/pi/numpy_pi.py | # file: numpy_pi.py
"""Calculating pi with Monte Carlo Method and NumPy.
"""
from __future__ import print_function
import numpy #1
@profile
def pi_numpy(total): #2
"""Compute pi.
"""
x = numpy.random.rand(total) ... |
passuf/WunderHabit | wunderlist/migrations/0012_auto_20151230_1853.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2015-12-30 17:53
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):
dependencies = [
('wunderlist', '0011_auto_20151... |
rohitkyadav/blog-api | src/posts/api/serializers.py | from rest_framework.serializers import (
HyperlinkedIdentityField,
ModelSerializer,
SerializerMethodField,
)
from comments.api.serializers import CommentSerializer
from accounts.api.serializers import UserDetailSerializer
from comments.models import Comment
from posts.models import Post
class PostCreateUpdateSer... |
bogdal/freepacktbook | freepacktbook/slack.py | import json
import requests
class SlackNotification(object):
icon_url = "https://github-bogdal.s3.amazonaws.com/freepacktbook/icon.png"
def __init__(self, slack_url, channel):
self.slack_url = slack_url
self.channel = channel
if not self.channel.startswith("#"):
self.chann... |
memento7/KINCluster | KINCluster/__init__.py | """
KINCluster is clustering like KIN.
release note:
- version 0.1.6
fix settings
update pipeline
delete unused arguments
fix convention by pylint
now logging
- version 0.1.5.5
fix using custom settings
support both moudle and dict
- version 0.1.5.4
Update tokenizer, remove stopwords ... |
app-git-hub/SendTo | examples/save.py | import sublime, sublime_plugin
class SaveAllExistingFilesCommand(sublime_plugin.ApplicationCommand):
def run(self):
for w in sublime.windows():
self._save_files_in_window(w)
def _save_files_in_window(self, w):
for v in w.views():
self._save_existing_file_in_view(v)
def _save_existing_file_in_view(self, v)... |
gnozell/Yar-Ha-Har | lib/riotwatcher/riotwatcher.py | from collections import deque
import time
import requests
# Constants
BRAZIL = 'br'
EUROPE_NORDIC_EAST = 'eune'
EUROPE_WEST = 'euw'
KOREA = 'kr'
LATIN_AMERICA_NORTH = 'lan'
LATIN_AMERICA_SOUTH = 'las'
NORTH_AMERICA = 'na'
OCEANIA = 'oce'
RUSSIA = 'ru'
TURKEY = 'tr'
# Platforms
platforms = {
BRAZIL: 'BR1',
EUR... |
gomjellie/SoongSiri | legacy_codes/app/managers.py | from .message import *
from functools import wraps
import datetime
import pymongo
import re
from app import session
class Singleton(type):
instance = None
def __call__(cls, *args, **kwargs):
if not cls.instance:
cls.instance = super(Singleton, cls).__call__(*args, **kwargs)
return... |
natemara/aloft.py | setup.py | from setuptools import setup
with open('requirements.txt') as f:
required = f.read().splitlines()
setup(
name="aloft.py",
version="0.0.4",
author="Nate Mara",
author_email="natemara@gmail.com",
description="A simple API for getting winds aloft data from NOAA",
license="MIT",
test_suite="tests",
keywords="avi... |
DailyActie/Surrogate-Model | 01-codes/scipy-master/scipy/sparse/linalg/__init__.py | """
==================================================
Sparse linear algebra (:mod:`scipy.sparse.linalg`)
==================================================
.. currentmodule:: scipy.sparse.linalg
Abstract linear operators
-------------------------
.. autosummary::
:toctree: generated/
LinearOperator -- abstra... |
ngageoint/geoq | geoq/agents/admin.py | # -*- coding: utf-8 -*-
# This technical data was produced for the U. S. Government under Contract No. W15P7T-13-C-F600, and
# is subject to the Rights in Technical Data-Noncommercial Items clause at DFARS 252.227-7013 (FEB 2012)
from reversion.admin import VersionAdmin
from django.contrib.gis import admin
from .model... |
oblique-labs/pyVM | rpython/jit/metainterp/test/test_recursive.py | import py
from rpython.rlib.jit import JitDriver, hint, set_param
from rpython.rlib.jit import unroll_safe, dont_look_inside, promote
from rpython.rlib.objectmodel import we_are_translated
from rpython.rlib.debug import fatalerror
from rpython.jit.metainterp.test.support import LLJitMixin
from rpython.jit.codewriter.po... |
wevote/WeVoteServer | follow/models.py | # follow/models.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
from datetime import datetime, timedelta
from django.db import models
from election.models import ElectionManager
from exception.models import handle_exception, handle_record_found_more_than_one_exception,\
handle_record_not_found_exc... |
whtsky/parguments | parguments/cli.py | # Copyright (c) 2010 by Dan Jacob.
#
# Some rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and t... |
GeneralizedLearningUtilities/SuperGLU | python_module/stomp/test/p3_backward_test.py | import unittest
from stomp import backward3
class TestBackward3(unittest.TestCase):
def test_pack_mixed_string_and_bytes(self):
lines = ['SEND', '\n', 'header1:test', '\u6771']
self.assertEqual(backward3.encode(backward3.pack(lines)),
b'SEND\nheader1:test\xe6\x9d... |
Bjornkjohnson/makeChangePython | Change.py | import collections
class Change(object):
def __init__(self):
super(Change, self).__init__()
def makeChange(self, change):
coinVaulues = collections.OrderedDict()
coinVaulues['h'] = 50
coinVaulues['q'] = 25
coinVaulues['d'] = 10
coinVaulues['n'] = 5
coinVaulues['p'] = 1
coi... |
fanout/webhookinbox | api/views.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from base64 import b64encode, b64decode
import datetime
import copy
import json
from django.conf import settings
from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseNotFound, HttpResponseNotAllowed
from gripcontrol import Channel, Ht... |
mitdbg/modeldb | client/verta/verta/_swagger/_public/uac/model/UacGetOrganizationByIdResponse.py | # THIS FILE IS AUTO-GENERATED. DO NOT EDIT
from verta._swagger.base_type import BaseType
class UacGetOrganizationByIdResponse(BaseType):
def __init__(self, organization=None):
required = {
"organization": False,
}
self.organization = organization
for k, v in required.items():
if self[k] ... |
CospanDesign/python | yaml/example1.py | #! /usr/bin/python
import yaml
def main():
#f = open("data.yaml", "r")
f = open("data2.yaml", "r")
yd = yaml.load(f)
#print "YAML Data: %s" % str(yd)
for key in yd:
print "%s" % key
print "Type: %s" % str(type(yd[key]))
print str(yd[key])
print ""
def yaml_test():... |
disenone/zsync | test/parallel_task/ventilator.py | # -*- coding: utf-8 -*-
import zmq
import random
import time
def run():
context = zmq.Context()
sender = context.socket(zmq.PUSH)
sender.bind('tcp://*:5557')
sink = context.socket(zmq.PUSH)
sink.connect('tcp://localhost:5558')
print 'Press Enter when the workers are ready: '
_ = raw... |
tdickers/mitmproxy | mitmproxy/console/grideditor.py | from __future__ import absolute_import, print_function, division
import copy
import os
import re
import urwid
from mitmproxy import filt
from mitmproxy import script
from mitmproxy import utils
from mitmproxy.console import common
from mitmproxy.console import signals
from netlib.http import cookies
from netlib.http... |
wolrah/arris_stats | arris_scraper.py | #!/usr/bin/env python
# A library to scrape statistics from Arris CM820 and similar cable modems
# Inspired by https://gist.github.com/berg/2651577
import BeautifulSoup
import requests
import time
cm_time_format = '%a %Y-%m-%d %H:%M:%S'
def get_status(baseurl):
# Retrieve and process the page from the modem
... |
Tjorriemorrie/trading | 18_theoryofruns/app_old/src/main/main.py | import logging
from src.settings import JINJA_ENVIRONMENT
from src.base import BaseHandler
from src.main.models import Torrent, UserTorrent
from google.appengine.ext import ndb
from google.appengine.api import users
import arrow
from time import sleep
class IndexPage(BaseHandler):
def get(self):
# new mov... |
seanbell/opensurfaces | server/photos/management/commands/add_special.py | from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
from photos.models import PhotoSceneCategory
from photos.add import add_photo
#from licenses.models import License
class Command(BaseCommand):
args = '<flickr_dir>'
help = 'Adds photos from flickr'
def handle... |
sauloal/cnidaria | scripts/venv/lib/python2.7/site-packages/pandas/core/format.py | # -*- coding: utf-8 -*-
from __future__ import print_function
# pylint: disable=W0141
import sys
from pandas.core.base import PandasObject
from pandas.core.common import adjoin, notnull
from pandas.core.index import Index, MultiIndex, _ensure_index
from pandas import compat
from pandas.compat import(StringIO, lzip, r... |
JensTimmerman/radical.pilot | docs/source/conf.py | # -*- coding: utf-8 -*-
#
# RADICAL-Pilot documentation build configuration file, created by
# sphinx-quickstart on Mon Dec 3 21:55:42 2012.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#... |
swangui/ggrid | foobar.py | import os
import webapp2
from mako.template import Template
from mako.lookup import TemplateLookup
class MainHandler(webapp2.RequestHandler):
def get(self):
template_values = {
'some_foo': 'foo',
'some_bar': 'bar'
}
# the template file in our GAE app directory
path = os.path.join(os.path.... |
glwagner/py2Periodic | tests/twoLayerQG/testTwoLayerQG.py | import time, sys
import numpy as np
import matplotlib.pyplot as plt
sys.path.append('../../')
from py2Periodic.physics import twoLayerQG
from numpy import pi
params = {
'f0' : 1.0e-4,
'Lx' : 1.0e6,
'beta' : 1.5e-11,
'defRadius' : 1.5e4,
'H1' : 500.0,
'H2' ... |
reviewboard/rbpkg | rbpkg/package_manager/tests/test_dep_graph.py | from __future__ import unicode_literals
from rbpkg.package_manager.dep_graph import DependencyGraph
from rbpkg.testing.testcases import TestCase
class DependencyGraphTests(TestCase):
"""Unit tests for rbpkg.package_manager.dep_graph.DependencyGraph."""
def test_iter_sorted_simple(self):
"""Testing D... |
mvanveen/cargo | cargo/dock.py | import docker
from cargo.container import Container
from cargo.image import Image
# this is a hack to get `__getattribute__` working for a few reserved properties
RESERVED_METHODS = ['containers', '_client', 'images', 'info', 'start', 'stop']
class Dock(object):
"""Wrapper class for `docker-py` Client instances"""... |
artnez/faceoff | faceoff/helpers/decorators.py | """
Copyright: (c) 2012-2014 Artem Nezvigin <artem@artnez.com>
License: MIT, see LICENSE for details
"""
from functools import wraps
from flask import g, request, session, render_template, url_for, redirect
from faceoff.models.user import find_user
def templated(template_name=None):
"""
Automatically renders... |
holmes-app/holmes-alf | holmesalf/wrapper.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# This file is part of holmesalf.
# https://github.com/holmes-app/holmes-alf
# Licensed under the MIT license:
# http://www.opensource.org/licenses/MIT-license
# Copyright (c) 2014 Pablo Aguiar scorphus@gmail.com
from holmesalf import BaseAuthNZWrapper
from alf.client i... |
alexwaters/python-readability-api | examples/read-bookmarks.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
read-bookmark.py
~~~~~~~~~~~~~~~~
This module is an example of how to harness the Readability API w/ oAuth.
This module expects the following environment variables to be set:
- READABILITY_CONSUMER_KEY
- READABILITY_CONSUMER_SECRET
- READABILITY_ACCESS_TOKEN
- READA... |
Fizzadar/pyinfra | tests/test_api/test_api.py | from unittest import TestCase
from paramiko import SSHException
from pyinfra.api import Config, State
from pyinfra.api.connect import connect_all
from pyinfra.api.exceptions import NoGroupError, NoHostError, PyinfraError
from ..paramiko_util import PatchSSHTestCase
from ..util import make_inventory
class TestInven... |
sigopt/sigopt-python | test/cli/test_cli_config.py | import click
import mock
import pytest
from click.testing import CliRunner
from sigopt.cli import cli
class TestRunCli(object):
@pytest.mark.parametrize('opt_into_log_collection', [False, True])
@pytest.mark.parametrize('opt_into_cell_tracking', [False, True])
def test_config_command(self, opt_into_log_collect... |
cmancone/ezgal | tests/zf_grid/test_get_rest_mags.py | import unittest
import ezgal.zf_grid
import numpy as np
import math
# I put the test data for the zf_grid tests in
# tests.zf_grid instead of in tests because
# there is a lot of data but it is all
# specific for this test.
import tests.zf_grid
class test_get_rest_mags(tests.zf_grid.test_zf_grid):
def test_get_r... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.