repo_name stringlengths 5 104 | path stringlengths 4 248 | content stringlengths 102 99.9k |
|---|---|---|
SwordYork/sequencing | sequencing_np/attention/attention.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Author: Sword York
# GitHub: https://github.com/SwordYork/sequencing
# No rights reserved.
#
from .. import np, TIME_MAJOR, DTYPE
from ..nn.base import Layer
class Attention(Layer):
FLOAT_MIN = -100000.0
def __init__(self, keys, values, values_length, b... |
ojii/django-multilingual-ng | docs/conf.py | # -*- coding: utf-8 -*-
#
# django-multilingual-ng documentation build configuration file, created by
# sphinx-quickstart on Mon Mar 8 22:33:53 2010.
#
# 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
# autogenerate... |
cliffano/swaggy-jenkins | clients/python-aiohttp/generated/openapi_server/models/pipeline_run_impllinks.py | # coding: utf-8
from datetime import date, datetime
from typing import List, Dict, Type
from openapi_server.models.base_model_ import Model
from openapi_server.models.link import Link
from openapi_server import util
class PipelineRunImpllinks(Model):
"""NOTE: This class is auto generated by OpenAPI Generator (... |
hugolundin/dailyprogrammer | python/easy/228.py | def is_ordered(word: str) -> bool:
for w in range(len(word)):
if w == 0:
continue
w1 = ord(word[w - 1])
w2 = ord(word[w])
if w1 > w2:
return False
return True
def is_reversed(word: str) -> bool:
for w in range(len(word)):
if w == 0:
... |
laputian/dml | hu/match_shapes__1.py | from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import cv2
from cv2 import matchShapes
from skimage.measure import compare_ssim
import sys
sys.path.insert(0, '../mlp_test')
from data_utils import load_mnist
train_data, verificatio_data, test_data = load_... |
fire-uta/ir-simulation | qsdl/parser/trecRelevanceReader.py | # -*- coding: latin-1 -*-
'''
Created on 19.10.2012
@author: Teemu Pääkkönen
'''
import re
class S: pass # Storage class
S.readers = {}
S.regex = re.compile(r'^(\d+)\s+\d+\s+(\S+)\s+(\S+)')
def get_relevance_reader( relevanceFile ):
if S.readers.has_key( relevanceFile ):
return S.readers[ relevanceFile... |
e0ne/auth-signals-connector | auth_signals_connector/connector.py | import logging
from django.conf import settings
from django.contrib.auth import signals
LOG = logging.getLogger(__name__)
def login_user(sender, request, user, **kwargs):
LOG.info('User "{0}" logged in'.format(user))
def logout_user(sender, request, user, **kwargs):
LOG.info('User "{0}" logged out'.forma... |
tadfisher/rama | rama/event.py | from rama.dispatch import Dispatcher
import re
import traceback
import sys
import xcb
from xcb import xproto
CAPITAL_LETTER_RE = re.compile(r'\B([A-Z])')
class EventDispatcher(Dispatcher):
def __init__(self, wm):
super(EventDispatcher, self).__init__(wm=wm)
self.conn = wm.conn
def dispatch_... |
dmccloskey/molmass | molmass/molmass.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# molmass.py
# Copyright (c) 1990-2015, Christoph Gohlke
# All 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 re... |
Orange-Cyberdefense/fenrir-ocd | modARP.py | # coding=utf-8
######################################################################
##|# -------- modARP : ARP management module for MANGLE -------- #|###
##|# - It is responsible for handling ARP requests and replies - #|###
##|# - in order to avoid triggering switch's security measures - #|###
##|# - while still pr... |
tKhan719/Theta | Theta/main.py | from arithmetics import Addition
def main():
subject_dict = {'1': BasicArithmetics.basic_arith(), '2': Algebra.algebra(),
'3': BasicGeometry.basic_geo(), '4': Geometry.geometry(),
'5': Trigonometry.trigonometry(), '6': Calculus.calculus()}
print """1) Basic Arithmetics\... |
IndeedTokyo-BrickWall/brick-wall-build | brick_wall_build/tests/build_scripts/build_with_params.py | #!/usr/bin/python
from brick_wall_build import task
tasks_run = []
@task()
def clean(directory='/tmp'):
print "qq"
tasks_run.append('clean[%s]' % directory)
@task(clean)
def html():
tasks_run.append('html')
@task()
def tests(*test_names):
tasks_run.append('tests[%s]' % ','.join(test_names... |
tysonholub/twilio-python | tests/integration/api/v2010/account/available_phone_number/test_toll_free.py | # coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from tests import IntegrationTestCase
from tests.holodeck import Request
from twilio.base.exceptions import TwilioException
from twilio.http.response import Response
class TollFreeTestCase(Integrat... |
chitnguyen169/connect4CaseStudy | connect4/tests.py | from django.test import TestCase
from connect4.models import Game
from django.contrib.auth.models import User
# Create your tests here.
class GameTestCase(TestCase):
def setUp(self):
self.player1 = User(username="c1",
first_name="chi",
last_name="ngu... |
jnewland/ha-config | custom_components/senseme/switch.py | """Support for Big Ass Fans SenseME switch."""
from typing import Any
from aiosenseme import SensemeFan
from homeassistant.components.switch import DEVICE_CLASS_SWITCH, SwitchEntity
from homeassistant.const import CONF_DEVICE
from . import SensemeEntity
from .const import DOMAIN
FAN_SWITCHS = [
# Turning on slee... |
PhilippMundhenk/IVNS | ECUSimulation/components/security/ecu/software/impl_app_layer_tesla.py | import simpy
from tools.ecu_logging import ECULogger as L
from components.security.ecu.software.impl_app_layer_regular import RegularApplicationLayer
import logging
import random
class TeslaApplicationLayer(RegularApplicationLayer):
''' This class implements the application layer that
is used for the Tesla... |
JoelBender/bacpypes | sandbox/xtest_issue_45.py | #!/usr/bin/python
"""
test_issue_45
This sample application builds a VLAN with two application layer nodes and
uses a console prompt to send packets.
"""
from bacpypes.debugging import bacpypes_debugging, ModuleLogger
from bacpypes.consolelogging import ArgumentParser
from bacpypes.consolecmd import ConsoleCmd
from... |
andela-sjames/Django-ReactJS-Library-App | reactlibapp/libraryapi/utils.py | # resource: https://developers.google.com/identity/sign-in/web/backend-auth
import os
from oauth2client import client, crypt
from rest_framework.response import Response
from rest_framework.exceptions import AuthenticationFailed, PermissionDenied
def resolve_google_oauth(request):
# token should be passed as an ... |
pydicom/sendit | sendit/apps/api/urls.py | '''
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, merge, publish, distribute,... |
alfredodeza/tambo | tambo/tests/test_parser.py | from py.test import raises
from tambo import Parse
import sys
if sys.version < '3':
from cStringIO import StringIO
else:
from io import StringIO
class Test_parsing_arguments(object):
def test_removes_the_first_item_in_the_list_always(self):
parser = Parse([])
parser.parse_args()
a... |
mivdnber/roetsjbaan | roetsjbaan/main.py | import argparse, sys, time, os
from tabulate import tabulate
import imp
import roetsjbaan
import roetsjbaan.messages as messages
sys.path.append(os.getcwd())
f, path, desc = imp.find_module('roetsjfile', [os.getcwd()])
roetsjfile = imp.load_module('roetsjfile', f, path, desc)
migrator = roetsjbaan.Migrator(roetsjfil... |
radish-bdd/radish | tests/unit/test_config.py | """
radish
~~~~~~
The root from red to green. BDD tooling for Python.
:copyright: (c) 2019 by Timo Furrer <tuxtimo@gmail.com>
:license: MIT, see LICENSE for more details.
"""
import pytest
from radish.config import Config
from radish.errors import RadishError
def test_config_adds_items_as_attributes():
"""The... |
fohristiwhirl/disorderBook | bots/extreme_bot.py | import json, random, time
import stockfighter_minimal as sf
account = "EXTREMEBOT"
venue, symbol = "TESTEX", "FOOBAR"
sf.set_web_url("http://127.0.0.1:8000/ob/api/")
sf.change_api_key("noisekey")
def main():
global account
global venue
global symbol
orderType = "limit"
all_orders = []
while... |
collectiveacuity/pocketLab | pocketlab/commands/start.py | __author__ = 'rcj1492'
__created__ = '2016.03'
__license__ = 'MIT'
'''
starts services in docker containers
'''
_start_details = {
'title': 'Start',
'description': 'Initiates a container with the Docker image for one or more services. Unless overridden by flags, lab automatically adds the environmen... |
johntellsall/shotglass | dec/cmd_index.py | # cmd_index.py
import json
import logging
import subprocess
import sqlite3
import sys
from pathlib import Path
import git
import shotlib
# Universal Ctags
CTAGS_ARGS = "ctags --output-format=json --fields=*-P -o -".split()
logging.basicConfig(format="%(asctime)-15s %(message)s", level=logging.INFO)
def run_ctags... |
cleverhans-lab/cleverhans | cleverhans_v3.1.0/cleverhans/loss.py | """Loss functions for training models."""
import copy
import json
import os
import warnings
import numpy as np
import tensorflow as tf
from cleverhans.attacks import Attack
from cleverhans.compat import softmax_cross_entropy_with_logits
from cleverhans.model import Model
from cleverhans.utils import safe_zip
try:
... |
a710128/Lesson9 | API/capture/model.py | import tensorflow as tf
from keras.models import *
from keras.layers import *
from keras import backend as K
import numpy as np
import random
import datetime
import os
import gc
import string
characters = string.digits + string.ascii_lowercase+string.ascii_uppercase + ' '
width, height, n_len, n_class = 200, 60, 6, len... |
joaobarbosa/onesignal-python | tests/conftest.py | import pytest
from onesignalclient.app_client import OneSignalAppClient
from onesignalclient.user_client import OneSignalUserClient
from onesignalclient.notification import Notification
@pytest.fixture(scope="session")
def app_id():
return 'e6d73965-8ee6-410c-5e33-4c0cef33155t7'
@pytest.fixture(scope="session"... |
aehlke/manabi | manabi/apps/flashcards/migrations/0042_auto_20170131_0014.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11a1 on 2017-01-31 00:14
import autoslug.fields
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('flashcards', '0041_jlpt-n5-deck'),
]
operations = [
migrat... |
ksmit799/Toontown-Source | toontown/shtiker/OptionsPage.py | from panda3d.core import *
import ShtikerPage
from toontown.toontowngui import TTDialog
from direct.gui.DirectGui import *
from toontown.toonbase import TTLocalizer
import DisplaySettingsDialog
from direct.task import Task
from otp.speedchat import SpeedChat
from otp.speedchat import SCColorScheme
from otp.speedchat im... |
ashleysommer/sanic-cors | sanic_cors/decorator.py | # -*- coding: utf-8 -*-
"""
decorator
~~~~
This unit exposes a single decorator which should be used to wrap a
Sanic route with. It accepts all parameters and options as
the CORS extension.
:copyright: (c) 2022 by Ashley Sommer (based on flask-cors by Cory Dolphin).
:license: MIT, see LICEN... |
CalebBell/ht | setup.py | # -*- coding: utf-8 -*-
'''Chemical Engineering Design Library (ChEDL). Utilities for process modeling.
Copyright (C) 2016, Caleb Bell <Caleb.Andrew.Bell@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... |
Bitcoin-ABC/bitcoin-abc | contrib/buildbot/test/test_endpoint_buildDiff.py | #!/usr/bin/env python3
#
# Copyright (c) 2020 The Bitcoin ABC developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
import json
import mock
import requests
import unittest
from unittest.mock import call
from build import Bu... |
heyf/cloaked-octo-adventure | leetcode/203_remove-linked-list-elements.py | # 203. Remove Linked List Elements - LeetCode
# https://leetcode.com/problems/remove-linked-list-elements/description/
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class LinkedList(object):
def __init__(self, lst):
se... |
Stargrazer82301/CAAPR | CAAPR/CAAPR_AstroMagic/PTS/pts/core/config/update.py | #!/usr/bin/env python
# -*- coding: utf8 -*-
# *****************************************************************
# ** PTS -- Python Toolkit for working with SKIRT **
# ** © Astronomical Observatory, Ghent University **
# *****************************************************************
# ... |
gautelinga/BERNAISE | problems/electrowetting.py | import dolfin as df
import os
import numpy as np
from . import *
from common.io import mpi_is_root
from common.bcs import Fixed, NoSlip, FreeSlip, Slip, ContactAngle
from common.functions import max_value
__author__ = "Gaute Linga and Asger Bolet"
'''
Control paremetors in BERNAISE units
Potential drop over the elec... |
Ledoux/ShareYourSystem | Pythonlogy/draft/Noders/Catcher/01_ExampleDoc.py |
#ImportModules
import ShareYourSystem as SYS
#Definition of an instance
MyProducer=SYS.ProducerClass().produce(
"Catchers",
['First','Second','Third','Four'],
SYS.CatcherClass,
)
#Catch with a relative path
MyProducer['<Catchers>FirstCatcher'].grasp(
'/NodePointDeriveNoder/<Catchers>SecondCatcher'
).catch(
... |
VoltBit/ellida | install/res/meta-ellida/recipes-ellida/ellida-daemon/ellida-daemon-0.1/ellidadaemon/providers/provider.py |
from abc import ABCMeta, abstractmethod
import sys
sys.path.append('/usr/bin/python3.5/site-packages/')
sys.path.append('/usr/bin/python2.7/site-packages/')
class Provider(object):
__metaclass__ = ABCMeta
DEFAULT_LOG_NAMEFILE = "/tmp/ellida.log"
def __init__(self):
pass
@abstractmethod
... |
jefferyrayrussell/data-structures | src/test_double.py | # -*- coding: utf-8 -*-
"""Tests for double.py."""
from __future__ import unicode_literals
import pytest
from double import DNode, DList
TYPE_TABLE = [
'1',
1,
'-' * 10000,
'āĕijœ',
'',
b'1234',
'12345\t',
[1, 2, 3],
(1, 2, 3)
]
TABLE_LENGTHS = [
(['a'], "(a)"),
(['a', ' b... |
rxcomm/mixminion | lib/mixminion/Common.py | # Copyright 2002-2011 Nick Mathewson. See LICENSE for licensing information.
"""mixminion.Common
Common functionality and utility code for Mixminion"""
__all__ = ['IntervalSet', 'Lockfile', 'LockfileLocked', 'LOG', 'LogStream',
'MixError',
'MixFatalError', 'MixProtocolError', 'UIError', 'Us... |
rwl/PyCIM | CIM15/IEC61970/Outage/ClearanceTag.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... |
projectshift/shift-media | setup.py | #!/usr/bin/env python
import os
from shiftmedia.version import version
from setuptools import setup, find_packages
# ----------------------------------------------------------------------------
# Building
#
# Create source distribution:
# ./setup.py sdist
#
#
# Create binary distribution (non-univeral, python 3 only):... |
taspinar/twitterscraper | twitterscraper/main.py | """
This is a command line application that allows you to scrape twitter!
"""
import argparse
import collections
import csv
import datetime as dt
import json
import logging
from os.path import isfile
from pprint import pprint
from twitterscraper.query import (query_tweets, query_tweets_from_user,
... |
Mecanon/morphing_wing | dynamic_model/results/Hartl_SMA/config_B/plot_generations.py | # -*- coding: utf-8 -*-
"""
Created on Tue Apr 05 11:34:28 2016
@author: Pedro Leal
"""
import math
from xfoil_module import output_reader
from optimization_tools import plot_generations
filename = "opt_data.txt"
n_generation = 50
outputs_plotted = ['theta']
#output_constrained = ['theta']
#g1 = lambda x: True if x... |
thecrackofdawn/Peach2.3 | Peach/Generators/static.py |
'''
Default static generators. Includes generic string, binary, and numeric
static generators.
@author: Michael Eddington
@version: $Id: static.py 2020 2010-04-14 23:13:14Z meddingt $
'''
#
# Copyright (c) Michael Eddington
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this... |
paultag/syn | tests/test_versions.py | # Copyright (c) Syn AUTHORS, 2012, under the terms and conditions of the
# AUTHORS file.
from syn.versions import cmp_lt, cmp_gt, cmp_eq
def test_less_then():
v1 = "1"
v2 = "2"
assert cmp_lt(v1, v2)
v1 = "1.0"
v2 = "1.1"
assert cmp_lt(v1, v2)
v1 = "1.0.0"
v2 = "1.0.1"
assert cmp_l... |
full-stakk/flask-rest | resources/users.py | """This module handles calls to the database based on URIs it recieves."""
from flask.ext.restful import (Resource, Api, fields, marshal, marshal_with,
reqparse, abort)
from flask import jsonify, Blueprint, make_response, g
from auth import auth
import models
import json
# Response def... |
morganmeliment/fizzbuzz | fizzbuzz.py | """
fizzbuzz.py
Author: Morgan Meliment
Credit: none
Assignment:
Write a program that prints the numbers from 1 to 100. But for
multiples of three print “Fizz” instead of the number and for
the multiples of five print “Buzz”. For numbers which are multiples
of both three and five print “FizzBuzz”.
We will use a v... |
cerivera/crossfire | bin/firefox/addon-sdk-1.15/python-lib/cuddlefish/_version.py |
# This file helps to compute a version number in source trees obtained from
# git-archive tarball (such as those provided by githubs download-from-tag
# feature). Distribution tarballs (build by setup.py sdist) and build
# directories (produced by setup.py build) will contain a much shorter file
# that just contains t... |
lovepopcards/tap-mailchimp | src/tap_mailchimp/jsonext.py | import json
from json import load, loads
class JsonObject:
def __init__(self, d, required_keys=None, defaults=None):
if required_keys:
for k in required_keys:
setattr(self, k, d[k])
if defaults:
for k, v in defaults.items():
setattr(self, k, d... |
Pushwoosh/pushwoosh-python-lib | pypushwoosh/utils.py | from datetime import datetime, date
from six import string_types
from .constants import PLATFORMS, PLATFORM_NAMES, LINK_MINIMIZERS,\
TAG_FILTER_OPERATOR_LTE, TAG_FILTER_OPERATOR_GTE, TAG_FILTER_OPERATOR_EQ, TAG_FILTER_OPERATOR_IN, \
TAG_FILTER_OPERATOR_BETWEEN, TAG_FILTER_OPERATOR_NOTIN, TAG_FILTER_OPERATOR_N... |
ornlneutronimaging/iBeatles | src/iBeatles/utilities/array_utilities.py | import numpy as np
from scipy.ndimage import convolve
def find_nearest_index(array, value):
idx = (np.abs(np.array(array) - value)).argmin()
return idx
def get_min_max_xy(pos_array):
min_x = 10000
max_x = -1
min_y = 10000
max_y = -1
for xy in pos_array:
[_x, _y] = xy
if ... |
ti-mo/comfo | python/comfo/types.py | """
Concrete types for converting from protobuf objects.
Since the Python protobuf compiler outputs code that generates
classes on the fly from a symbol database, we convert them as
concrete types here to ensure the expected fields are present.
"""
from pprint import pformat
class ComfoMessage:
"""Mixin for prot... |
kittolau/selepy | web_helper/name_generator/abstract_name_generator.py | from random import randint
import math
class AbstractNameGenerator(object):
def __init__(self):
return
def nameGen(self,firstNames, lastNames):
names2 = firstNames
names1 = lastNames
firstNameRnd = int( math.floor( randint(0,len(names2) - 1) ) )
lastNameRnd = int( mat... |
mlubin/pylinprog | pylinprog.py | import numpy as np
from scipy.sparse import csr_matrix, csc_matrix, vstack
import julia
j = julia.Julia()
j.call("using MathProgBase")
from julia import MathProgBase
def solver(packagename,solvername):
j.call("using %s" % packagename)
return j.eval(solvername)
clp = solver("Clp","ClpSolver()")
linprog_wrap... |
yoshinarikou/MilleFeuilleRaspberryPi | milpython/GpioInputTest.py | ########################################################################
# MCU Gear(R) system Sample Code
# Auther:y.kou.
# web site: http://www.milletool.com/
# Date : 8/OCT/2016
#
########################################################################
#Revision Information
#
#########################################... |
pete0emerson/slackhook | slackhook.py | #!/usr/bin/env python
import ConfigParser
import requests
import json
import os
import sys
class Slackhook:
def _set_element(self, element, value):
# This automagically calls the right self.set_{ELEMENT}
unpack_options = { 'username':self.set_username, 'company':self.set_company, 'token':self.set_token, 'c... |
heezes/Hand-gesture-to-speech | suggestions.py | import os
class Hinter:
'''
Hinter is used to load a dictionary and obtain some suggestions
regarding the next possible letters or compatible words.
'''
def __init__(self, words):
self.words = words
@staticmethod
def load_english_dict():
'''
Loads the english dictionary and returns a Hinter object with... |
facinginternet/fictf-api | api/admin.py | from django.contrib import admin
from django.contrib.auth.models import Permission
from api.models import Problem, Player, CorrectSubmit
from django.contrib.contenttypes.models import ContentType
def recalculate_points(problem):
"""引数の problem を解いたことがある全ての player の獲得点数を再計算する"""
for prob_submit in problem.subm... |
manthansharma/fun-code | python/whatsapp-bot.py | import time
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
''' WhatsApp Web Bot to send message
Requirements:
beautifulsoup4==4.4.1
requests==2.10.0
selenium==2.53.6
Note: Need ChromeDriver - WebDriver for Chrome Link : ... |
DreamForgeContrive/tinyblox | tinyblox/ovsx.py | __author__ = "Kiran Vemuri"
__email__ = "kkvemuri@uh.edu"
__status__ = "Development"
__maintainer__ = "Kiran Vemuri"
from remotex import Connection
class Ovs:
"""
Class to facilitate interactions with ovs running on a remote server
"""
def __init__(self, host, username, password):
self.host =... |
ActiveState/code | recipes/Python/201294_Dynamic_Classes/recipe-201294.py | #!/usr/bin/env python
#-----------------------------------------------------------------------------
# Copyright 2003 by Bud P. Bruegger, Sistema, Italy
# mailto:bud@sistema.it
# http://www.sistema.it
#-----------------------------------------------------------------------------
# dynClass -- Dynamic Classes
# ... |
WGBH/FixIt | mla_game/apps/transcript/migrations/0024_auto_20180105_1900.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2018-01-05 19:00
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('transcript', '0023_auto_20171113_1841'),
]
operations = [
migrations.RemoveField(
... |
sragain/pcmc-nips | lib/mnl_utils.py | import numpy as np
from scipy.optimize import minimize
import random
from pcmc_utils import solve_ctmc
def ILSR(C,n):
"""performs the ILSR algorithm to learn optimal MNL weights for choice data
Arguments:
C- dictionary containing choice data
n- number of elements in the union of the choice sets
epsilon- hyperpa... |
ashwyn/eden-message_parser | static/scripts/tools/build.sahana.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# run as:
# python web2py.py -S eden -M -R applications/eden/static/scripts/tools/build.sahana.py
# or
# python web2py.py -S eden -M -R applications/eden/static/scripts/tools/build.sahana.py -A gis
#
#
# Built with code/inspiration from MapFish, OpenLayers & Michael C... |
icometrix/dicom2nifti | docs/rst/conf.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# dicom2nifti documentation build configuration file, created by
# sphinx-quickstart on Thu Jul 28 09:37:31 2016.
#
# 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
... |
cydenix/OpenGLCffi | OpenGLCffi/GL/EXT/EXT/coordinate_frame.py | from OpenGLCffi.GL import params
@params(api='gl', prms=['tx', 'ty', 'tz'])
def glTangent3bEXT(tx, ty, tz):
pass
@params(api='gl', prms=['v'])
def glTangent3bvEXT(v):
pass
@params(api='gl', prms=['tx', 'ty', 'tz'])
def glTangent3dEXT(tx, ty, tz):
pass
@params(api='gl', prms=['v'])
def glTangent3dvEXT(v):
pass... |
yosida95/redisengine | setup.py | # -*- coding: utf-8 -*-
import os
from setuptools import (
setup,
find_packages,
)
here = os.path.dirname(__file__)
requires = [
'redis',
]
tests_require = [
'nose',
'coverage',
'mock',
]
def _read(name):
try:
return open(os.path.join(here, name)).read()
except:
retu... |
iShoto/testpy | codes/20200125_visualize_object_detection_annotation_data/src/utils.py | import os
import argparse
import cv2
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
def main():
args = parse_args()
df = pd.read_csv(args.anno_path)
label_names = sorted(set(df['label_name'].values.tolist()))
colormap = get_colormap(label_names, args.colormap_name)
#print(colormap)
img_p... |
stefanw/froide | froide/foirequest/migrations/0033_requestdraft_flags.py | # Generated by Django 2.1.4 on 2019-01-14 14:40
import django.contrib.postgres.fields.jsonb
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('foirequest', '0032_auto_20181115_1339'),
]
operations = [
migrations.AddField(
model_name='r... |
erdc/proteus | proteus/tests/cylinder2D/ibm_rans2p_3D/cylinder.py | from math import *
import proteus.MeshTools
from proteus import Domain
from proteus.default_n import *
from proteus.Profiling import logEvent
from proteus import Context
import os
#===============================================================================
# Context
#==============================================... |
SmithSamuelM/emptor | setup.py | """ setup.py
Basic setup file to enable pip install
http://python-distribute.org/distribute_setup.py
python setup.py register -r pypi sdist upload -r pypi
"""
#from distribute_setup import use_setuptools
#use_setuptools()
from setuptools import setup, find_packages
setup(
name='emptori... |
hep7agon/city-feedback-hub | frontend/templatetags/custom_tags.py | from datetime import timedelta
from django import template
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from django.core.urlresolvers import reverse
from django.utils import timezone
from api.analysis import *
from api.models import Service
register = template.Library()
# ... |
luanrafael/pygame-site | FlaskApp/src/rest_api/__init__.py | """
Module containing all rest apis
Each rest api must be register in the __main__
file with the method register_blueprint
the rest api must follow this base structure
from flask import Blueprint, jsonify
api_name = Blueprint("api_name", __name__)
@api_name.route("/url_prefix/endpoint", methods=["GET"])
... |
scanse/sweep-3d-scanner | scanner/scanner.py | """Defines a 3D scanner"""
import argparse
import time
import datetime
import math
import threading
import sweep_helpers
import scan_settings
import scan_exporter
import scan_utils
import scanner_base
from scanner_output import output_json_message
class Scanner(object):
"""The 3d scanner.
Attributes:
... |
Pulgama/supriya | supriya/midi/NoteOffMessage.py | from supriya.midi.MidiMessage import MidiMessage
class NoteOffMessage(MidiMessage):
### CLASS VARIABLES ###
__slots__ = ("_note_number", "_velocity")
### INITIALIZER ###
def __init__(
self, channel_number=None, note_number=None, timestamp=None, velocity=None
):
MidiMessage.__in... |
DavidQiuChao/CS231nHomeWorks | assignment1/cs231n/classifiers/k_nearest_neighbor.py | import numpy as np
from past.builtins import xrange
class KNearestNeighbor(object):
""" a kNN classifier with L2 distance """
def __init__(self):
pass
def train(self, X, y):
"""
Train the classifier. For k-nearest neighbors this is just
memorizing the training data.
... |
franzinc/agraph-python | src/franz/openrdf/tests/importtests.py | # -*- coding: utf-8 -*-
import gzip
import os
import tempfile
import pytest
from franz.openrdf.model import Literal, URI
from franz.openrdf.repository.repositoryconnection import DocumentKey
from franz.openrdf.rio.docformat import DocFormat
from franz.openrdf.tests.conftest import min_version
from franz.openrdf.tests... |
tristan0x/hpcbench | tests/benchmark/test_hpl.py | import unittest
from hpcbench.benchmark.hpl import HPL
from .benchmark import AbstractBenchmarkTest
class TestHplData(unittest.TestCase):
def test_default(self):
self.maxDiff = None
hpl = HPL()
expected = dict(realN=3456, nb=192, pQ=[6, 6])
self.assertEqual(hpl.data, hpl._data_fro... |
FNNDSC/pman | tests/test_resources.py |
import logging
from pathlib import Path
import shutil
import os
import time
from unittest import TestCase
from unittest import mock, skip
from flask import url_for
from pman.app import create_app
class ResourceTests(TestCase):
"""
Base class for all the resource tests.
"""
def setUp(self):
... |
hepochen/hoedown_misaka | build_ffi.py | # -*- coding: utf-8 -*-
import cffi
# Block-level extensions
EXT_TABLES = (1 << 0)
EXT_FENCED_CODE = (1 << 1)
EXT_FOOTNOTES = (1 << 2)
# Span-level extensions
EXT_AUTOLINK = (1 << 3)
EXT_STRIKETHROUGH = (1 << 4)
EXT_UNDERLINE = (1 << 5)
EXT_HIGHLIGHT = (1 << 6)
EXT_QUOTE = (1 << 7)
EXT_SUPERSCRIPT = (1 << 8)
EXT_MA... |
jwheatp/twitter-riots | analysis/plot_wordcloud.py | from os import path
import math
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from wordcloud import WordCloud
from collections import Counter
import sys
import re
import glob
import numpy
path = str(sys.argv[1])
out = str(sys.argv[2])
i = 0
words = {}
sets = {}
for filename in glob.glob(path... |
ministryofjustice/cla_backend | cla_backend/apps/call_centre/tests/test_permissions.py | from django.conf.urls import patterns
from django.http import HttpResponse
from django.test import TestCase
from rest_framework import status
from rest_framework.authentication import OAuth2Authentication
from rest_framework.views import APIView
from legalaid.tests.views.test_base import CLAOperatorAuthBaseApiTestMixi... |
eSedano/hoplite | 1.0/lib/random.py | #!/usr/bin/env python
# --------------------------------------------------------------------------------------------------
# __ ______ ____ __ ________________
# / / / / __ \/ __ \/ / / _/_ __/ ____/
# / /_/ / / / / /_/ / / / / / / / __/
# / __ / /_/ / ____/ /____/ / / / / /___
# /_/ /_/\____/... |
bourdeau/Blog | app/admin/models.py | from app.application import db
from flask_security import UserMixin, RoleMixin
roles_users = db.Table('roles_users', db.Column('user_id', db.Integer(), db.ForeignKey('user.id')), db.Column('role_id', db.Integer(), db.ForeignKey('role.id')))
class Role(db.Model, RoleMixin):
id = db.Column(db.Integer(), primary_k... |
benelot/bullet-gym | pybulletgym/train_KerasDDPG_PybulletInvertedDoublePendulum.py | #!/usr/bin/env python
import Trainer
import datetime
import argparse
import pybulletgym.envs
trainer = Trainer.Trainer()
argparser = argparse.ArgumentParser()
Trainer.add_opts(argparser)
# precoded options
opts = argparser.parse_args()
opts.agent="KerasDDPGAgent-v0"
opts.env="PybulletInvertedDoublePendulum-v0"
opts... |
KaiYan0729/nyu_python | intro-programming/final_project/final_project.py | #!/usr/bin/env python3
from datetime import date
import math
import numpy as np
import sys
from math import *
#Binomial Tree model
def tree(stock_price, strike_price, rf, volatility, div_yield, steps, c_or_p):
#Inputs
Dt = 1 / steps #set time to expiration equal to 1
r_Dt = rf * Dt
exp_r_Dt = math.exp(r... |
jgowans/correlation_plotter | snap_reader.py | import struct
class SnapReader:
def __init__(self, fpga, snap_name, data_length):
self.fpga = fpga
self.snap_name = snap_name
self.data_length = data_length
devs = fpga.listdev()
if '{}_dram'.format(snap_name) in devs:
self.is_dram_snap = True
el... |
jmhobbs/pircie | pircie/irc.py | # -*- coding: utf-8 -*-
# Copyright (c) 2010 John Hobbs
#
# http://github.com/jmhobbs/pircie
#
# 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 limitati... |
pavelsof/stl | setup.py | import os.path
from setuptools import setup, find_packages
from stl import __version__
BASE_DIR = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(BASE_DIR, 'README.rst')) as f:
README = f.read()
setup(
name = 'stltimelogger',
version = __version__,
description = 'cli time logger',
long... |
GaretJax/irco | irco/graphs/institutions.py | import itertools
import collections
import networkx as nx
from irco import logging
log = logging.get_logger()
def get_institutions(publication):
institutions = set()
for affiliation in publication.affiliations:
institutions.add(affiliation.institution.name)
return institutions
def create(... |
cupy/cupy | cupy/fft/config.py | from cupy import _util
# expose cache handles to this module
from cupy.fft._cache import get_plan_cache # NOQA
from cupy.fft._cache import clear_plan_cache # NOQA
from cupy.fft._cache import get_plan_cache_size # NOQA
from cupy.fft._cache import set_plan_cache_size # NOQA
from cupy.fft._cache import get_plan_cache... |
loleg/dribdat | dribdat/public/api.py | # -*- coding: utf-8 -*-
import boto3
from flask import (
Blueprint, current_app,
Response, request, redirect,
stream_with_context, send_file,
jsonify, flash, url_for
)
from flask_login import login_required, current_user
from sqlalchemy import or_
from ..extensions import db
from ..utils import times... |
Cito/DBUtils | tests/test_steady_db.py | """Test the SteadyDB module.
Note:
We do not test any real DB-API 2 module, but we just
mock the basic DB-API 2 connection functionality.
Copyright and credit info:
* This test was contributed by Christoph Zwerschke
"""
import unittest
from . import mock_db as dbapi
from dbutils.steady_db import (
connect as ... |
velezj/well_posed_problems | definer_d/defining.py | ##
## Copyright Javier Velez <velezj@alum.mit.edu> April 2017
## All Rights Reserved
##
import logging
logger = logging.getLogger( __name__ )
##
#
# This file ocntinas the core Definition concept and
# related classes
import ast
import symtable
##====================================================================... |
Talvalin/server-client-python | tableauserverclient/models/pagination_item.py | import xml.etree.ElementTree as ET
from .. import NAMESPACE
class PaginationItem(object):
def __init__(self):
self._page_number = None
self._page_size = None
self._total_available = None
@property
def page_number(self):
return self._page_number
@property
def page_... |
FarmBot/farmbot_os | priv/farmware/plant_detection/P2C.py | """Image Pixel Location to Machine Coordinate Conversion."""
import sys
import os
import json
import numpy as np
from plant_detection.Parameters import Parameters
from plant_detection.Image import Image
from plant_detection.DB import DB
from plant_detection import ENV
from plant_detection.Log import log
class Pixel2... |
dtysky/Gal2Renpy | Sublime_Plugin/Gal2RenpyCompletions.py | #coding:utf-8
#########################
#Copyright(c) 2014 dtysky
#########################
import sublime, sublime_plugin
import json,os,pickle,codecs,locale,re
import sys
sys.path.append(os.path.split(__file__)[0])
path=os.path.split(__file__)[0]+'/'+'User.json'
game_path=json.load(open(path,'r'))['game_gal2renpy_pa... |
JamoBox/django-notify | docs/source/conf.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# django-notify documentation build configuration file, created by
# sphinx-quickstart on Thu Feb 16 20:57:01 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in thi... |
cmvandrevala/finance_scripts | portfolio_creator/portfolio_creator.py | import json
from portfolio.portfolio import Portfolio
class PortfolioCreator:
def create(self, data_source):
portfolio = Portfolio()
data = data_source.get()
snapshots = json.loads(data)
for item in snapshots["snapshots"]:
portfolio.import_data({"timestamp": item["time... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.