repo_name stringlengths 5 104 | path stringlengths 4 248 | content stringlengths 102 99.9k |
|---|---|---|
pudo/storyweb | storyweb/assets.py | from flask.ext.assets import Bundle
from storyweb.core import assets
js_assets = Bundle(
'vendor/moment/moment.js',
'vendor/medium-editor/dist/js/medium-editor.js',
'vendor/angular/angular.js',
'vendor/angular-route/angular-route.js',
'vendor/angular-animate/angular-animate.js',
'vendor/angula... |
drdaeman/python-engineio | engineio/socket.py | import time
import six
from . import packet
from . import payload
class Socket(object):
"""An Engine.IO socket."""
upgrade_protocols = ['websocket']
def __init__(self, server, sid):
self.server = server
self.sid = sid
self.queue = self.server.async.Queue()
self.last_ping ... |
lucabezerra/VinTwitta | tweet_monitor/models.py | from django.db import models
class Hashtag(models.Model):
name = models.CharField(max_length=150)
def __str__(self):
return self.name
class Tweet(models.Model):
provider_id = models.CharField(max_length=30, unique=True)
text = models.CharField(max_length=150)
owner = models.CharField(ma... |
sleepydog1214/svg-art-generator | Setup.py | import argparse
class Setup:
def __init__(self):
self.parser = argparse.ArgumentParser()
self.parser.add_argument("file", help="Input .jpg, .jpeg, or .png file")
def GetArgs(self):
args = self.parser.parse_args()
return self.getUserFile(args.file)
# **... |
personal-robots/sar_social_stories | src/ss_process_story_ods.py | #!/usr/bin/env python
# Jacqueline Kory Westlund
# July 2016
#
# The MIT License (MIT)
#
# Copyright (c) 2016 Personal Robots Group
#
# 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 ... |
alphagov/notifications-admin | tests/app/main/views/test_email_preview.py | import re
import pytest
@pytest.mark.parametrize(
"query_args, result", [
({}, True),
({'govuk_banner': 'false'}, 'false')
]
)
def test_renders(client_request, mocker, query_args, result):
mocker.patch('app.main.views.index.HTMLEmailTemplate.__str__', return_value='rendered')
respon... |
216software/Profiles | communityprofiles/profiles/urls.py | #from django.conf.urls.defaults import *
from django.conf.urls import patterns, url, include
urlpatterns = patterns('',
url(r'^data_display/', include('data_displays.urls')),
url(r'^dataview/(?P<level_slug>[-\w]+)/(?P<geo_slug>[-\w]+)/(?P<indicator_slug>[-\w]+)/$', 'profiles.views.data_view', name='data_view')... |
Skylion007/popupcad | popupcad_deprecated/removability.py | # -*- coding: utf-8 -*-
"""
Written by Daniel M. Aukes.
Email: danaukes<at>seas.harvard.edu.
Please see LICENSE.txt for full license.
"""
from popupcad.manufacturing.multivalueoperation2 import MultiValueOperation2
import dev_tools.enum as enum
import popupcad_manufacturing_plugins.algorithms as algorithms
from popupc... |
znick/anytask | dependencies/yandex-oauth-py-0.1.1/setup.py | #!/usr/bin/env python
import sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
if sys.version_info < (2,5):
raise NotImplementedError("Sorry, you need at least Python 2.5 or Python 3.x to use yandex-oauth.")
setup(name='yandex-oauth-py',
version='0.1.1',
... |
klocey/DiversityTools | StatPak/ACE.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
#scikit-bio/skbio/diversity/alpha/_ace.py
#Greg Caporasogregcaporaso on Aug 7, 2014 API: moved base.py to _base.py
#!/usr/bin/env python
# ----------------------------------------------------------------------------
# Copyright (... |
LordSputnik/python-mbio | mbio/entities/release.py | from mbio.entities.entity import Entity
from mbio.utils import get_json
import datetime
import json
class Release(Entity):
def __init__(self, data, *args, **kwargs):
super(Release, self).__init__(*args, **kwargs)
if isinstance(data, str):
self.mbid = data
json_struct = get_... |
Elishanto/VK-Word-Cloud-2016 | start_sending_old.py | # from collections import Counter
# from datetime import datetime
import datetime
from queue import Queue
from threading import Thread
import vk_api
from vk_wc import send_cloud, worker
import config
vk_group_session = vk_api.VkApi(token=config.vk_community_token)
vk_group = vk_group_session.get_api()
vk_session = v... |
plotly/plotly.py | packages/python/plotly/plotly/validators/histogram/_xcalendar.py | import _plotly_utils.basevalidators
class XcalendarValidator(_plotly_utils.basevalidators.EnumeratedValidator):
def __init__(self, plotly_name="xcalendar", parent_name="histogram", **kwargs):
super(XcalendarValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name... |
dekuNukem/NintenDAC | firmware/old/inputs/xbox_ctrl.py | import time
import joyanalog
import threading
import collections
from inputs import get_gamepad
joycon_status = collections.OrderedDict()
joycon_status["l0"] = 0 #0
joycon_status["l1"] = 0
joycon_status["lx"] = 127
joycon_status["ly"] = 127
joycon_status["-"] = 0
joycon_status["sbl"] = 0
joycon_status["... |
introprogramming/exercises | exercises/chat/online_examples/pub_server.py | # http://learning-0mq-with-pyzmq.readthedocs.org/en/latest/pyzmq/patterns/pubsub.html
import random
import sys
import time
import zmq
port = "5556"
if len(sys.argv) > 1:
port = sys.argv[1]
int(port)
context = zmq.Context()
socket = context.socket(zmq.PUB)
socket.bind("tcp://*:{}".format(port))
while True:
... |
uiandwe/dfxp | dfxp/settings.py | import os
# Django settings for mysite project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_p... |
pavlov99/json-rpc | jsonrpc/tests/test_jsonrpc_errors.py | import json
import sys
from ..exceptions import (
JSONRPCError,
JSONRPCInternalError,
JSONRPCInvalidParams,
JSONRPCInvalidRequest,
JSONRPCMethodNotFound,
JSONRPCParseError,
JSONRPCServerError,
JSONRPCDispatchException,
)
if sys.version_info < (2, 7):
import unittest2 as unittest
el... |
widodopangestu/mysite | books/migrations/0003_auto_20170208_1149.py | # -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-02-08 11:49
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.manager
class Migration(migrations.Migration):
dependencies = [
('books', '0002_auto_20170131_0803'),
]
operations = ... |
eidonfiloi/SparseRecurrentNetwork | config/forecast_network_configuration.py | __author__ = 'ptoth'
def get_config():
params = {}
params['global'] = {
'epochs': 5
}
update_epochs = 1
verbose = 1
activation_function = "Sigmoid"
loss_function = "MSE"
activation_threshold = 0.5
min_w = -1.0
max_w = 1.0
lifetime_sparsity = 0.014
duty_cycle... |
smARTLab-liv/smartlabatwork-release | slaw_arm_navigation/nodes/youbot_arm_reconf.py | #!/usr/bin/env python
#PACKAGE = 'slaw_arm_navigation'
import rospy
from dynamic_reconfigure.server import Server
import dynamic_reconfigure.client
import actionlib
from control_msgs.msg import *
from actionlib_msgs.msg import *
from trajectory_msgs.msg import *
from sensor_msgs.msg import *
from slaw_arm_navigat... |
oseledets/pybtex | pybtex/style/names/lastfirst.py | # Copyright (c) 2010, 2011, 2012 Andrey Golovizin
#
# 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, modify, merge... |
x100up/PBB2 | handlers/api.py | import re
import tornado.web
import tornado.escape
from . import BaseHandler
html_re = re.compile('(<.*?>)')
class NewNotificationsHandler(BaseHandler):
@tornado.web.authenticated
def get(self):
notifications = []
notis = self.db.notifications.find({
'to': self.current_user['name... |
lycheng/project_euler | p1_p10.py | #!/usr/bin/python2.7
# -*- coding: utf-8 -*-
__author__ = "lycheng"
__email__ = "lycheng997@gmail.com"
from utils import timeit, is_palindromic
@timeit(times=1)
def p1():
return sum([i for i in range(1000) if i % 3 == 0 or i % 5 == 0])
@timeit(times=1)
def p2():
p = 1
n = 2
result = 0
while p <... |
ryanfitch/Python3_Koans_Solutions | python3/koans/about_string_manipulation.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from runner.koan import *
class AboutStringManipulation(Koan):
def test_use_format_to_interpolate_variables(self):
value1 = 'one'
value2 = 2
string = "The values are {0} and {1}".format(value1, value2)
self.assertEqual('The values are ... |
jstoja/TsinghuaMailSystem | src/com/mailsystem/services/DepartmentService.py | '''
Created on 8 juin 2014
@author: Romain
'''
from src.com.mailsystem.orm import Department
class DepartmentService:
@staticmethod
def listAll(db_users):
s = db_users.session()
ret = s.query(Department).all()
s.close()
return ret
@staticmethod
def selectById(db_u... |
mozman/ezdxf | src/ezdxf/render/trace.py | # Copyright (c) 2020-2021, Manfred Moitzi
# License: MIT License
from typing import (
List,
TYPE_CHECKING,
Iterable,
Tuple,
Dict,
Union,
cast,
Sequence,
)
from abc import abstractmethod
from collections import namedtuple
import math
from ezdxf.math import (
Vec2,
Vec3,
Vertex... |
OuhscBbmc/StatisticalComputing | 2015_Presentations/11_November/MonteCarlo_3Dist.py | samples = 200
r = 0.83
r2 = 0.33
r3 = 0.56
# Generate pearson correlated data with approximately cor(X, Y) = r
import numpy as np
data = np.random.multivariate_normal([0, 0, 0 ], [[1, r, r2], [r, 1, r3], [r2, r3, 1] ], size=samples)
#X, Y = data[:,0], data[:,1]
X,Y,Z = data[:,0], data[:,1], data[:,2]
#X, Y = da... |
guineawheek/spock | spock/plugins/helpers/start.py | """
This plugin creates a convenient start() method and attaches it directly
to the client. More complex bots will likely want to create their own
initialization plugin, so StartPlugin stays out of the way unless you
call the start() method. However, the start() method is very convenient
for demos and tutorials, and il... |
lucasb-eyer/heatmap | examples/simplest.py | #!/usr/bin/env python
# heatmap - High performance heatmap creation in C.
#
# The MIT License (MIT)
#
# Copyright (c) 2013 Lucas Beyer
#
# 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 witho... |
lexqt/EduTracTimingAndEstimation | timingandestimationplugin/webui.py | from pkg_resources import resource_filename
from genshi.builder import tag
from genshi.filters.transform import Transformer
from trac.core import *
from trac.perm import IPermissionRequestor
from trac.web.chrome import ITemplateProvider, ITemplateStreamFilter, add_script, add_stylesheet
from trac.web.api import IRequ... |
AutorestCI/azure-sdk-for-python | azure-batch/azure/batch/models/exit_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 ... |
johnbachman/belpy | indra/tests/test_rest_api.py | import json
from datetime import datetime
from copy import deepcopy
from nose.plugins.attrib import attr
from os import path
from rest_api.api import api
from indra.statements import *
HERE = path.dirname(path.abspath(__file__))
a = Agent('a', db_refs={'HGNC': '1234', 'TEXT': 'a'})
b = Agent('b', db_refs={'UP': 'P15... |
marksweiss/sofine | sofine/examples/portfolio_collector.py | # TODO
# - write code to perform useful queries with business rules
# - wrapper to update the data and report
# - cron somewhere
def _get_data(c, customer_id, p, password, a, account_id, e, email):
import sofine.runner as runner
import psycopg2
# sofine pipeline to collect the data
data = {}
... |
manashmndl/bluebrain | src/python/modules/cannybots/clients/joypad.py |
from cannybots.utils import arduino_map
class SimpleJoypadClient:
def __init__(self, bot):
self.bot = bot
def __removed__updateJoypad(self, x, y, b):
#print x,y,b
x = arduino_map(x, -255, 255, 0, 255)
y = arduino_map(-y, -255, 255, 0, 255)
msg = format(x,'02X') + for... |
guillaumevincent/keepass-less | tests/test_core.py | import unittest
from core import split_entry
class KeepassTestCase(unittest.TestCase):
def test_entry_split(self):
password, salt, length = split_entry('password:salt')
self.assertEqual('password', password)
self.assertEqual('salt', salt)
self.assertEqual(10, length)
def test_... |
Appleman1234/safeandsound | safeandsound-standalone.py | #!/usr/bin/env python
import configparser
import errno
import glob
import gnupg
import os
import shutil
import sys
import tarfile
import time
from distutils.dir_util import copy_tree
from subprocess import Popen
def make_sure_path_exists(path):
try:
os.makedirs(path)
except OSError as exception:
... |
zabertooth/grdbms | grdbms.py | ###############################################################################
# Module: grdbms
#
# Description: Allows consumers to make a database query using one of several
# supported packages. Thus, users are free to install any supported DBMS
# package. Returns results in a uniform structure
#
# Author: ... |
calebsmith/sebastian | sebastian/core/transforms.py | from sebastian.core import MIDI_PITCH, OFFSET_64, DURATION_64
from sebastian.core import Point, OSequence
from sebastian.core.notes import modifiers, letter
def add(properties):
def _(point):
point.update(properties)
return point
return lambda seq: seq.map_points(_)
def degree_in_key(key):
... |
GrappigPanda/GithubTODOScraper | scraper/Scraper.py | from httplib import HTTPConnection, HTTPException
from json import loads, dump
from time import sleep
from datetime import datetime
import github3
from BlobHandler import BlobHandler
from DBHandler import DBHandler
from utils import filter_files_by_ext, construct_sha_dictionary,\
flatten_sha_dict, load_json_lazy
... |
otype/aws-helpers | src/aws-instances.py | #!/usr/bin/env python
#
# aws-instances.py
#
# A simple Python script that wraps the AWS CLI (https://aws.amazon.com/cli/)
# and generates a table view of instantiated EC2 instances running on AWS.
#
import json
import subprocess
import sys
import argparse
# FUNCTIONS
#
#
def columns_layout(extended=False):
if ex... |
samwisehawkins/wrftools | get_time.py | """ Get the inital time for a simulation based on supplied arguments
Config comes from a file, specified as --config argument. Some configuration options (listed below)
can also be given at the command line, where they will override the configuration file.
See example/forecast.yaml for a full list of configurati... |
gzqichang/wa | qbase/qbase/fields.py | from django.db import models
from django.conf import settings
from django.utils import dateparse
from django.utils.translation import ugettext_lazy as _, ungettext_lazy
from copy import deepcopy
from functools import partial
from qbase.forms import TreeNodeChoiceField, TreeNodeMultipleChoiceField
class NullCharField... |
bernardkaminski/gini | frontend/src/gbuilder/Core/Connection.py | """The logical connection object that links two devices together"""
from Devices.Bridge import *
from Devices.Firewall import *
from Devices.Hub import *
from Devices.Mobile import *
from Devices.Router import *
from Devices.Cloud import *
from Devices.Tunnel import *
from Devices.Subnet import *
from Device... |
machinedesign/grammaropt | grammaropt/tests/test_rnn.py | import math
import pytest
import numpy as np
from scipy.stats import norm
from scipy.stats import poisson
from scipy.stats import beta
from grammaropt.rnn import RnnModel
from grammaropt.rnn import RnnWalker
from grammaropt.rnn import RnnDeterministicWalker
from grammaropt.rnn import RnnAdapter
from grammaropt.rnn im... |
yoophi/today-server | app/tasks.py | #import os
#from datetime import timedelta
#from celery import Celery
#from mongoengine import connect
#from db import Connection
#from log import Logger
#from models.letter_impl import LetterImpl
#from settings import Setting
#current_dir = os.path.dirname(os.path.abspath(__file__))
#setting = Setting()
#setting.... |
roblad/sensmon | sensnode/common.py | #!/usr/bin/python2
# -*- coding: utf-8 -*-
__author__ = 'Artur Wronowski'
__version__ = '0.4-dev'
__appname__ = 'sensnode-core'
__license__ = 'MIT'
__email__ = 'arteqw@gmail.com'
import datetime
import logging
import platform
import os
import subprocess
import socket
import fcntl
import struct
import simplejson as js... |
adamgilman/ems-costing | vendors/sendgrid.py | class SendGrid(object):
def getPrice(self, numberofemails):
#0-40000 on 9.95
if (numberofemails <= 40000):
return 9.95
plans = [
self._price(9.95, 40000, .0010, numberofemails), #ess40
self._price(19.95, 100000, .00075, numberofemails), #ess100
... |
plotly/plotly.py | packages/python/plotly/plotly/graph_objs/histogram2dcontour/_colorbar.py | from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType
import copy as _copy
class ColorBar(_BaseTraceHierarchyType):
# class properties
# --------------------
_parent_path_str = "histogram2dcontour"
_path_str = "histogram2dcontour.colorbar"
_valid_props = {
"bg... |
Fillll/reddit2telegram | reddit2telegram/channels/btd6/app.py | #encoding:utf-8
from utils import weighted_random_subreddit
# Subreddit that will be a source of content
subreddit = weighted_random_subreddit({
'btd6': 1.0,
# If we want get content from several subreddits
# please provide here 'subreddit': probability
# 'any_other_subreddit': 0.02
})
# Telegram cha... |
nachoaguadoc/aimlx-demos | controller/grocery_controller.py | from flask import Blueprint
from flask import Flask, abort
from flask import jsonify
from flask import render_template
from flask import request,send_from_directory
import jsonpickle
import json
import requests
import config as conf
import helpers
import os
grocery_api = Blueprint('grocery_api', __name__)
@grocery_a... |
boh1996/LectioAPI | importers/importRooms.py | import sys, os
sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'scrapers'))
sys.path.append("..")
from datetime import datetime
from database import *
import error
import sync
import rooms as roomsApi
def importRooms ( school_id, branch_id ):
try:
objectList = roomsApi.rooms({
"school_id" : school... |
steven004/nose-autochecklog | test/test_lesson2_check.py | author__ = 'Steven LI'
from test_steps import *
def my_add(*args):
ret = 0
for i in args:
ret += i
return ret
def my_mul(*args):
ret = 1
for i in args:
ret *= i
return ret
def test_basic2():
test_logger.info("To show the basic auto-log functions")
## eq(expr1, expr2,... |
fjacob21/MAX | service/src/script.py |
class script(object):
def __init__(self, name, version, desc, script_class):
self._name = name
self._version = version
self._desc = desc
self._script_class = script_class
@property
def name(self):
return self._name
@property
def version(self):
retu... |
kaideyi/KDYSample | kYPython/FluentPython/BasicLearn/OOP/Property2.py |
class Test(object):
def __init__(self):
self.__num = 100
def getNum(self):
return self.__num
def setNum(self, newNum):
self.__num = newNum
# 定义属性
num = property(getNum, setNum)
t = Test()
# t.__num = 200 # 这里相当于给 t 定义了属性恰巧叫 __num
# print(t.__num)
print(t.getNu... |
sunil3590/TIM | wolfbot/motion/advance_follower.py | import sys
sys.path.append('/wolfbot/agent')
import wolfbot as wb
from time import time
from time import sleep
sys.path.append('/boot/uboot/tim_code/sensors/')
from ir_ain import IR_AIN
import color_sensor_ISL29125
w = wb.wolfbot()
w.move(0,0)
sleep(5)
ir = IR_AIN()
ir.set_thresh(0.5)
cs = color_sensor_ISL29125.col... |
geodynamics/spatialdata | spatialdata/spatialdb/SimpleGridDB.py | # ----------------------------------------------------------------------
#
# Brad T. Aagaard, U.S. Geological Survey
#
# This code was developed as part of the Computational Infrastructure
# for Geodynamics (http://geodynamics.org).
#
# Copyright (c) 2010-2017 University of California, Davis
#
# See COPYING for license... |
andersinno/foosball | config/wsgi.py | """
WSGI config for foosball project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION``... |
Valian/python-business-logic | examples/football_match/logic.py | from business_logic import validator, validated_by
from examples.football_match import models
from examples.football_match.errors import MatchErrors
@validator
def can_shoot_goal(person, match):
if not isinstance(person, models.Player):
raise MatchErrors.CANT_SHOOT_GOAL_NOT_PLAYER
if not match.status... |
probml/pyprobml | scripts/gibbs_demo_ising.py | # -*- coding: utf-8 -*-
"""
Author : Ming Liang Ang
Based on : https://github.com/probml/pmtk3/blob/master/demos/gibbsDemoIsing.m
"""
import superimport
import numpy as np
import matplotlib.pyplot as plt
#from tqdm.notebook import tqdm
from tqdm import tqdm
import pyprobml_utils as pml
pixelX = 100
pixelY = 100
def... |
tomkralidis/GeoHealthCheck | GeoHealthCheck/factory.py | import logging
LOGGER = logging.getLogger(__name__)
class Factory:
"""
Object, Function class Factory (Pattern).
Based on: http://stackoverflow.com/questions/2226330/
instantiate-a-python-class-from-a-name
Also contains introspection util functions.
"""
@staticmethod
def create_o... |
erscott/RASLseqTools | RASLseqTools/RASLseqSeq.py |
'''
These functions extract RASLseq Probe Sequences from a fastq read
by finding the sequence between 2 adaptor strings
'''
def rasl_probe_seq_extraction(df, AD1='GGAAGCCTTGGCTTTTG', AD2='AGATCGGAAGAGCACAC'):
'''
This function returns the ligation sequence between the two adaptors
if there is a perfect... |
pelmers/dxr | dxr/build.py | from datetime import datetime
from errno import ENOENT
from fnmatch import fnmatchcase
from itertools import chain, izip, repeat
import os
from os import stat, makedirs
from os.path import islink, relpath, join, split
from shutil import rmtree
import subprocess
import sys
from sys import exc_info
from traceback import ... |
tyrylu/pyfmodex | tests/test_sound.py | import pytest
from pyfmodex.enums import SOUND_TYPE, SOUND_FORMAT, OPENSTATE, RESULT, TIMEUNIT
from pyfmodex.flags import MODE
from pyfmodex.exceptions import FmodError
def test_add_delete_syncpoint(sound):
point = sound.add_sync_point(1, TIMEUNIT.MS, "test")
assert point > 0
sound.delete_sync_point(point)... |
freifeld/cpabDiffeo | cpab/cpaNd/ExpmEff.py | #!/usr/bin/env python
"""
Created on Wed May 28 09:10:37 2014
Author: Oren Freifeld
Email: freifeld@csail.mit.edu
"""
import os
import time
from scipy.sparse.linalg import expm
import numpy as np
from multiprocessing import Pool
try:
from expm_affine_2D import expm_affine_2D
from expm_affine_2D import expm_... |
jnrbsn/daemonocle | tests/test_helpers.py | import json
import os
import posixpath
from hashlib import sha256
import psutil
import pytest
from daemonocle import DaemonError
from daemonocle.helpers import ExecWorker, FHSDaemon, MultiDaemon
@pytest.mark.skipif(not psutil.LINUX, reason='only run on Linux')
@pytest.mark.sudo
@pytest.mark.parametrize(
('prefi... |
krishnaku/ec2x | test/test_helpers.py | from mock import MagicMock
from pytest import fixture
from io import StringIO
def mock_ec2_instance(name, state='stopped', **kwargs):
instance = MagicMock(
name='ec2-instance-' + name,
tags=[
{
'Key': 'Name',
'Value': name
}
],
... |
taketwo/glasbey | test/test_glasbey.py | import os
from shutil import copyfile, move
from unittest import TestCase
from glasbey import Glasbey
import numpy
class TestGlasbey(TestCase):
def setUp(self) -> None:
file_path = os.path.dirname(os.path.realpath(__file__))
self.test_palette = file_path + "/../palettes/set1.txt"
self.test... |
li-xirong/jingwei | model_based/svms/fiksvm/trainFikConcepts.py | import sys
import os
from basic.constant import ROOT_PATH
from basic.common import makedirsforfile,checkToSkip,printStatus
from basic.annotationtable import readConcepts,readAnnotationsFrom
from svm import KERNEL_TYPE
from svmutil import svm_train
from fiksvm import svm_to_fiksvm, fiksvm_save_model, fiksvm_load_model... |
llondon6/kerr_public | kerr/mapqnms.py |
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% #
'''Class for boxes in complex frequency space'''
# The routines of this class assist in the solving and classification of
# QNM solutions
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% #
class cwbox:
# ***********... |
luispedro/waldo | waldo/tests/test_locate_load.py | from sqlalchemy import create_engine, and_
from sqlalchemy.orm import sessionmaker
import re
import waldo.locate.models
import waldo.locate.load
import waldo.locate.retrieve
from waldo.translations.models import Translation
from .backend import testdir as _testdir
_testinput1 = _testdir + 'LOCATE_human_v6_20081121.xml... |
acq4/acq4 | acq4/modules/Manager/Manager.py | # -*- coding: utf-8 -*-
from __future__ import print_function
import os
from acq4 import modules
from acq4.modules.Module import Module
from acq4.util import Qt
from acq4.util.debug import printExc
Ui_MainWindow = Qt.importTemplate(".ManagerTemplate")
class Manager(Module):
moduleDisplayName = "Manager"
mo... |
akshaykurmi/reinforcement-learning | atari_breakout/model.py | import tensorflow as tf
class DQN(tf.keras.Model):
def __init__(self, input_shape, num_actions):
super().__init__()
self.inp = tf.keras.layers.InputLayer(input_shape=input_shape)
self.conv1 = tf.keras.layers.Conv2D(filters=64, kernel_size=(7, 7), activation="relu")
self.pool1 = tf.... |
bhgames/data_check | models/helpers/base.py | from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, scoped_session
from os import environ
import yaml
if 'DCHK_ENV' not in environ:
environ['DCHK_ENV'] = 'development'
def init(engine):
global Base
global db_session
Base = declarative_base()
db_session =... |
CodeforHawaii/ACLU | backend/data/tmk/20170713/tmk_google_downloader.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright © 2017
#
# Distributed under terms of the MIT license.
import click
import requests
@click.command()
@click.option('--google_id', default="0ByFp918U5axuTFRWTkk0RGFtZnc", help="")
@click.option('--destination', default="./20170713.tmk_state.shp.zip", help=""... |
SOM-st/RPySOM | src/som/interpreter/ast/nodes/sequence_node.py | from .expression_node import ExpressionNode
from rlib.jit import unroll_safe
class SequenceNode(ExpressionNode):
_immutable_fields_ = ['_exprs?[*]']
_child_nodes_ = ['_exprs[*]']
def __init__(self, expressions, source_section):
ExpressionNode.__init__(self, source_section)
self._ex... |
PainNarrativesLab/TwitterMining | tests/test_Loggers.py | import unittest
from ObserverAndSubscribers import *
from Loggers import *
class SearchLoggerTest(unittest.TestCase):
"""
Test for Loggers.SearchLogger
"""
def setUp(self):
self.object = SearchLogger()
def tearDown(self):
pass
def test_set_log_file(self):
testpath =... |
dasap89/django_note_app | note_project/note_project/settings.py | """
Django settings for note_project project.
Generated by 'django-admin startproject' using Django 1.9.12.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""
import... |
infojasyrc/client_dataws | client_dataws/register.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
'''
Created on March 06, 2013
@author: Jose Antonio Sal y Rosas Celi
@contact: arturo.jasyrc@gmail.com
'''
import optparse
from datetime import datetime
from components.upload.uploadingSCP import uploadingSCP
from lib.html.requestAPI import requestAPI
from lib.html.leerDat... |
goldsborough/algs4 | union-find/interview/question3.py | #!/usr/local/bin/python3
# -*- coding: utf-8 -*-
"""
Successor with delete.
Given a set of N integers S={0,1,...,N−1} and a
sequence of requests of the following form:
- Remove x from S
- Find the successor of x: the smallest y in S such that y≥x.
Design a data type so that all operations (except construction)
sho... |
YixinXiao/cs | py/net/udp_broadcat.py | #!/usr/bin/evn python
# -*- encoding:utf-8 -*-
import argparse, socket
BUFSIZE = 65535
def server(interface, port):
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind((interface, port))
print 'Listening for datagrams at {}' % sock.getsockname()
while True:
data, address = sock.... |
galbramc/gpkit | gpkit/__init__.py | # -*- coding: utf-8 -*-
"""Lightweight GP Modeling Package
For examples please see the examples folder.
Requirements
------------
numpy
MOSEK or CVXOPT
scipy(optional): for complete sparse matrix support
sympy(optional): for latex printing in iPython Notebook
Attributes
----------... |
jordan-wright/talent-match | talent_match_tests.py | #!/usr/bin/env python
import os
from talent_match import app, db
from config import basedir
import unittest
class TalentMatchTestCase(unittest.TestCase):
def setUp(self):
app.config['TESTING'] = True
app.config['WTF_CSRF_ENABLED'] = False
self.app = app.test_client()
def tearDown(sel... |
jimbo1qaz/msh | util.py | """
This file contains miscellaneous utilities. Anything working on a track is excluded.
"""
import bisect as _bisect
from fractions import Fraction as _Fraction
from midi import MIDI as _MIDI
from typing import Sequence as _Sequence, Any as _Any
from classes import MshException as _MshException, TrackType as _Track... |
SiarheiGribov/pyBot | wikinews-statcats.py | import time
import requests
import login
API_url = "https://ru.wikinews.org/w/api.php"
ua = {"User-agent": "pyBot/wikinews-statcats (toolforge/iluvatarbot; iluvatar@tools.wmflabs.org) requests"}
with open("statcats.txt", "r", encoding="utf-8") as f:
lines = f.readlines()
f.close()
timestamp = str(lines[0])
pageid... |
mmcorp/django-oscar-brand | brand/app.py | from django.conf.urls import patterns, url
from oscar.core.application import Application
from brand import views
class BrandApplication(Application):
name = 'brand'
list_view = views.ListView
detail_view = views.DetailView
def get_urls(self):
urlpatterns = super(BrandApplication, self).get... |
mtth/kit | kit/base.py | #!/usr/bin/env python
"""Kit class module."""
from celery import Celery
from celery.signals import task_postrun
from celery.task import periodic_task
from flask import Flask
from flask.signals import request_tearing_down
from os.path import abspath, dirname, join
from sqlalchemy import create_engine
from sqlalchemy.... |
supermikol/coursera | Algorithm Toolbox/Week 4/majority_element/majority_element.py | # Uses python3
import sys
def get_majority_element(a, left, right):
if left == right:
return -1
if left + 1 == right:
return a[left]
#write your code here
mid = left + (right - left) // 2
left_major = get_majority_element(a, left, mid)
right_major = get_majority_element(a, mid, ... |
introprogramming/exercises | exercises/adventure/adventure.py | from locations import *
from switch import *
current_location = 'haunted forest'
here = locations[current_location]
def move(direction):
global here, current_location
new_loc = here.get_neighbor(direction)
if (new_loc):
current_location = new_loc
here = locations[current_location]
el... |
grepme/IRads | iradsmain.py | #!/usr/bin/python
import cherrypy
import config
import os.path
from database.database import Database
from database.mappings import *
from helpers import *
from irads import Irads
from iradsanalysis import IradsAnalysis
from iradsmanager import IradsManager
from iradsreport import IradsReport
from iradssearch import I... |
Edzvu/Edzvu.github.io | M2Crypto-0.35.2/M2Crypto/m2.py | from __future__ import absolute_import
"""M2Crypto low level OpenSSL wrapper functions.
m2 is the low level wrapper for OpenSSL functions. Typically you would not
need to use these directly, since these will be called by the higher level
objects you should try to use instead.
Naming conventions: All functions wrappe... |
arthurcolle/drench-udp | drench/drench.py | """Geo lookup provided courtesy of freegeoip.net"""
import argparse
import requests
import socket
import tparser
import hashlib
import struct
import reactor
import requests
from random import randrange
import peer
import time
import os
import random
import json
from string import ascii_letters, digits
from listener im... |
aapris/tilajakamo | tilajakamoweb/home/migrations/0016_auto_20160204_1306.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2016-02-04 13:06
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('home', '0015_auto_20160204_1117'),
]
operations = [
migrations.RenameField(
... |
gregvw/linsolve-experiment | test.py | import numpy as np
import cy_linsolve as cy
import sys
if __name__ == '__main__':
n = int(sys.argv[1])
A = np.random.randn(n,n)
b = np.random.randn(n)
x_np = np.linalg.solve(A,b)
x_cy = cy.py_linsolve(A,b)
print('Numpy result')
print(x_np)
print('LAPACK, C++, and Cython Result')
... |
JSchatzman/django-imager | imagersite/imager_images/migrations/0001_initial.py | # -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-01-24 05:37
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('imager_profile', '0004_auto_20170119_19... |
KartoffelCheetah/personal-website-001 | console_paint_presets.py | #!/usr/bin/env python3
#-*- coding:utf-8 -*-
from console_paint import painter
def painterColor(color) :
def wrap(func) :
def new_function(*args, **kwargs) :
painter(*args, color=color, **kwargs)
return new_function
return wrap
@painterColor('#888844')
def printWarning(*args, **kwa... |
hizardapp/Hizard | hyrodactil/applications/urls.py | from django.conf.urls import patterns, url
import views
urlpatterns = patterns('',
url(
r'^$',
views.ApplicationListView.as_view(),
name='list_applications'
),
url(
r'^list/(?P<pk>\d+)/$',
views.ApplicationListView.as_view(),
name='list_applications_opening'
),
... |
trezona-lecomte/SublimeLinter-contrib-sqlint | linter.py | #
# sqlint.py
# SQL Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Steve Purcell & Kieran Trezona-le Comte
# Copyright (c) 2015 Powershop NZ Ltd
#
# License: MIT
#
"""This module exports the Sqlint plugin class."""
from SublimeLinter.lint import Linter, util
class Sqlint(Lint... |
sai-y/swift-coding-challenge | fibonacci_test.py | #!/bin/python3
"""
Tests for the fibonacci code example
"""
import unittest
import fibonacci
from sys import stderr
import sys
def test_prime():
assert fibonacci.is_prime(2) == 1
assert fibonacci.is_prime(25) == 0
assert fibonacci.is_prime(218922995834555169026) == 0
def test_fibonacci(capsys):
fibo... |
zang-cloud/zang-python | zang/inboundxml/elements/connect.py | # -*- coding: utf-8 -*-
"""
zang.inboundxml.elements..connect
~~~~~~~~~~~~~~~~~~~
Module containing `Connect` inbound xml element
"""
from zang.inboundxml.elements.base_node import BaseNode
from zang.inboundxml.elements.agent import Agent
class Connect(BaseNode):
_allowedContentClass = (
Agent,
)
... |
edibledinos/pwnypack | tests/test_asm.py | import pytest
import pwny
target_x86_32 = pwny.Target('x86', 32)
target_x86_64 = pwny.Target('x86', 64)
target_arm_32_le = pwny.Target('arm', 32, pwny.Target.Endian.little)
target_arm_32_be = pwny.Target('arm', 32, pwny.Target.Endian.big)
target_armv7m_32_le = pwny.Target('arm', 32, pwny.Target.Endian.little, mode=p... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.