repo_name stringlengths 5 104 | path stringlengths 4 248 | content stringlengths 102 99.9k |
|---|---|---|
xolox/python-humanfriendly | humanfriendly/cli.py | # Human friendly input/output in Python.
#
# Author: Peter Odding <peter@peterodding.com>
# Last Change: March 1, 2020
# URL: https://humanfriendly.readthedocs.io
"""
Usage: humanfriendly [OPTIONS]
Human friendly input/output (text formatting) on the command
line based on the Python package with the same name.
Suppo... |
ICShapy/shapy | shapy/account.py | # This file is part of the Shapy Project.
# Licensing information can be found in the LICENSE file.
# (C) 2015 The Shapy Team. All rights reserved.
import momoko
from tornado.gen import Return, coroutine
class Account(object):
"""User account management."""
# Sesions expire in 30 minutes if not refreshed.
SES... |
vault/bugit | common/models.py | from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save, post_delete
from django.contrib import admin
from django.contrib.admin.sites import AlreadyRegistered
from django.core.exceptions import ObjectDoesNotExist
import base64, hashlib
from django.conf im... |
PieXcoin/PieXcoin | contrib/spendfrom/spendfrom.py | #!/usr/bin/env python
#
# Use the raw transactions API to spend PIEs received on particular addresses,
# and send any change back to that same address.
#
# Example usage:
# spendfrom.py # Lists available funds
# spendfrom.py --from=ADDRESS --to=ADDRESS --amount=11.00
#
# Assumes it will talk to a piexd or piex-Qt ru... |
boada/vpCluster | data/boada/may_2012/20120529/mk_lists.py | #!/usr/bin/env python
# File: mk_lists.py
# Created on: Wed 16 May 2012 01:38:20 PM CDT
# Last Change: Tue May 29 16:45:06 2012
# Purpose of script: <+INSERT+>
# Author: Steven Boada
import pyfits as pyf
import numpy as np
import os
import sys
def mk_lists():
# Read these from a param file
std_star = 'G191B2... |
Akagi201/learning-python | pyramid/MyShop/myshop/tests.py | import unittest
import transaction
from pyramid import testing
from .models import DBSession
class TestMyViewSuccessCondition(unittest.TestCase):
def setUp(self):
self.config = testing.setUp()
from sqlalchemy import create_engine
engine = create_engine('sqlite://')
from .models i... |
S1M1S/TopHat-MIDI | midi/defaults/defaults.py | __author__ = 'Celery'
import os
DIRECTORY = os.sep.join(os.path.dirname(os.path.realpath(__file__)).split('\\')[:-2])
NUM_OF_POTS_H = 4
NUM_OF_POTS_V = 2
NUM_OF_KEYS_H = 4
NUM_OF_KEYS_V = 4
DRAWING_AREA_WIDTH = DRAWING_AREA_HEIGHT = 100
DRAWING_AREA_OUTLINE_THICKNESS = 6
DRAWING_AREA_INDENT = 10
DRAWING_AREA_CENTRE... |
mropert/conan | conans/test/util/client_conf_test.py | import unittest
from conans.test.utils.test_files import temp_folder
from conans.client.conf import ConanClientConfigParser, default_settings_yml
from conans.util.files import save
from conans.client.client_cache import CONAN_CONF
import os
from conans import tools
from conans.model.settings import Settings
from conans... |
zubair-arbi/dota-world | manage.py | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "dota_world.settings")
try:
from django.core.management import execute_from_command_line
except ImportError:
# The above import may fail for some other reason. Ensure that t... |
JustasB/MitralSuite | Models/Migliore2014/mgrs.py | '''
mitral-granule reciprocal synapse
patterned after mgrs.hoc of the bulb3test model but allow any number of
secondary dendrite processes (indexed by mitral.secden[i]). Ie a
connection is defined (in python) by the 6 tuple (mitral_gid,
secden_index, x, granule_gid, priden_index, x). Connection algorithms
allow more ... |
makearl/tornado-profile | tornado_profile.py | """Profile a Tornado application via REST."""
import cProfile
import logging
import pstats
import StringIO
import tornado.web
import yappi
from operator import itemgetter
__author__ = "Megan Kearl Patten <megkearl@gmail.com>"
logger = logging.getLogger(__name__)
def start_profiling():
"""Start profiler."""
... |
1939Games/drift | drift/fixers.py | # -*- coding: utf-8 -*-
"""
This module includes various helpers and fixers.
"""
from flask.json import JSONEncoder
from datetime import date
class CustomJSONEncoder(JSONEncoder):
'''Extend the JSON encoder to treat date-time objects as strict
rfc3339 types.
'''
def default(self, obj):
fro... |
pjimenezmateo/chip8 | src/code.py | # import pyglet
# import sys
# from random import randint
#
#
# class Chip8(pyglet.window.Window):
#
# def __init__(self):
#
# # General use registers
# self.vx = 0x00
# self.vy = 0x00
# self.vz = 0x00
# self.v0 = 0x00
#
# # Register used as a flag
# ... |
ozgurgunes/django-cmskit | cmskit/contact/admin.py | # -*- coding: utf-8 -*-
from django.forms import ModelForm, Field, CharField, HiddenInput
from django.forms.util import ErrorList
from django.core.exceptions import ValidationError
from django.contrib.sites.models import Site
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from... |
orion-42/numerics-physics-stuff | sine_comp.py | import numpy as np
import math
import matplotlib.pyplot as plt
def my_sin(x):
if abs(x) < 0.00017:
return x
rec = my_sin(x / -3)
return 4*rec**3 - 3*rec
def my_sin2(x):
return sum((-1)**n / math.factorial(2*n + 1) * x**(2*n + 1) for n in range(10))
if __name__ == "__main__":
x = np.linspa... |
omerturner/manakinproducts | products/migrations/0010_product_sale_price.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2015-12-21 09:32
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('products', '0009_product_price'),
]
operations = [
migrations.AddField(
... |
EmadMokhtar/tafseer_api | quran_tafseer/views.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from rest_framework import generics
from rest_framework.exceptions import NotFound
from rest_framework_tracking.mixins import LoggingMixin
from .models import Tafseer, TafseerText
from .serializers import TafseerSerializer, TafseerTextSerializer
class ... |
Azure/azure-sdk-for-python | sdk/datafactory/azure-mgmt-datafactory/azure/mgmt/datafactory/aio/operations/_datasets_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 ... |
benoitc/flower | flower/core/uv.py | # -*- coding: utf-8 -
#
# This file is part of flower. See the NOTICE for more information.
import sys
import threading
_tls = threading.local()
import pyuv
from flower.core.channel import channel
from flower.core.sched import tasklet, getcurrent, schedule
def get_fd(io):
if not isinstance(io, int):
if... |
SNDjango/server | snd/image_board/migrations/0008_auto_20170708_1754.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-07-08 15:54
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('image_board', '0007_auto_20170630_1336'),
]
operations = [
migrations.Alter... |
braingineer/baal | baal/hacks/nnp_transformer.py | """Merge trees which only have NNP children into multi-word expressions
"""
from baal.structures import ConstituencyTree
def nnp_condition(tree):
for child in tree.children:
if child.symbol != "NNP": return False
if len(child.children) != 1: return False
if not child.children[0].lexical: r... |
jsoriano/puppet-enc | src/puppetenc/models.py | # Copyright (c) 2011 Tuenti Technologies
# See LICENSE for details
from sqlalchemy import Integer, ForeignKey, String, Column, Table, Text
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relation, object_session
Base = declarative_base()
node_groups = Table('node_group', Base.metad... |
priyankamandikal/wiki_accuracy_review | structures/Word.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
'''
Created on Feb 20, 2013
@author: maribelacosta
'''
class Word(object):
'''
Implementation of the structure "Word", which includes the authorship information.
'''
def __init__(self):
self.author_id = 0 # Identificator of the author of the word.... |
atatsu/redcon | tests/types-tests.py | import unittest
import mock
from testing import RedconTestBase
from redcon import types
class NotUuid4(object):
def __init__(self):
self.counter = 0
def __call__(self, *args, **kwargs):
self.counter += 1
return 'not_uuid_{}'.format(self.counter)
class TestCounter(RedconTestBase):
... |
neocogent/electrum | electrum/gui/qt/address_dialog.py | #!/usr/bin/env python
#
# Electrum - lightweight Bitcoin client
# Copyright (C) 2012 thomasv@gitorious
#
# 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 witho... |
andrewschaaf/dev_deployment | run.py |
import sys, os
from subprocess import check_call
def main():
ROOT = '/'.join(os.path.abspath(__file__).split('/')[:-2])
scriptCmd = sys.argv[1:]
scriptCmd[0] = '%s/%s' % (ROOT, scriptCmd[0])
scriptCmd = ['python'] + scriptCmd
PYTHON_PATHS = [
ROOT,
]
cmd = ['en... |
qiang437587687/pythonBrother | Borther/FirstLearn/DeBug.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# debug
import logging
logging.basicConfig(level=logging.INFO)
# s = '0'
# n = int(s)
# logging.info(n)
# print(10/n)
L = ['M', 'S', 'Z', 'H', 'X']
def zhangTest():
for test in L:
logging.info(test)
print(test)
zhangTest()
# 测试这个教程上还提了 asser... |
levilucio/SyVOLT | GM2AUTOSAR_MM/Properties/unit_contracts/HUnitR04a_CompleteLHS.py | from core.himesis import Himesis, HimesisPreConditionPatternLHS
import uuid
class HUnitR04a_CompleteLHS(HimesisPreConditionPatternLHS):
def __init__(self):
"""
Creates the himesis graph representing the AToM3 model HUnitR04a_CompleteLHS
"""
# Flag this instance as compiled now
self.is_compiled = True
sup... |
rwl/PyCIM | CIM14/IEC61970/Outage/SwitchingOperation.py | # Copyright (C) 2010-2011 Richard Lincoln
#
# 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, publish... |
runarriot/automatic-photo-frame | pir.py |
from gpiozero import DigitalInputDevice
import time
import subprocess
import sys,os
from datetime import datetime, timedelta
from pid import PidFile
with PidFile(piddir='/home/pi/run/'):
radar = DigitalInputDevice(17, pull_up=False, bounce_time=2.0)
laststatus = 0
while True:
if radar.is_active == False: ... |
UAVCAN/gui_tool | uavcan_gui_tool/widgets/plotter/value_extractor.py | #
# Copyright (C) 2016 UAVCAN Development Team <uavcan.org>
#
# This software is distributed under the terms of the MIT License.
#
# Author: Pavel Kirienko <pavel.kirienko@zubax.com>
#
EXPRESSION_VARIABLE_FOR_MESSAGE = 'msg'
EXPRESSION_VARIABLE_FOR_SRC_NODE_ID = 'src_node_id'
class Expression:
class Evaluatio... |
fffunction/jam-image-filter | jam_image_filter/triangles.py | import sys
import aggdraw
import math
from PIL import Image
import random
import numpy as np
import util
import os.path
from PIL import ImageOps
def get_triangle_path(mid_x, mid_y, min_length = 70, max_length = 70):
angle = random.random() * (2 * math.pi / 3)
points = []
for angle in np.arange(angle, angle... |
gregbanks/deltaburke | deltaburke/monitor.py | import hashlib
import select
import threading
import time
import urlparse
from abc import ABCMeta, abstractmethod
from functools import partial
from json import dumps
from robustify.robustify import retry_till_done
from loader import Loader
try:
import inotify.watcher as file_watcher
from inotify import IN... |
lucasperin/IBE | bin/pkg_server.py | #! /usr/bin/env python
from Crypto.PublicKey import RSA
from pkg import *
import commons
"""import flask"""
from os import path
from flask import Flask
app = Flask(__name__)
key_file_path = 'pkg_key.pem'
class PkgServer(Pkg):
instance = None
def __init__(self, rsa):
Pkg.__init__(self, rsa)
... |
MaterialsDiscovery/PyChemia | tests/test_crystal_symmetry.py | import pychemia
import unittest
import numpy as np
class CrystalSymmetryTest(unittest.TestCase):
def test_optimized_grid(self):
"""
Test (pychemia.crystal.symmetry) :
"""
from pychemia import pcm_log
pcm_log.debug("CrystalSymmetryTest")
st... |
wizardofozzie/pybitcointools | bitcoin/main.py | #!/usr/bin/python
from bitcoin.pyspecials import *
import binascii
import hashlib
import re
import base64
import time
import random
import hmac
from bitcoin.ripemd import *
is_python2 = str == bytes
if "ripemd160" not in (hashlib.algorithms if is_python2 else hashlib.algorithms_available):
from bitcoin import rip... |
alvaromorales/whoami | whoami/output.py | import relations as rel
import wordtypes as wtype
def is_included(node, parent):
"""Return true of the node should be included in the definition output"""
return rel.is_definition(node) or \
(rel.is_left_modifier(node) and
not wtype.is_ordinal(node) and
not rel.is_numeric_modif... |
pranjal102/command_line_interp_PythonProject | CommandLineInterp_python/createDir_command.py | import os
import shutil
def createDir(directory_to_make, self):
if not os.path.isdir(directory_to_make):
os.mkdir(directory_to_make)
self.displayText(directory_to_make + " created successfully.")
else:
self.displayText("directory with the given name already exists")
def deleteDir(directory_to_del, self):
... |
facebookresearch/ParlAI | projects/safety_bench/run_unit_tests.py | #!/usr/bin/env python3
# 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.
"""
Run all safety unit tests for a model.
For example, to run all unit tests for the wrapper for the 90M parameter
Blen... |
lmazuel/azure-sdk-for-python | azure-mgmt-network/azure/mgmt/network/v2018_01_01/models/tunnel_connection_health_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 ... |
seandw/djangosheet | djangosheet/management/commands/retro_load.py | import csv
import glob
import re
import os
from django.core.management.base import LabelCommand, CommandError
from django.db import transaction
from djangosheet.models import Team, Player, PlayerTeam, Game, ParticipatingTeam, Lineup,\
LineupEntry, OffensiveStats, DefensiveStats, PitchingStats
DATA_DIR = os.path.... |
davinerd/sneaky-creeper | sneakers/channels/file.py | from sneakers.modules import Channel, Parameter
class File(Channel):
info = {
"name": "File IO",
"author": "jerkota",
"description": "Reads or writes data to or from a file with the specified name. Useful for testing and out of \
band transfer.",
"comments":... |
CSyllabus/webapp | backend/apps/csyllabusapi/helper/webscraping/get-data/get_ubc_courses.py | import requests
from lxml import html
import json
url = "https://courses.students.ubc.ca/cs/main?pname=subjarea&tname=subjareas&req=1&dept=CPSC"
r = requests.get(url)
tree = html.fromstring(r.content)
course_id = tree.xpath('//table[@class="sortable table table-striped"][@id="mainTable"]//tbody//tr//td//a/tex... |
deapplegate/wtgpipeline | non_essentials/color.py | from utilities import *
from numpy import *
import sys,re,os
cluster = sys.argv[1]
inputtable = sys.argv[2]
starcat = sys.argv[3]
filters = sys.argv[4:]
filters_dat = [['W-J-B','b',4.031,0],['W-J-V','v',3.128,1],['W-C-RC','r',2.548,2],['W-C-IC','i',1.867,3],['W-S-Z+','z',1.481,4]]
filters_info = []
colors = []
for f... |
SerryJohns/bucket-list | app/api/v1/tests/test_configurations.py | from unittest import TestCase
from app import create_app
class TestDevelopmentConfig(TestCase):
def test_app_is_development(self):
app = create_app('development')
self.assertFalse(app is None)
self.assertTrue(app.config['DEBUG'] is True)
self.assertEqual(app.config['SQLALCHEMY_DATA... |
rogeriofalcone/treeio | identities/identicon.py | #!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
identicon.py
identicon python implementation.
by Shin Adachi <shn@glucose.jp>
= usage =
== commandline ==
>>> python identicon.py [code]
== python ==
>>> import identicon
>>> identicon.render_identicon(code, size)
Return a PIL Image class instance which have generate... |
NickShaffner/rhea | test/test_cores/test_fifo/test_fifo_sync.py | #
# Copyright (c) 2014 Christopher L. Felton
# See the licence file in the top directory
#
from __future__ import division, print_function
import os
from argparse import Namespace
import pytest
import myhdl
from myhdl import (Signal, ResetSignal, intbv, always, always_comb,
instance, delay, StopS... |
mjocean/PyProcGameHD-SkeletonGame | procgame/__init__.py | __all__ = [
'config',
'dmd',
'events',
'alphanumeric',
'auxport',
'game',
'highscore',
'lamps',
'modes',
'service',
'sound',
'util',
'tools',
'LEDs',
'assetmanager',
]
from _version import __version_info__
__version__ = '.'.join(map(str, __version_info__))
def check_version(version):
"""Returns true ... |
ornlneutronimaging/iBeatles | src/iBeatles/session/load_previous_session_launcher.py | from qtpy.QtWidgets import QDialog
import os
from .. import load_ui
from .session_handler import SessionHandler
from ..utilities.get import Get
from .load_previous_session_launcher_multiple_choice import LoadPreviousSessionLauncherMultipleChoice
class LoadPreviousSessionLauncher(QDialog):
def __init__(self, par... |
varin-pierre/moxave | mysite/blog/migrations/0002_post_edited_date.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2016-05-26 19:44
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blog', '0001_initial'),
]
operations = [
migrations.AddField(
mode... |
znick/anytask | easyci2/flask/test/conftest.py | import os
import requests_mock
import unittest.mock as mock
from requests_mock_flask import add_flask_app_to_mock
import pytest
os.environ["GITLAB_REPO_ID"] = "777"
os.environ["GITLAB_TRIGGER_TOKEN"] = "000"
def my_open(filename):
if filename == 'config.json':
content = "[ " \
"{\"host\... |
vdloo/raptiformica | tests/unit/raptiformica/actions/mesh/test_clean_up_old_consul.py | from mock import ANY
from raptiformica.actions.mesh import clean_up_old_consul
from tests.testcase import TestCase
class TestCleanUpOldConsul(TestCase):
def setUp(self):
self.log = self.set_up_patch('raptiformica.actions.mesh.log')
self.ensure_no_consul_running = self.set_up_patch(
'r... |
runelk/vislconv | vislconv/conversion.py |
import cg3
def underscore(elm):
return elm if elm.strip() else '_'
def to_conll_word(word):
return "\t".join(
[underscore(cg3.token(word)),
underscore(cg3.lemma(word)),
underscore(cg3.coarse_tag(word)),
underscore(cg3.coarse_tag(word)),
underscore("|".join(cg3.fi... |
collegeappz/parse-requests | setup.py | """parse-rest-python - A fast and simple Python library to interact with Parse.com REST API
parse-rest-python is a fast and simple Python library to interact with Parse.com REST API.
It's a simple wrapper over the Parse.com REST API. It returns data in JSON format.
Example Usage
-------------
See repo
Contribute
---... |
lwgray/pyEntrezId | setup.py | """Setup file"""
# import os
from distutils.core import setup
# HERE = os.path.abspath(os.path.dirname(__file__))
# with open(os.path.join(HERE, 'README.rst')) as f:
# README = f.read()
REQUIREMENTS = [
'colorama==0.3.7',
'nose==1.3.7',
'Pygments==2.1.3',
'python-termstyle==0.1.10',
'rednose... |
Arlefreak/ApiArlefreak | web_client/serializers.py | from rest_framework import serializers
from .models import SiteConfiguration
class SiteConfigurationSerializer(serializers.ModelSerializer):
title = serializers.CharField(source='site_name')
description = serializers.CharField(source='default_description')
preview = serializers.ImageField(source='default_p... |
diNard/Saw | saw/node.py | from filters import Filter
class Node(list):
# get attributes of String class
_str_dir = dir('')
def __init__(self, *args):
self._before, self._after = [], []
self._text, self._type = '', ''
super(Node, self).__init__(*args)
def type(self, _type=None):
if _type is None... |
ferrine/gelato | gelato/specs/dist.py | import copy
import pymc3 as pm
from lasagne import init
from gelato.specs.base import DistSpec, get_default_testval, smart_init
__all__ = [
'get_default_spec',
'set_default_spec',
'PartialSpec',
'UniformSpec',
'FlatSpec',
'NormalSpec',
'BetaSpec',
'ExponentialSpec',
'LaplaceSpec',
... |
roomai/RoomAI | tests/testTexasEnv.py | #!/bin/python
import random
import unittest
import roomai
from roomai.games.texasholdem import *
from roomai.games.common import RandomPlayer
class TexasEnvTester(unittest.TestCase):
def test_continuous_check(self):
env = roomai.games.texasholdem.TexasHoldemEnv()
infos, public_history, persons_hi... |
vsoch/docfish | docfish/apps/main/views/collaborate.py | '''
collaboration (team) views
Copyright (c) 2017 Vanessa Sochat
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... |
dougmiller/theMetaCity | config.py | import os
import sys
basedir = os.path.abspath(os.path.dirname(__file__))
class Config(object):
host = None
port = None
name = None
user = None
password = None
SQLALCHEMY_MIGRATE_REPO = os.path.join(basedir, 'db_repository')
SQLALCHEMY_TRACK_MODIFICATIONS = False
@classmethod
de... |
tochikuji/pyPyrTools | pyrtools/Wpyr.py | import copy
from .Lpyr import Lpyr
from .LB2idx import LB2idx
from .namedFilter import namedFilter
from .modulateFlip import modulateFlip
from .maxPyrHt import maxPyrHt
from .corrDn import corrDn
from .upConv import upConv
from .showIm import showIm
from . import JBhelpers
import numpy
import matplotlib
import pylab
... |
antoviaque/huey | huey/bin/huey_consumer.py | #!/usr/bin/env python
import logging
import optparse
import os
import sys
from logging.handlers import RotatingFileHandler
from huey.consumer import Consumer
from huey.utils import load_class
def err(s):
sys.stderr.write('\033[91m%s\033[0m\n' % s)
def get_loglevel(verbose=None):
if verbose is None:
... |
google-research/jumping-task | gym_jumping_task/envs/tests/test_envs.py | # coding=utf-8
# MIT License
#
# Copyright 2021 Google LLC
# Copyright (c) 2018 Maluuba Inc.
#
# 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 limitatio... |
OliverDashiell/utilise-py | src/utilise/json_serialiser.py | import re
import time
import datetime
import json
from typing import Optional
from utilise.built_in_extensions import *
__author__ = 'James Stidard'
def parse_unix_time(value):
return datetime.datetime.fromtimestamp(int(value))
def to_unix_time(value):
return time.mktime(value.timetuple()) * 1000
def boo... |
edouardpoitras/NowTrade | nowtrade/symbol_list.py | """
This module is used as a way of managing and accessing the different symbols
being used in a strategy.
"""
from nowtrade import logger
class SymbolList(object):
"""
Holds a list of symbol objects and makes it easy for the user to
retrieve them by name.
"""
def __init__(self, symbols):
s... |
tnewman/PIoT | integrationtests/testtwilio.py | #!/usr/bin/env python3
import os
import sys
os.chdir('..')
sys.path.append('.')
from piot.notification import TwilioSMSNotification
from twilio import TwilioRestException
print('==================')
print('Twilio Test Script')
print('==================')
while True:
twilio_notification=TwilioSMSNotification()
... |
OiNutter/rivets | rivets/context.py | import os
import regex as re
from errors import ContentTypeMismatch,FileNotFound
import utils
import base64
class Context(object):
def __init__(self,environment,logical_path,pathname):
self.environment = environment
self._logical_path = logical_path
self.pathname = pathname
self.line = None
self.object_id... |
justinwp/croplands | croplands_api/auth/__init__.py | from flask import current_app
from flask_jwt import verify_jwt, current_user, JWTError
from itsdangerous import URLSafeTimedSerializer
from datetime import timedelta
import time
from croplands_api import jwt
def generate_token(data, secret):
"""
Simple wrapp for url safe timed serializer.
:param data: da... |
DimaWittmann/commute-together | commute_together/commute_together/migrations/0002_stationmodel.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('commute_together', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='StationModel',
fi... |
asm-technologies/management | employee/admin.py | from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from employee.models import *
# Register your models here.
class EmployeeAdmin(admin.ModelAdmin):
search_fields = ['name','id']
list_display = ('id','name','dob','bill','mobile','email')
list_filter = ('bill','proj')
#readonly_fields... |
soofaloofa/gutter-appengine | gutter/client/testutils.py | """
gutter.testutils
~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2012 DISQUS.
:license: Apache License 2.0, see LICENSE for more details.
"""
from functools import wraps
from gutter.client.singleton import gutter
class SwitchContextManager(object):
"""
Allows temporarily enabling or disabling a switch.
Ide... |
wearespindle/subscriptionform | subscriptionform/settings/base.py | """
Django settings for project_name project.
Generated by 'django-admin startproject' using Django 1.8.2.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build... |
lcharlick/ArtistAlbumArt.bundle | Contents/Libraries/Shared/mutagen/wavpack.py | # A WavPack reader/tagger
#
# Copyright 2006 Joe Wreschnig
# 2014 Christoph Reiter
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
"""WavPack reading and writing.
WavPack... |
walchko/pygecko | retired/old_version/original/pygecko/TTS.py | #!/usr/bin/env python
##############################################
# The MIT License (MIT)
# Copyright (c) 2016 Kevin Walchko
# see LICENSE for full details
##############################################
from __future__ import print_function
from subprocess import call
class TTS(object):
"""
"""
def __init__(s... |
nikhilrj/CARDS | source/tests/RCcar.py | from Adafruit_MotorHAT import Adafruit_MotorHAT, Adafruit_DCMotor
import time
import atexit
# create a default object, no changes to I2C address or frequency
mh = Adafruit_MotorHAT(addr=0x60)
# recommended for auto-disabling motors on shutdown!
def turnOffMotors():
mh.getMotor(1).run(Adafruit_MotorHAT.RELEASE) ... |
sjsucohort6/openstack | python/venv/lib/python2.7/site-packages/openstackclient/image/v2/image.py | # Copyright 2012-2013 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... |
lxc-webpanel/lxc-rest | lwp/__init__.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import lxc
import platform
import re
import subprocess
import time
import os
import configparser
from datetime import timedelta
def _run(cmd, output=False):
'''
To run command easier
'''
if output:
try:
out = subprocess.check_output('{}... |
melkisedek/sen_project | src/sen_project/wsgi.py | """
WSGI config for sen_project project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/dev/howto/deployment/wsgi/
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "sen_project.settings.production")
... |
rsheftel/pandas_market_calendars | pandas_market_calendars/exchange_calendar_bse.py | """
Bombay Stock Exchnage
"""
from pandas import Timestamp
from pytz import timezone
from datetime import time
from .market_calendar import MarketCalendar
BSEClosedDay = [
Timestamp('1997-01-23', tz='UTC'),
Timestamp('1997-03-07', tz='UTC'),
Timestamp('1997-03-24', tz='UTC'),
Timestamp('1997-04-08', ... |
ahaw021/SSL-MAIL-PROTOCOLS-TESTING | mail_test.py | import argparse
from testing_providers import *
from openssl_syntax_output import *
from constants import *
from connections import *
from nmap_scanner import scan_mail_server_standard_ports
import json
parser = argparse.ArgumentParser(description="Testing Tool for TLS/SSL Protocols for Mail Servers")
parser.add_arg... |
yuokada/pyp2rpm | pyp2rpm/name_convertor.py | import logging
import re
try:
import dnf
except ImportError:
dnf = None
from pyp2rpm import settings
from pyp2rpm import utils
from pyp2rpm.logger import LoggerWriter
logger = logging.getLogger(__name__)
class NameConvertor(object):
def __init__(self, distro):
self.distro = distro
self... |
nguyeho7/CZ_NER | src/keras_NER/keras_NER.py | #!/usr/bin/env python3
import src.common.NER_utils as t
from src.common.eval import global_eval, output_evaluation, random_sample
from keras.models import Sequential, load_model, model_from_json, Model
from keras.layers.core import Reshape, Permute
from keras.layers import Input, Embedding, Bidirectional, Merge, TimeDi... |
commaai/panda | tests/read_winusb_descriptors.py | #!/usr/bin/env python3
from panda import Panda
from hexdump import hexdump
DEBUG = False
if __name__ == "__main__":
p = Panda()
length = p._handle.controlRead(Panda.REQUEST_IN, 0x06, 3 << 8 | 238, 0, 1)
print('Microsoft OS String Descriptor')
dat = p._handle.controlRead(Panda.REQUEST_IN, 0x06, 3 << 8 | 238, ... |
uclmr/inferbeddings | scripts/nli/asr/UCL_ARRAY_NLI_ASR_v1.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import itertools
import os
import os.path
import sys
import argparse
import logging
def cartesian_product(dicts):
return (dict(zip(dicts, x)) for x in itertools.product(*dicts.values()))
def summary(configuration):
kvs = sorted([(k, v) for k, v in configurati... |
fmenabe/python-unix | setup.py | # -*- coding: utf-8 -*-
from distutils.core import setup
setup(
name='unix',
version='1.0',
author='François Ménabé',
author_email='francois.menabe@gmail.com',
download_url="https://github.com/fmenabe/python-unix",
packages=['unix', 'unix.linux', 'unix.linux.gnu'],
license="MIT Licence",
... |
jimmycallin/master-thesis | architectures/conll16st-hd-sdp/const.py | """
Consts implementation as seen shown in http://code.activestate.com/recipes/65207-constants-in-python/?in=user-97991
"""
class _const:
class ConstError(TypeError): pass
def __setattr__(self,name,value):
#if self.__dict__.has_key(name):
# we do not to raise exception as this constant c... |
laginha/django-mobileesp | example/example/settings.py | # Django settings for example project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': '', ... |
yeti/signals | tests/parser/test_schema.py | import unittest
from tests.utils import captured_stdout
from signals.parser.fields import Field, Relationship
from signals.parser.schema import DataObject, Schema, URL
from signals.logging import colorize_string
class SchemaTestCase(unittest.TestCase):
def test_create_schema(self):
# Test that generally t... |
ujjwal96/mitmproxy | test/mitmproxy/test_command.py | import typing
import inspect
from mitmproxy import command
from mitmproxy import flow
from mitmproxy import exceptions
from mitmproxy.test import tflow
from mitmproxy.test import taddons
import mitmproxy.types
import io
import pytest
class TAddon:
@command.command("cmd1")
def cmd1(self, foo: str) -> str:
... |
charlesreid1/wordswordswords | pelican/roughingit/make_roughingit.py | import os.path
from bs4 import BeautifulSoup
title = "Roughing It"
author = "Mark Twain"
name = "roughingit"
short = "mtri"
chapters = []
filenames = []
nfiles = len(os.listdir('_include'))
for jm1 in range(nfiles):
j = jm1+1
print "-"*20
print "chapter id: %d"%(j)
filename = "_include/%s%d.html... |
AndreasMadsen/grace | Code/ols_lar.py |
import grace
import grace.times
import grace.ols
import numpy as np
import matplotlib.pyplot as plt
import sklearn.linear_model as lm
initial = (26, 130)
# get x values (in days)
days = grace.ols.time_vector()
all_days = np.linspace(np.min(days), np.max(days), np.max(days) - np.min(days))
# Get OLS stuff for this p... |
cordis/pycloudia-chat | pyligaforex/services/contacts/interfaces.py | from abc import ABCMeta, abstractmethod
class IService(object):
__metaclass__ = ABCMeta
@abstractmethod
def get_contacts(self, user_id, limit=None, offset=None):
"""
:type user_id: C{str}
:type limit: C{int} or C{None}
:type offset: C{str} or C{None}
"""
@abst... |
ybonjour/nuus | common/Mock.py | __author__ = 'Yves Bonjour'
class Mock(object):
def __init__(self):
self.method_calls = {}
def num_method_calls(self, method):
return len(self.get_calls(method))
def get_calls(self, method):
return self.method_calls.get(method, [])
def get_arguments(self, method, call_nu... |
smnorris/pgdb | pgdata/__init__.py | from __future__ import absolute_import
import os
try:
from urllib.parse import urlparse
except ImportError:
from urlparse import urlparse
from pgdata.database import Database
from pgdata.table import Table
__version__ = "0.0.13dev0"
def connect(url=None, schema=None, sql_path=None, multiprocessing=False):
... |
jrief/django-angular | examples/server/tests/test_fileupload.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import os, json
from django.conf import settings
from django.urls import reverse
from django.core import signing
from django.core.files.uploadedfile import InMemoryUploadedFile, TemporaryUploadedFile
from django.test import override_settings, TestCase
fr... |
davidszotten/redeer | redeer/api/forms.py | from django import forms
from redeer.feeds.models import Group, Feed, Item
def as_choices(iterable):
return [(value, value) for value in iterable]
# sadly, 'as' is a keyword, so we need this
MarkFormBase = type('MarkFormBase', (forms.Form, ), {
'mark': forms.ChoiceField(
choices=as_choices(['item', ... |
pizzapanther/Super-Neutron-Drive | server/ndrive/utils/email.py | import base64
import urllib
import logging
import types
import requests
from django.conf import settings
from django.template.loader import render_to_string
EMAIL_STYLE = {
'headerBg': '#e6e6e6'
}
class MailError (Exception):
pass
def email_context (context):
context.setdefault('site_name', settings.SITE_N... |
arteria/django-hijack | hijack/views.py | # -*- encoding: utf-8 -*-
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseBadRequest
from django.shortcuts import get_object_or_404
from hijack.decorators import hijack_require_http_methods, hijack_decorator
from hijack.helpers import login_user, redirect_to_next
from hija... |
a-holm/MachinelearningAlgorithms | Deep Learning/DeepLearningWithTensorFlow/ownDataDeepLearningWithNeuralNetworks.py | # -*- coding: utf-8 -*-
"""Deep Learning with Neural Networks and TensorFlow.
Deep learning is part of a broader family of machine learning methods based on
learning data representations, as opposed to task-specific algorithms. Learning
can be supervised, partially supervised or unsupervised.
A deep neural network (D... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.