repo_name stringlengths 5 100 | path stringlengths 4 231 | language stringclasses 1
value | license stringclasses 15
values | size int64 6 947k | score float64 0 0.34 | prefix stringlengths 0 8.16k | middle stringlengths 3 512 | suffix stringlengths 0 8.17k |
|---|---|---|---|---|---|---|---|---|
CSCI-462-01-2017/bedrock | tests/pages/internet_health.py | Python | mpl-2.0 | 732 | 0 | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from selenium.webdriver.common.by import By
from pages.base import BasePage
class InternetHealthPage(BasePage):
... | blogs')
_blog_feed_articles_locator = (By.CSS_SELECTOR, '#blogs article')
@property
def is_blog_feed_displayed(self):
return self.is_element_displayed(*self._blog_feed_locator)
@property
def number_of_blog_articles_present(self):
| return len(self.find_elements(*self._blog_feed_articles_locator))
|
simontakite/sysadmin | pythonscripts/learningPython/exiter2.py | Python | gpl-2.0 | 208 | 0.009615 | impo | rt sys
def bye():
sys.exit(40) # Crucial error: abort now!
try:
bye()
except Exception:
print('got it') # Oops--we ignored the exit
print('continuing...' | )
|
SpaceGroupUCL/qgisSpaceSyntaxToolkit | esstoolkit/external/pyqtgraph/opengl/shaders.py | Python | gpl-3.0 | 16,009 | 0.011618 | try:
from OpenGL import NullFunctionError
except ImportError:
from OpenGL.error import NullFunctionError
from OpenGL.GL import *
from OpenGL.GL import shaders
import re
## For centralizing and managing vertex/fragment shader programs.
def initShaders():
global Shaders
Shaders = [
ShaderProgram... | ## See:
##
## http://stackoverflow.com/questions/9609423/applying-part-of-a-texture-sprite-sheet-texture-map-to-a-point-sprite-in-ios
## http://stackoverflow.com/questions/3497068/textured-points-in-opengl-es-2-0
##
##
VertexShader("""
... | sition = ftransform();
}
"""),
#FragmentShader("""
##version 120
#uniform sampler2D texture;
#void main ( )
#{
#gl |
lebauce/artub | builder/Installer/hooks/hook-DateTime.py | Python | gpl-2.0 | 79 | 0 | hid | denimports = ['ISO', 'ARPA', 'ODMG', 'Locale', 'Feasts', 'Parser', 'NIST']
| |
tkralphs/GrUMPy | src/grumpy/examples/LP6.py | Python | epl-1.0 | 420 | 0.05 | numVars = 2
#points = [[2.5, 4.5], | [6.5, 0.5],
# [7, 5.7], [7.7, 5], [-2, -2]]
#rays = []
A = [[ -1, 3.75 ],
[ 1, -3.4 ],
[ -1.625, 1.125],
[ 3.75, -1 ],
[ 1, 1 ],
]
b = [ 14.375,
4.8 ,
1.0 | ,
23.875,
12.7 ,
]
c = [2, 1]
opt = (7.7, 5)
obj_val = 20.4
sense = ('<=', 'Max')
|
alex/sqlalchemy | test/base/test_dependency.py | Python | mit | 8,781 | 0.001025 | from sqlalchemy.util import topological
from sqlalchemy.testing import assert_raises, eq_
from sqlalchemy.testing.util import conforms_partial_ordering
from sqlalchemy import exc
from sqlalchemy.testing import fixtures
class DependencySortTest(fixtures.TestBase):
def assert_sort(self, tuples, allitems=None):
... | 15', 'node13'),
| ('node17', 'node11'), ('node1', 'node19'), ('node15', 'node8'),
('node6', 'node20'), ('node14', 'node11'), ('node6', 'node14'),
('node11', 'node2'), ('node10', 'node20'), ('node1', 'node11'),
('node20', 'node19'), ('node4', 'node20'), ('node15', 'node20'),
('node9', ... |
respawner/peering-manager | devices/tests/test_views.py | Python | apache-2.0 | 772 | 0 | from devices.models import Platform
from utils.testing import ViewTestCases
class PlatformTestCase(
ViewTestCases.CreateObjectViewTestCase,
ViewTestCases.EditObjectViewTestCase,
ViewTestCases.DeleteObjectViewTestCase,
ViewTestCases.ListObjectsViewTestCase,
):
model = Platform
@classmethod
... | s.bulk_create(
[
Platform(name="Some OS", slug="someos"),
Platform(name="Test OS", slug="testos"),
]
)
cls.form_data = {
"name": "Bugs OS",
"slug": "bugsos",
"napalm_driver": "bugsos" | ,
"napalm_args": {},
"password_algorithm": "",
"description": "",
}
|
sciunto/rss2email | rss2email/feeds.py | Python | gpl-2.0 | 14,342 | 0.000279 | # Copyright (C) 2004-2014 Aaron Swartz
# Brian Lalor
# Dean Jackson
# Erik Hetzner
# Etienne Millon <me@emillon.org>
# Joey Hess
# Lindsey Smith <lindsey.smith@gmail.com>
# ... | afile_encoding = 'utf-8'
def __init__(self, configfiles=None, datafile=None, config=None):
super(Feeds, self).__init__()
if configfiles is None:
configfiles = self._get_configfiles()
self.configfiles = configfiles
if datafile is None:
datafile = self._get_dat... | _config.CONFIG
self.config = config
self._datafile_lock = None
def __getitem__(self, key):
for feed in self:
if feed.name == key:
return feed
try:
index = int(key)
except ValueError as e:
raise IndexError(key) from e
... |
Ophiuchus1312/enigma2-master | lib/python/Plugins/Extensions/Infopanel/SwapManager.py | Python | gpl-2.0 | 12,563 | 0.026825 | # for localized messages
from . import _
from Screens.Screen import Screen
from Screens.MessageBox import MessageBox
from Screens.ChoiceBox import ChoiceBox
from Components.config import config, configfile, ConfigYesNo, ConfigSubsection
from Components.ActionMap import ActionMap
from Components.Label import Label
from... | .split()
self.swap_place = parts[0]
if self.swap_place == 'sfdisk:':
self.swap_place = ''
self.device = True
f = open('/proc/swaps', 'r')
for line in f.readlines():
parts = line.strip().split()
if line.find('partition') != -1:
self.swap_active = True
self.swapsize = pa... | titions():
d = path.normpath(p.mountpoint)
if path.exists(p.mountpoint) and p.mountpoint != "/" and not p.mountpoint.startswith('/media/net'):
devicelist.append((p.description, d))
if len(devicelist):
for device in devicelist:
for filename in glob(device[1] + '/swap*'):
self.swap_place = ... |
macknowak/simtools | simtools/simrun.py | Python | gpl-3.0 | 3,606 | 0.000832 | # -*- coding: utf-8 -*-
"""Simulation launch services.
Simulation launch services provide the following functionality:
- generating simulation id based on local date and time;
- generating simulation directory name;
- loading names of simulation directories from a text file;
- creating directory structure for simulat... | ns as options
from simtools.base import is_iterable, is_string
TMP_DIR_PREFIX = "_"
def generate_sim_id():
"""Generate simulation id based on local date and time."" | "
t = time.localtime()
sim_id = "{0:04}{1:02}{2:02}_{3:02}{4:02}{5:02}".format(
t.tm_year, t.tm_mon, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec)
return sim_id
def generate_sim_dirname(tmp=False, sim_id=None):
"""Generate simulation directory name."""
if not sim_id:
sim_id = generate_... |
evature/flightstats | flightstats/flightstats.py | Python | mit | 7,585 | 0.007779 | '''
Created on Jun 29, 2016
@author: evature
https://developer.flightstats.com/api-docs/scheduledFlights/v1
'''
from __future__ import absolute_import
import os
import requests
import datetime
from pprint import pprint
from pytz import timezone
from flightstats.flightaware_airports import AIRPORTS as FA_AIRPORTS
... | arrival_day=arrival_date.day)
content = send_request(search_url)
return content
def departures(from_airport, to_airport, departure_date):
"""
finds departure
@from_airport The airport code (IATA) of the departure airport (required)
@to_airport The airport co... | )
"""
search_url = "from/{from_airport}/to/{to_airport}/departing/{departure_year}/{departure_month}/{departure_day}".format(from_airport=from_airport,
to_airport=to_airport,
... |
radiosilence/pip | pip/__init__.py | Python | mit | 8,056 | 0.000993 | #!/usr/bin/env python
import os
import optparse
import sys
import re
import difflib
from pip.exceptions import InstallationError, CommandError, PipError
from pip.log import logger
from pip.util import get_installed_distributions, get_prog
from pip.vcs import git, mercurial, subversion, bazaar # noqa
from pip.basepar... |
svn_backend = vcs.get_backend('svn')
if svn_backend:
svn_location = svn_backend(
).get_location(dist, dependency_links)
if not svn_location:
| logger.warn(
'Warning: cannot find svn location for %s' % req)
comments.append('## FIXME: could not find svn URL in dependency_links for this package:')
else:
comments.append('# Installing as editable to satisfy requirement %s:' % req)
... |
ranisalt/moita-migrant | migrant.py | Python | mit | 1,377 | 0.000726 | #!/usr/bin/env python
import argparse
import binascii
import datetime
import gzip
import json
import magic
import os
import pymongo
import sys
def read_gzip(filename):
with gzip.open(filename) as file:
content = file.read()
return content
def read_plain(filename):
with open(filename) as | file:
content = file.read()
return content
readers = {
b'application/x-gzip': read_gzip,
b'text/plain': read_plain,
}
def read(filename):
type = magic.from_file(filename, mime=True)
| return readers[type](filename).decode()
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('-m', help='path to moita configuration file',
dest='moita', metavar='MOITA', required=True)
parser.add_argument('filename', nargs='+')
args = parser.parse_... |
mrgloom/kepler-mapper | examples/digits/digits.py | Python | mit | 1,593 | 0.021971 | import km
# Load digits data
from sklearn import datasets
data, labels = datasets.load_digits().data, datasets.load_digits().target
# Create images for a custom tooltip array
import StringIO
from scipy.misc import imsave, toimage
import base64
tooltip_s = []
for image_data in data:
output = StringIO.StringIO()
img ... | pper.visualize(compl | ex, "keplermapper_digits_ylabel_tooltips.html", "Digits", graph_gravity=0.25, custom_tooltips=labels) |
TeamEOS/external_chromium_org | chrome/common/extensions/docs/server2/cron_servlet.py | Python | bsd-3-clause | 12,019 | 0.007904 | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import logging
import posixpath
import traceback
from app_yaml_helper import AppYamlHelper
from appengine_wrappers import IsDeadlineExceededError, logservic... | he time these won't have changed since the last cron run, so it's a
# little wasteful, but hopefully rendering is really fast (if it isn't we
# have a problem).
_cro | nlog.info('starting')
# This is returned every time RenderServlet wants to create a new
# ServerInstance.
#
# TODO(kalman): IMPORTANT. This sometimes throws an exception, breaking
# everything. Need retry logic at the fetcher level.
server_instance = self._GetSafeServerInstance()
trunk_fs =... |
alok1974/compage | src/compage/logger.py | Python | mit | 5,536 | 0 | import os
import inspect
import logging
logging.basicConfig()
logging.getLogger().setLevel(logging.DEBUG)
TRACEBACK | _INSPECTOR = inspect.currentframe
DEBUG = logging.DEBUG
INFO = logging.INFO
ERROR = logging.ERROR
WARNING = logging.WARN
CRITICAL = logging.CRITICAL
def debugCaller(traceback=None):
""" Function who return all the traceback of a call."""
tracebackLog = inspect.getouterframes(traceback)
| moduleName = os.path.basename(
tracebackLog[1][1]).replace(".py", "").replace(
'<Script Block >', 'stdin')
methodName = tracebackLog[1][3]
return [moduleName, methodName]
class Logger(object):
"""
"""
level = INFO
criticalFunc = None
infoFunc = None
warningFunc = None
... |
fbentz/vedasboardgame | vedasboardgame/boardgame/admin.py | Python | mit | 95 | 0 | from django.co | ntrib import admin
from .models import BoardGame
admin | .site.register(BoardGame)
|
isard-vdi/isard | engine/engine/engine/services/balancers/balancer_interface.py | Python | agpl-3.0 | 262 | 0 | # Copyright 2018 the Isard-vd | i project authors:
# Alberto Larraz Dalmases
# Josep Maria Viñolas Auquer
# Daniel Criado Casas
# License: AGPLv3
class BalancerInterface(object):
def get_next(sel | f, **kwargs):
raise NotImplementedError
|
jscn/django | tests/auth_tests/test_hashers.py | Python | bsd-3-clause | 23,079 | 0.000955 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from unittest import skipUnless
from django.conf.global_settings import PASSWORD_HASHERS
from django.contrib.auth.hashers import (
UNUSABLE_PASSWORD_PREFIX, UNUSABLE_PASSWORD_SUFFIX_LENGTH,
BasePasswordHasher, PBKDF2PasswordHasher, PBKDF2SHA1Pass... | le(encoded))
self.assertTrue(check_password('lètmei', encoded))
self.assertFalse(check_password('lètmeiz', encoded))
self.assertEqual(identify_hasher(encoded).algorithm, "crypt")
# Blank passwords
blank_encoded = make_password('', 'ab', 'crypt')
se | lf.assertTrue(blank_encoded.startswith('crypt$'))
self.assertTrue(is_password_usable(blank_encoded))
self.assertTrue(check_password('', blank_encoded))
self.assertFalse(check_password(' ', blank_encoded))
@skipUnless(bcrypt, "bcrypt not installed")
def test_bcrypt_sha256(self):
... |
emmuchira/kps_erp | erpnext/selling/page/point_of_sale/point_of_sale.py | Python | gpl-3.0 | 2,765 | 0.027848 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe, json
from frappe.utils.nestedset import get_root_of
@frappe.whitelist()
def get_items(start, page_length, price_list, item_group, search... | if search_value:
# search serial no
serial_no_data = frappe.db.get_value('Serial No', search_value, ['name', 'item_code'])
if serial_no_data:
serial_no, item_code = serial_no_data
if not serial_no:
batch_no_data = frappe.db.get_value('Batch', | search_value, ['name', 'item'])
if batch_no_data:
batch_no, item_code = batch_no_data
if not serial_no and not batch_no:
barcode_data = frappe.db.get_value('Item', {'barcode': search_value}, ['name', 'barcode'])
if barcode_data:
item_code, barcode = barcode_data
item_code, condition = get_conditio... |
savoirfairelinux/ring-daemon | tools/jamictrl/sippwrap.py | Python | gpl-3.0 | 5,229 | 0.001912 | #!/usr/bin/env python
#
# Copyright (C) 2012 by the Free Software Foundation, Inc.
#
# Author: Alexandre Savard <alexandre.savard@savoirfairelinux.com>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foun... | in self.logfile[40]
def isAnySuccessfulCall(self):
""" Look for any successful call
Return true if there are successful call, false elsewhere """
# TODO: F | ind a better way to determine which line to consider
if "Successful call" not in self.logfile[39]:
print "Error: Could not find 'Successful call' statistics"
return False
return "1" in self.logfile[39]
def test_result_parsing():
dirlist = os.listdir("./")
logfile = [... |
sinpantuflas/aubio | waflib/extras/compat15.py | Python | gpl-3.0 | 7,478 | 0.050682 | #! /usr/bin/env python
# encoding: utf-8
# WARNING! Do not edit! http://waf.googlecode.com/git/docs/wafbook/single.html#_obtaining_the_waf_file
import sys
from waflib import ConfigSet,Logs,Options,Scripting,Task,Build,Configure,Node,Runner,TaskGen,Utils,Errors,Context
sys.modules['Environment']=ConfigSet
ConfigSet.Env... | ames
if added:continue
y.post()
seen.append(x)
for t in getattr(y,'compiled_tasks',[]):
self.link_task.inputs.extend(t.outputs)
@TaskGen.after(' | apply_link')
def process_obj_files(self):
if not hasattr(self,'obj_files'):
return
for x in self.obj_files:
node=self.path.find_resource(x)
self.link_task.inputs.append(node)
@TaskGen.taskgen_method
def add_obj_file(self,file):
if not hasattr(self,'obj_files'):self.obj_files=[]
if not'process_obj_files'in sel... |
patricklaw/pants | src/python/pants/backend/python/lint/docformatter/skip_field.py | Python | apache-2.0 | 840 | 0.002381 | # Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from pants.backend.pytho | n.target_types import (
PythonSourcesGeneratorTarget,
PythonSourceTarget,
PythonTestsGeneratorTarget,
PythonTestTarget,
)
from pants.engine.target import BoolField
class SkipDocformatterField(BoolField):
alias = "skip_docformatter"
default = False
help = "If true, don't run Docformatter on... | es():
return [
PythonSourceTarget.register_plugin_field(SkipDocformatterField),
PythonSourcesGeneratorTarget.register_plugin_field(SkipDocformatterField),
PythonTestTarget.register_plugin_field(SkipDocformatterField),
PythonTestsGeneratorTarget.register_plugin_field(SkipDocformatterF... |
arjunsatyapal/lantern | demo1/quiz/models.py | Python | apache-2.0 | 6,723 | 0.010858 | #!/usr/bin/python
#
# Copyright 2010 Google Inc.
#
# 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 law or ag... | d (key) for particular version of the quiz.
time_stamp: Time_stamp for a new revision.
commit_message: Commit message associated with new version.
"""
quiz_id = db.StringProperty()
time_stamp = db.DateTimeProperty(auto_now=True)
commit_messa | ge = db.StringProperty(default='Commiting a new version')
class QuizPropertyModel(QuizBaseModel):
"""Defines various properties for a quiz.
Attributes:
shuffle_questions: If set questions are presented in random order.
min_options: minimum number of options to be presented.
max_options: maximum numb... |
econti/quora-clone | quora/questions/migrations/0001_initial.py | Python | mit | 3,169 | 0.003471 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2016-01-20 03:46
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migration... | uestions',
},
| ),
migrations.CreateModel(
name='QuestionComment',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('comment', models.CharField(max_length=500)),
('date', models.DateTimeFiel... |
huyphan/pyyawhois | test/record/parser/test_response_whois_centralnic_com_hu_com_status_registered.py | Python | mit | 6,533 | 0.00199 |
# This file is autogenerated. Do not edit it manually.
# If you want change the content of this file, edit
#
# spec/fixtures/responses/whois.centralnic.com/hu.com/status_registered
#
# and regenerate the tests with the following script
#
# $ scripts/generate_tests.py
#
from nose.tools import *
from dateutil.parse... | ngDelete", "pendingDelete"])
def test_available(self):
eq_(self.record.available, False)
def test_domain(self):
eq_(self.record.domain, "porn.hu.com")
def test_nameservers(self):
eq_(self.record.nameservers.__class__.__name__, 'list')
eq_(len(self.record.nameservers), 2)
... | e__, 'Nameserver')
eq_(self.record.nameservers[0].name, "ns1.sedoparking.com")
eq_(self.record.nameservers[1].__class__.__name__, 'Nameserver')
eq_(self.record.nameservers[1].name, "ns2.sedoparking.com")
def test_admin_contacts(self):
eq_(self.record.admin_contacts.__class__.__name_... |
grnet/synnefo | snf-admin-app/synnefo_admin/admin/tests/projects.py | Python | gpl-3.0 | 1,582 | 0.001274 | # -*- coding: utf-8 -*-
# Copyright (C) 2010-2014 GRNET S.A.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This ... | # Get the member and project quota.
member_quota = get_project_quota_category(self.project, "member")
project_quota = get_project_quota_category(self.project, "limit")
# Compare them to the ones in the application.
self.assertEqual(mem | ber_quota, [(desc, '512')])
self.assertEqual(project_quota, [(desc, '1024')])
|
pombredanne/msgpack-numpy | setup.py | Python | bsd-3-clause | 1,407 | 0.022743 | #!/usr/bin/env python
import sys, os
from glob import glob
try:
import setuptools
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup
NAME = 'msgpack-numpy'
VERSION = '0.3.6'
AUTHOR = 'Lev Givon'
AUTHOR_EMAIL = ... | 'MANIFEST'):
os.remove('MANIFEST')
setup(
name = NAME,
version = VERSION,
author = AUTHOR,
author_email = AUTHOR_EMAIL,
license = LICENSE,
classifiers = CLASSIFIERS,
description = DESCRIPTION,
long_description = LONG_DESCRIPTION,
url =... | = ['numpy',
'msgpack-python>=0.3.0']
)
|
s20121035/rk3288_android5.1_repo | external/deqp/android/scripts/GenAndroidCTSXML.py | Python | gpl-3.0 | 5,485 | 0.025889 | import argparse
import string
class TestGroup:
def __init__(self, name, parent = None):
self.parent = parent
self.name = name
self.testGroups = {}
self.testCases = {}
if parent:
assert not name in parent.testGroups
parent.testGroups[name] = self
def getName (self):
return self.name
def getPath ... | string.split(p | ath, ".")
currentGroup = rootGroup
assert pathComponents[0] == rootGroup.getName()
for i in range(1, len(pathComponents)):
component = pathComponents[i]
if i == len(pathComponents) - 1:
TestCase(component, currentGroup)
else:
if currentGroup.hasGroup(component):
currentGroup = currentGroup.getGrou... |
spixi/wesnoth | data/tools/wesnoth/wmlparser3.py | Python | gpl-2.0 | 27,879 | 0.002152 | #!/usr/bin/env python3
# encoding: utf-8
"""
This parser uses the --preprocess option of wesnoth so a working
wesnoth executable must be available at runtime if the WML to parse
contains preprocessing directives.
Pure WML can be parsed as is.
For example:
wml = ""
[unit]
id=elve
name=Elve
... | al("id"))
Because no preprocessing is required, we did not have to pass the
location | of the wesnoth executable to Parser.
The get_all method always returns a list over matching tags or
attributes.
The get_name method can be used to get the name and the get_text_val
method can be used to query the value of an attribute.
"""
import os, glob, sys, re, subprocess, argparse, tempfile, shutil
import atex... |
pkrusche/bsponmpi_template | site_scons/toolsets/clang.py | Python | mit | 1,021 | 0.039177 | import os
###############################################################################
# Make add options to an environment to use GCC
###################################### | #########################################
#
# Required options in root env:
# mode : 'debug' or 'release
# debuginfo : true or false to include debug info also in release versi | on
# profile : true or false to enable/disable gprof support
#
def generate (root):
root['CC'] = 'clang'
root['CXX'] = 'clang++'
root['LINK'] = 'clang++'
if os.environ.has_key('TERM'):
root['ENV']['TERM'] = os.environ['TERM']
mode = root['mode']
debuginfo = root['debuginfo']
profile = root['prof... |
CarlosMart626/umusicfy | umusicfy/umusicfy/urls.py | Python | apache-2.0 | 1,887 | 0.00212 | """umusicfy URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-b... | he include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url, include
from django.contrib import admin
from rest_framework_jwt.views import obtain_jwt_token
from rest_framework_jwt.views import refresh_jwt_t... | ation API Router
from rest_framework import routers
from songs.views import ArtistViewSet, AlbumViewSet, SongViewSet
router = routers.DefaultRouter()
router.register(r'artists', ArtistViewSet)
router.register(r'albums', AlbumViewSet)
router.register(r'songs', SongViewSet)
urlpatterns = [
url(r'^', include('index.... |
compstak/selenium | py/test/selenium/webdriver/common/webdriverwait_tests.py | Python | apache-2.0 | 16,435 | 0.004807 | #!/usr/bin/python
# Copyright 2011 WebDriver committers
#
# 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 l... | d_element_by_id('clickToShow').click()
element = WebDriverWait(self.driver, 5).until(EC.visibility_of(hidden))
self.assertTrue(element.is_displayed())
def testExpectedConditionTextToBePresentInElement(self):
| self._loadPage('booleanAttributes')
try:
WebDriverWait(self.driver, 0.7).until(EC.text_to_be_present_in_element((By.ID, 'unwrappable'), 'Expected'))
self.fail("Expected TimeoutException to have been thrown")
except TimeoutException as e:
pass
self.driver.execu... |
openstack/ceilometer | ceilometer/tests/unit/network/statistics/test_port.py | Python | apache-2.0 | 3,879 | 0 | #
# Copyright 2014 NEC Corporation. All rights reserved.
#
# 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... | rTestBase):
def test_port_pollster(self):
self._test_pollster(
port.PortPollster,
'switch.port',
sample.TYPE_GAUGE,
'port')
def test_port_pollster_uptime(self):
self._test_pollster(
port.PortPollsterUptime,
'switch.port.up... | ceive_packets(self):
self._test_pollster(
port.PortPollsterReceivePackets,
'switch.port.receive.packets',
sample.TYPE_CUMULATIVE,
'packet')
def test_port_pollster_transmit_packets(self):
self._test_pollster(
port.PortPollsterTransmitPacket... |
Azure/WALinuxAgent | azurelinuxagent/common/utils/textutil.py | Python | apache-2.0 | 12,526 | 0.001517 | # Microsoft Azure Linux Agent
#
# Copyright 2018 Microsoft Corporation
#
# 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 b... |
"""
if type(a) == type(b'') or type(a) == type(u''):
a = ord(a)
return a
def compare_bytes(a, b, start, length):
for offset in range(start, start + length):
if str_to_ord(a[offset]) != str_to_ord(b[offset]):
return False
return True
def int_to_ip4_addr(a):
"""
... | 8) & 0xFF,
(a) & 0xFF)
def hexstr_to_bytearray(a):
"""
Return hex string packed into a binary struct.
"""
b = b""
for c in range(0, len(a) // 2):
b += struct.pack("B", int(a[c * 2:c * 2 + 2], 16))
return b
def set_ssh_config(config, name, val):
found ... |
maferelo/saleor | saleor/account/migrations/0034_service_account_token.py | Python | bsd-3-clause | 1,717 | 0.000582 | import django.db.models.deletion
import oauthlib.common
from django.db import migrations, models
def move_existing_token(apps, schema_editor):
ServiceAccount = apps.get_model("account", "ServiceAccount")
for service_account in ServiceAccount.objects.iterator():
service_account.tokens.create(
... | ed=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("name", models.CharField(blank=True, default="", max_length=128)),
(
"auth_token",
... | models.CharField(
default=oauthlib.common.generate_token,
max_length=30,
unique=True,
),
),
(
"service_account",
models.ForeignKey(
... |
pintostack/core | infrastructure/windows_azure.py | Python | apache-2.0 | 8,648 | 0.003122 | #!/usr/bin/env python
'''
Windows Azure external inventory script
=======================================
Generates inventory that Ansible can understand by making API request to
Windows Azure using the azure python library.
NOTE: This script assumes Ansible is being executed where azure is already
installed.
p... | ue)
pri | nt data_to_print
def get_images(self):
images = []
for image in self.sms.list_os_images():
if str(image.label).lower().find(self.args.list_images.lower()) >= 0:
images.append(vars(image))
return json.loads(json.dumps(images, default=lambda o: o.__dict__))
de... |
thoreg/satchmo | satchmo/apps/satchmo_ext/recentlist/context_processors.py | Python | bsd-3-clause | 606 | 0.018152 | from livesettings import config_value
from product.models import Product
def recent_products(request):
"""Puts the recently-viewed products in the page variables"""
recent = | request.session.get('RECENTLIST',[])
maxrecent = config_value('PRODUCT','RECENT_MAX')
products = []
for slug in recent:
if len(products) > maxrecent:
break
try:
p = Product.objects.get_by_site(slug__exact = slug)
products.append(p)
... | s}
|
seleniumbase/SeleniumBase | seleniumbase/console_scripts/rich_helper.py | Python | mit | 1,219 | 0 | from rich.console import Console
from rich.markdown import Markdown
from rich.syntax import Syntax
def process_syntax(code, lang, theme, line_numbers, code_width, word_wrap):
syntax = Syntax(
code,
lang,
theme=theme,
line_numbers=line_numbers,
code_width=code_width,
... | # noqa
return True # Success
| except Exception:
return False # Failure
def display_code(code):
try:
console = Console()
console.print(code) # noqa
return True # Success
except Exception:
return False # Failure
def fix_emoji_spacing(code):
try:
# Fix the display width of certain... |
dwillmer/fastats | tests/maths/test_gamma.py | Python | mit | 878 | 0 |
from pytest import approx, raises
from fastats.maths.gamma import gammaln
def test_gamma_ints():
assert gammaln(10) == approx(12.801827480081469, rel=1e-6)
assert gammaln(5) == approx(3.1780538303479458, rel=1e-6)
assert gammaln(19) == approx(36.39544520803305, rel=1e-6)
def test_gamma_floats():
a... | 71155090776673, rel=1e-6)
assert gammaln(8.8129) == approx(10.206160943471318, rel=1e-6)
assert gammaln(12.001) == approx(17.50475055100354, rel=1e-6)
assert gammaln(0.007812) == approx(4.847635060148693, rel=1e-6)
assert gammaln(86.13) == approx(296.3450079998172, rel=1e- | 6)
def test_gamma_negative():
raises(AssertionError, gammaln, -1)
raises(AssertionError, gammaln, -0.023)
raises(AssertionError, gammaln, -10.9)
if __name__ == '__main__':
import pytest
pytest.main([__file__])
|
lugino-emeritus/py-keysaver | keysaver.py | Python | gpl-3.0 | 13,387 | 0.028909 | '''
file syntax:
- version (2 byte), b'\x00\x01'
- encryption method (2 bytes):
b'\x00\x01':
- argon2id to expand pw to 32 byte key with 32 byte salt
- 32 byte salt to derive a master token = sha256(salt + pw)
- AES GCM global encryption with 12 byte nonce
- AES CBC for passwords: 16 byte iv, token as k... | ame):
self.filename = filename
self._method = None
self._enc_salt = None
self._enc_key = None
self._token_data = None
self._token = None
@property
def method(self):
return self._method
def _refresh_pw(self, pw):
if self._method == b'\x00\x00':
self._enc_salt = b''
self._enc_key = b''
elif s... | f._enc_key = crypto.argon2_param1_hash(pw, self._enc_salt)
else:
raise KeyError(f'method {self._method} unknown')
def _check_pw(self, pw):
if self._method == b'\x00\x00':
return True
elif self._method == b'\x00\x01':
return crypto.argon2_param1_hash(pw, self._enc_salt) == self._enc_key
else:
raise... |
Proteus-tech/nikola | nikola/plugins/task/rss.py | Python | mit | 3,784 | 0.000529 | # -*- coding: utf-8 -*-
# Copyright © 2012-2013 Roberto Alsina and others.
# 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 t... | ture__ import unicode_literals, print_function
import os
try:
from urlparse import urljoin
except ImportError:
from urllib.parse import urljoin # NOQA
from nikola import utils
from nikola.plugin_categories import Task
class GenerateRSS(Task) | :
"""Generate RSS feeds."""
name = "generate_rss"
def set_site(self, site):
site.register_path_handler('rss', self.rss_path)
return super(GenerateRSS, self).set_site(site)
def gen_tasks(self):
"""Generate RSS feeds."""
kw = {
"translations": self.site.confi... |
rogerthat-platform/rogerthat-backend | src/rogerthat/cron/log_retention.py | Python | apache-2.0 | 810 | 0 | # -*- coding: utf-8 -*-
# Copyright 2017 GIG Technology NV
#
# 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 law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY ... | n:1.3@@
from google.appengine.ext import webapp
from rogerthat.utils import log_offload
class SendLogs(webapp.RequestHandler):
def get(self):
log_offload.export_logs()
|
UMWRG/PywrApp | hydra_pywr/__init__.py | Python | gpl-3.0 | 49 | 0 | from | hydra_pywr_common.hydropower_nodes import | *
|
zhouhoo/wiki_zh_vec | wikiextractor/extractPage.py | Python | apache-2.0 | 4,438 | 0.002479 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# =============================================================================
# Version: 2.9 (Feb 13, 2016)
# Author: Giuseppe Attardi (attardi@di.unipi.it), University of Pisa
# =============================================================================
# Copyright (... | age:
page.append(line)
print '</mediawiki>'
input.close()
def main():
parser = argparse.ArgumentParser(prog=os.path.basename(sys.argv[0]),
formatter_class=argparse.RawDescriptionHelpFormatter,
description=__doc__)
parser.add_argument("input",
... | ser.add_argument("--template", action="store_true",
help="extract also all templates")
parser.add_argument("-v", "--version", action="version",
version='%(prog)s ' + version,
help="print program version")
args = parser.parse_args()
pr... |
Venris/crazyflie-multilink | lib/cfclient/utils/input.py | Python | gpl-2.0 | 15,839 | 0.001831 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# || ____ _ __
# +------+ / __ )(_) /_______________ _____ ___
# | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \
# +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/
# || || /_____/_/\__/\___/_/ \__,_/ /___/\___/
#
# Copyright (C) 20... | nt.utils.mux.takeovermux import TakeOverMux
from cfclient.utils.mux.mixmux import MixMux
from cfclient.utils.mux.takeoverselectivemux import TakeOverSelectiveMux
MAX_THRUST = 65000
class JoystickReader:
"""
Thread that will read input from devices/joysticks and send control-set
ponts to the | Crazyflie
"""
inputConfig = []
def __init__(self, do_device_discovery=True):
self._input_device = None
self._min_thrust = 0
self._max_thrust = 0
self._thrust_slew_rate = 0
self._thrust_slew_enabled = False
self._thrust_slew_limit = 0
self._has_pressu... |
krnflake/s3ql | src/s3ql/inherit_docstrings.py | Python | gpl-3.0 | 4,064 | 0.003692 | '''
inherit_docstrings.py - this file is part of S3QL (http://s3ql.googlecode.com)
Copyright © 2008 Nikolaus Rath <Nikolaus@rath.org>
This program can be distributed under the terms of the GNU GPLv3.
---
This module defines a metaclass and function decorator that allows
to inherit the docstring for a function from ... | tinue
fn.__doc__ = super_fn.__doc__
break
else:
raise RuntimeError("Can't inherit docstring for %s: method does not "
"exist in superclass | " % fn.__name__)
return fn
# This definition is only used to assist static code analyzers
def prepend_ancestor_docstring(fn):
'''Prepend docstring from superclass method
For this decorator to work, the class has to use the `InheritableDocstrings`
metaclass.
'''
raise RuntimeError('Decorator c... |
emesene/emesene | emesene/e3/cache/PictureCache.py | Python | gpl-3.0 | 4,793 | 0.000626 | '''a module to define a cache class for pictures'''
# -*- coding: utf-8 -*-
# This file is part of emesene.
#
# emesene is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the Licen... | cache
'''
return self.parse().items()
def insert(self, item):
'''insert a new item into the cache
return the information (stamp, hash) on success None otherwise
item -- a path to an image
'''
hash_ = Cache.get_file_path_hash(item)
if hash_ is None:
... | hash_)
last_path = os.path.join(self.path, 'last')
shutil.copy2(item, path)
shutil.copy2(item, last_path)
return self.__add_entry(hash_)
def insert_url(self, url):
'''download and insert a new item into the cache
return the information (stamp, hash) on success None ... |
gsathya/htpt | htpt/socks4a/htptProxy.py | Python | mit | 40,287 | 0.004294 | #!/usr/bin/env python
# Ben Jones
# Georgia Tech
# Spring 2014
#
# htpt-socks.py: this file builds upon the work of Zavier Lagraula's
# PySocks code to create a SOCKS server for our HTTP circumvention tool
import socks
"""SOCKS 4 proxy server class.
Copyright (C) 2001 Xavier Lagraula
See COPYRIGHT.txt an... | _timeout'
result[opt] = value
return ConfigFile.evaluate(definitions, result, defaults)
def __init__(self, RequestHandlerClass, | *args):
"""Constructor of the server."""
self.Options = DEFAULT_OPTIONS
listenPort = args[0]
if len(args) > 1:
sendPort = args[1]
self.Options['send_port'] = sendPort
self.Options['bind_port'] = listenPort
print "Server starting with foll... |
fouzelddin/py4j | py4j-python/src/py4j/compat.py | Python | bsd-3-clause | 2,249 | 0 | # coding: utf-8
"""
Compatibility functions for unified behavior between Python 2.x and 3.x.
:author: Alex Grönholm
"""
from __future__ import unicode_literals, absolute_import
import inspect
import sys
from threading import Thread
if sys.version_info[0] < 3:
def items(d):
return d.items()
def iteri... | return x.next()
range = xrange # noqa
long = long # noqa
basestring = basestring # noqa
unicode = unicode # noqa
bytearray2 = bytearray
unichr = unichr # noqa
bytestr = str
tobytestr = str
def isbytestr(s):
return isinstance(s, str)
def ispython3bytest... | rn isinstance(s, bytearray)
def bytetoint(b):
return ord(b)
def bytetostr(b):
return b
def strtobyte(b):
return b
import Queue
Queue = Queue.Queue
else:
def items(d):
return list(d.items())
def iteritems(d):
return d.items()
next = next
... |
tonygalmiche/is_coheliance | report/__init__.py | Python | agpl-3.0 | 147 | 0 | # -*- coding: utf-8 -*-
import is_suivi_facture
import is_suivi_refacturation_ass | ocie
import is_suivi_intervention
import is_account_invoice_line | |
wchan/tensorflow | tensorflow/python/ops/op_def_library.py | Python | apache-2.0 | 27,846 | 0.008403 | # Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you ma | y 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 law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR COND... | e the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Class to hold a library of OpDefs and use it to create Brain operations."""
from __future__ import absolute_import
from __future__ impo... |
rsc-dev/loophole | loophole/__main__.py | Python | mit | 9,572 | 0.002507 | #!/usr/bin/env python
__author__ = 'Radoslaw Matusiak'
__copyright__ = 'Copyright (c) 2016 Radoslaw Matusiak'
__license__ = 'MIT'
__version__ = '0.5'
import cmd
import functools
import os
import sys
from polar import Device
from polar.pb import device_pb2 as pb_device
__INTRO = """
_| ... | print "Device no: %i" % i
print "Device info:"
print dev
print " | -"*79
if 'langid' in err.message:
raise ValueError(
(
"Can't get device info. Origin Error: %s\n"
"Maybe this is a permission issue.\n"
"Please read sec... |
mick-d/nipype | nipype/interfaces/spm/tests/test_auto_ApplyTransform.py | Python | bsd-3-clause | 1,064 | 0.016917 | # AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
from __future__ import unicode_literals
from ..utils import ApplyTransform
def test_ApplyTransform_inputs():
input_map = dict(ignore_exception=dict(nohash=True,
usedefault=True,
),
in_file=dict(copyfile=True,
mandatory=True,
),
mat=dict... | ct(genfile=True,
),
paths=dict(),
use_mcr=dict(),
use_v8struct=dict(min_ver | ='8',
usedefault=True,
),
)
inputs = ApplyTransform.input_spec()
for key, metadata in list(input_map.items()):
for metakey, value in list(metadata.items()):
assert getattr(inputs.traits()[key], metakey) == value
def test_ApplyTransform_outputs():
output_map = dict(out_file... |
x0mak/test---project---python---Kurbatova | php4dvd/model/user.py | Python | apache-2.0 | 272 | 0.003676 | class User(object):
def __ | init__(self, username=None, password=None, email=None):
self.username = username
self.password = password
self.email = email
@classmethod
def Admin(cls):
return cls(username="admin", password="ad | min") |
frederica07/Dragon_Programming_Process | PyOpenGL-3.0.2/OpenGL/raw/GL/NV/conditional_render.py | Python | bsd-2-clause | 812 | 0.024631 | '''Autogenerated by get_gl_extensions script, do not edit!'''
from OpenGL import platform as _p, constants as _cs, arrays
from OpenGL.GL import glget
import ctypes
EXTENSION_NAME = 'GL_NV_conditional_render'
def _f( function ):
return _p.createFunction( function,_p.GL,'GL_NV_conditional_render',False)
_p.unpack_con... | _QUERY_BY_REGION_WAIT_NV 0x8E15
GL_QUERY_BY_REGION_NO_WAIT_NV 0x8E16""", globals())
@_f
@_p.types(None,_cs.GLuint,_cs.GLenum)
def glBeginConditionalRenderNV( id,mode ):pass
@_f
@ | _p.types(None,)
def glEndConditionalRenderNV( ):pass
def glInitConditionalRenderNV():
'''Return boolean indicating whether this extension is available'''
from OpenGL import extensions
return extensions.hasGLExtension( EXTENSION_NAME )
|
bjornedstrom/toytls | toytls/hash.py | Python | mit | 890 | 0 | # -*- coding: utf-8 -*-
""" reference implementation of TLS PRF from tlslite
"""
import hashlib
impor | t math
import hmac
def P_hash(hashmod, secret, seed, length):
bytes = ['\x00'] * leng | th
A = seed
index = 0
while 1:
A = hmac.HMAC(secret, A, hashmod).digest()
output = hmac.HMAC(secret, A+seed, hashmod).digest()
for c in output:
if index >= length:
return ''.join(bytes)
bytes[index] = c
index += 1
return ''.join... |
plotly/python-api | packages/python/plotly/plotly/validators/layout/yaxis/_fixedrange.py | Python | mit | 456 | 0.002193 | import _plotly_utils.basevalidators
class FixedrangeValidator(_plotly_utils.basevalidators.BooleanValidator) | :
def __init__(self, plotly_name="fixedrange", parent_name="layout.yaxis", **kwargs):
super(FixedrangeValidator | , self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "calc"),
role=kwargs.pop("role", "info"),
**kwargs
)
|
samuelmaudo/yepes | yepes/utils/unidecode/x082.py | Python | bsd-3-clause | 4,649 | 0.055066 | data = (
'Yao ', # 0x00
'Yu ', # 0x01
'Chong ', # 0x02
'Xi ', # 0x03
'Xi ', # 0x04
'Jiu ', # 0x05
'Yu ', # 0x06
'Yu ', # 0x07
'Xing ', # 0x08
'Ju ', # 0x09
'Jiu ', # 0x0a
'Xin ', # 0x0b
'She ', # 0x0c
'She ', # 0x0d
'Yadoru ', # 0x0e
'Jiu ', # 0x0f
'Shi ', # 0x10
'Tan ... | ', # 0x8c
'Shuo ', # 0x8d
'Qiong ', # 0x8e
'Tu ', # 0x8f
'Xia ', # 0x90
'Qi ', # 0x91
'Mang ', # 0x92
| 'Zi ', # 0x93
'Hui ', # 0x94
'Sui ', # 0x95
'Zhi ', # 0x96
'Xiang ', # 0x97
'Bi ', # 0x98
'Fu ', # 0x99
'Tun ', # 0x9a
'Wei ', # 0x9b
'Wu ', # 0x9c
'Zhi ', # 0x9d
'Qi ', # 0x9e
'Shan ', # 0x9f
'Wen ', # 0xa0
'Qian ', # 0xa1
'Ren ', # 0xa2
'Fou ', # 0xa3
'Kou ', # 0x... |
jedijulia/starwarspwa | starwarspwa/migrations/0003_auto_20160901_1650.py | Python | mit | 955 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2016-09-01 16:50
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('starwarspwa', '0002_subscription'),
]
operations = [
migrations.RemoveField(
... | Field(max_length=255, blank=True, null=True),
),
migrations.AddField(
model_name='subscription',
name='endpoint',
field=models.CharField(max_length=255, blank=True, null=True),
),
migrations.AddField(
model_name='subscription',
... | field=models.CharField(max_length=255, blank=True, null=True),
),
]
|
ColinIanKing/autotest | scheduler/monitor_db_unittest.py | Python | gpl-2.0 | 58,290 | 0.002608 | #!/usr/bin/python
import gc, logging, time
try:
import autotest.common as common
except ImportError:
import common
from autotest.frontend import setup_django_environment
from autotest.frontend.afe import frontend_test_utils
from autotest.client.shared.test_utils import mock
from autotest.client.shared.test_uti... | ound))
def _check_for_extra_schedulings(self):
if len(self._jobs_scheduled) != 0:
self.fail('Extra jobs scheduled: ' +
str(self._jobs_scheduled))
def _convert_jobs_to_metahosts(self, *job_ids):
sql_tuple = '(' + ','.join(str(i) for i in job_ids) + ')'
... | afe_host_queue_entries SET '
'meta_host=host_id, host_id=NULL '
'WHERE job_id IN ' + sql_tuple)
def _lock_host(self, host_id):
self._do_query('UPDATE afe_hosts SET locked=1 WHERE id=' +
str(host_id))
def setUp(self):
super(... |
d3matt/d3matt.com | src/d3matt/d3matt/wsgi.py | Python | bsd-2-clause | 387 | 0.002584 | """
WSGI | config for d3matt 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/1.6/howto/deployment/wsgi/
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "d3matt.settings")
from django.core.wsgi import ... | plication = get_wsgi_application()
|
urmyfaith/notes_web_py | basic/Templetor/05templetor-control-structures.py | Python | apache-2.0 | 296 | 0.047297 | i | mport web
render = web.template.render('templates/')
urls = (
'/(.*)', 'index'
)
class index:
def GET(self,name):
i=web.input(name=None)
return render.controlStructures(name)
if __name__ == "__main__":
app = web.application(urls, globals())
a | pp.run()
|
fastflo/emma | emmalib/__init__.py | Python | gpl-2.0 | 2,772 | 0.002886 | # -*- coding: utf-8 -*-
# emma
#
# Copyright (C) 2006 Florian Schmidt (flo@fastflo.de)
# 2014 Nickolay Karnaukhov (mr.electronick@gmail.com)
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software F... | == "-l" or arg == "--log":
if i + 1 == len(args):
usage()
log_file = args[i + 1]
skip = True
else:
usage()
# this singleton will be accessible as sys.stdout!
OutputHandler(debug_output, log_file, log_flush)
emma_inst | ance = Emma()
emma_instance.start()
gtk.main()
return 0
|
ndtran/l10n-switzerland | l10n_ch_account_statement_base_import/parser/ubs_file_parser.py | Python | agpl-3.0 | 7,013 | 0 | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2015 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Steve Ferry
#
# This program is free software: you can redistribute it and... | se_statement_balance(self):
"""Parse file start and | end balance
:return: Tuple of the file start and end balance
:rtype: float
"""
solde_line = self.lines[-1].split(";")
balance_end = float_or_zero(solde_line[0])
balance_start = float_or_zero(solde_line[1])
return balance_start, balance_end
def _p... |
NBor/SkyPython | src/layers/Layer.py | Python | apache-2.0 | 5,449 | 0.004588 | '''
// Copyright 2009 Google Inc.
//
// 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 law or agre... |
def get_layer_name(self):
raise NotImplementedError("need strings.xml")
def __init__(self):
''' |
Constructor
'''
self.render_map = {}
self.render_controller = None |
globality-corp/microcosm-flask | microcosm_flask/tests/swagger/parameters/test_enum.py | Python | apache-2.0 | 1,133 | 0.000883 | from enum import Enum, IntEnum, unique
from hamcrest import assert_that, equal_to, is_
from marshmallow import Schema
from microcosm_flask.fields import EnumField
from microcosm_flask | .swagger.api import build_parameter
@unique
class Choices(Enum):
Profit = "profit"
@unique
class ValueType(IntEnum):
Foo = 1
Bar = 2
class TestSchema(Schema):
choice = EnumField(Choices)
value = EnumField(ValueType, by_value=True)
def test_field_enum():
parameter = build_parameter(TestSc... | t",
],
})))
def test_field_enum_non_strict():
parameter = build_parameter(TestSchema().fields["choice"], strict_enums=False)
assert_that(parameter, is_(equal_to({
"type": "string",
})))
def test_field_int_enum():
parameter = build_parameter(TestSchema().fields["value"])
asser... |
jbrackins/scheduling-research | src/location.py | Python | unlicense | 3,581 | 0.0148 | from rec import CourseRecord
from score import RoomScore
from evaluation import ScheduleEvaluation
FULL_HOURS = 8 # 8:00AM - 4:00PM utilization
PARTIAL_HOURS = FULL_HOURS * 0.75 #75%
HALF_HOURS = FULL_HOURS * 0.50 #50%
SPARSE | _HOURS = FULL_HOURS * 0.25 #25%
class LocationScore:
def __init__(self, evals=None):
sel | f.evals = evals
self.courses = None
self.location = None
self.daily_weights = {"M": {}, "T": {}, "W": {}, "R": {}, "F": {} ,"S": {}}
self.daily_totals = {"M": {}, "T": {}, "W": {}, "R": {}, "F": {} ,"S": {}}
self.final_weighted = 0
self.weight_rank = 0 # 0 = wor... |
slint/zenodo | zenodo/modules/records/serializers/schemas/marc21.py | Python | gpl-2.0 | 12,434 | 0.000161 | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2016 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later v... |
# Custom
# ======
resource_type = fields.Raw(attribute='metadata.resource_type')
communities = fields.Raw(attribute='metadata.communities')
references = fields.Raw(attribute='metadata.references')
embargo_date = fields.Raw(attribute='metadata.embargo_date')
journal = fields.Raw(attrib... | od('get_files')
leader = fields.Method('get_leader')
conference_url = fields.Raw(attribute='metadata.meeting.url')
def get_leader(self, o):
"""Return the leader information."""
rt = o['metadata']['resource_type']['type']
rec_types = {
'image': 'two-dimensional_nonproje... |
Xosebelge/Pascal_Practicums | 09.06/2.py | Python | mit | 221 | 0.090498 | #coding: utf-8
inpu | t_string=raw_input()
brackets=0
for i in input_string:
if i=="(":
brackets+=1
elif i==")":
brackets-=1
if brackets<0:
print "No"
break
else:
if brackets>0:
print " | No"
else:
print "Yes"
|
AustinHartman/randomPrograms | reciprocal_cycles.py | Python | gpl-3.0 | 309 | 0.009709 | unit_fracs = [] | # Create list of all reciprocal frac 1-1000
for i in range(1, 1000):
unit_fracs.append(str(1/i)[2:])
unit_fracs = [frac for frac in unit_fracs if len(frac) > 4] # Filter all | list elements under 4 characters
print(unit_fracs)
|
hlerebours/lambda-calculus | lambdax/test/test_exposed.py | Python | mit | 3,947 | 0.001778 | """ Check what the `lambdax` module publicly exposes. """
import builtins
from inspect import isbuiltin, ismodule, isclass
from itertools import chain
import operator
from unittest.mock import patch
import lambdax.builtins_as_lambdas
import lambdax.builtins_overridden
from lambdax import x1, x2, x
def _get_exposed(t... | eth = tail[:-2]
original = _get_method_or_object(getattr(builtins, obj), meth)
as_λ = getattr(lambdax.builtins_as_lambdas, name)
overridden = _get_method_or_object(getattr(lambdax.builtins_overridden, obj), meth)
ref, ref_output = _get_effect(original)
expl, expl_output = _get_ef... | effect(overridden(x))
assert lbda_output == iso_output == expl_output == ref_output
try:
assert list(iter(lbda)) == list(iter(iso)) == list(iter(expl)) == list(iter(ref))
except TypeError:
assert lbda == iso == expl == ref
|
olsove/ougn-2017-p78 | locust/test/locustfile.py | Python | apache-2.0 | 4,070 | 0.010565 | from locust import HttpLocust, TaskSet, task, events
# names : random name generator https://github.com/treyhunner/names
import names
import os
def print_error(type, loc, code, reason) :
print "Error %s %s %s Reason:%s"%(type, code, loc, reason)
def print_success(type, loc, code) :
print "Success %s %s %s"%(t... | k(20)
def findByFirstName(self):
url = "%s/search/findByFirstName?name=%s"%(UserBehavior.root,names.get_first_name())
r = self.client.get(url=url, name="people/search/findByFirstName?name={name}")
type = "GET"
if r.status_code == 200 :
| print_success(type, url, r.status_code)
else:
print_error(type, url , r.status_code, r.reason)
@task(30)
def findByLastName(self):
url = "%s/search/findByLastName?name=%s"%(UserBehavior.root,names.get_last_name())
r = self.client.get(url=url, name="people/search/... |
soft-matter/pims_nd2 | setup.py | Python | bsd-3-clause | 1,353 | 0.000739 | import os
from setuptools import setup
try:
descr = open(os.path.join(os.path.dirname(__file__), 'README.md')).read()
except IOError:
descr = ''
try:
from pypandoc import convert
descr = convert(descr, 'rst', format='md')
except ImportError:
pass
setup_parameters = dict(
name="pims_nd2",
... |
"Operating System :: POSIX",
"Operating System :: Unix",
"Operating System :: MacOS"],
platforms=['MacOS X', 'Windows', 'Linux CentOs 6.5/7' | , 'Linux Debian 7/8'],
long_description=descr)
setup(**setup_parameters)
|
s34rching/python_classes | tests/test_contact_data.py | Python | apache-2.0 | 2,053 | 0.006332 | import re
import random
def test_contact_data_from_home_page(app):
r_index = random.randrange(len(app.contact.get_contact_list()))
data_from_home_page = app.contact.get_contact_list()[r_index]
data_from_edit_page = app.contact.get_contact_info_from_edit_page(r_index)
assert data_from_home_page.firstna... | page.address
assert data_from_home_page.all_phones_from_homepage == merge_phones_like_on_homepage(data_from_edit_page)
assert data_from_home_page.all_emails_from_homepage == merge_emails_like_on_homepage(data_from_edit_page)
assert data_from_home_page.id == data_from_edit_page.id
def test_phones_from_v | iew_page(app):
r_index = random.randrange(len(app.contact.get_contact_list()))
data_from_view_page = app.contact.get_contact_info_from_view_page(r_index)
data_from_edit_page = app.contact.get_contact_info_from_edit_page(r_index)
assert data_from_view_page.home_number == data_from_edit_page.home_number
... |
dfdeshom/reds | reds/redis_hash_layer.py | Python | gpl-2.0 | 1,323 | 0.013605 | import redis
from hashlib import sha1
class RedisHashLayer(object):
"""
A more memory-efficient way to store many small values in redis using hashes.
See http://antirez.com/post/redis-weekly-update-7.html
| Note: add these config value to redis:
hash-max-zipmap-entries 512
hash-max-zipmap-value 512
"""
def __init__(self,connection,name):
| self.connection = connection
self.name = name
def _get_hashname(self,key):
field = sha1(str(key)).hexdigest()
hashkey = "%s:%s" % (self.name, field[:4])
return (hashkey,field)
def __contains__(self,key):
hashkey,field = self._get_hashname(key)
res = self.connect... |
sirotin/at-a-glance-of-a-key | simple-python-testing-framework/tests/test_python_version.py | Python | mit | 658 | 0.004559 | # Author: Alexander Sirotin / sirotin@gmail.com
# Co | pyright (c) 2017 Alexander Sirotin.
# Licensed under MIT license:
# https://opensource.org/licenses/mit-license.php
# Your use is on an "AS-IS" basis, and subject to the terms and conditions of this license.
from tests_common impor | t TestBase, setup_logger
import sys
logger = setup_logger("TestPythonVersion")
class TestPythonVersion(TestBase):
@classmethod
def run_test(cls):
result = sys.version_info
logger.info("Python version is %d.%d.%d" % (result.major, result.minor, result.micro))
if result.major != 2:
... |
kaustubhhiware/hiPy | think_python/lists2.py | Python | mit | 1,424 | 0.019663 | def no_extreme(listed):
"""
Takes a list and chops off extreme ends
"""
del listed[0]
del listed[-1:]
return listed
def better_no_extreme(listed):
"""
why better ? For starters , does not modify original list
"""
return listed[1:-1]
t = ['a','b','c']
print t
print '\n'
print 'pop any element : by t.pop(1) ... | 'this splits at - '
print 'joining statement : '
delimeter=' '
print delimeter.join(listr2)
print '\nNote: 2 identical lists are 2 objects ,so l_a is l_b for identical lists still says False'
print 'This does not happen for strings etc'
print 'l_a is l_b only true if assigned as l_b = l_a'
print '\n t.append(x) retu... | ()'
print '\nDO\'s : t.append(x)\n t = t+[x] \n '
print 'Keep copy of original just in case : orig = t[:] \nt.sort()'
print '\nDONT\'s : t.append([x])\n t = t.append(x) \n t + [x] \n t = t + x' |
tannishk/airmozilla | airmozilla/manage/tests/test_autocompeter.py | Python | bsd-3-clause | 9,999 | 0 | import datetime
import json
from nose.tools import ok_, eq_, assert_raises
import mock
from django.conf import settings
from django.utils import timezone
from django.core.exceptions import ImproperlyConfigured
from funfactory.urlresolvers import reverse
from airmozilla.base.tests.testbase import Response
from airmo... | PETER_URL in url
data = json.loads(options['data'])
posts.append(data)
return Response(
'OK',
201
)
rpost.side_effect = mocked_post
event = Event.objects.get(title='Test event')
# also change to a non-public privac... | total_hits=100
)
event2 = Event.objects.create(
slug='something-else',
title=event.title,
status=event.status,
privacy=event.privacy,
start_time=event.start_time + datetime.timedelta(days=40),
description=event.description,
... |
Rensselaer-AI-League/GeneralizedGameServer | helpers/glicko2.py | Python | mit | 993 | 0.030211 | class Player:
self.rating = 1500 # Actual rating
self.rd = 350 # Rating deviation
self.sigma = 0.06 # Volatility
self.mu = None
self.phi = None
class | Glicko2:
self.tau = 1.0 # Should be betwee | n 0.3 and 1.2, use higher numbers for more predicatable games
def step2(self, player):
player.mu = (player.rating-1500)/173.7178
player.phi = player.sigma/173.7178
def g(phi):
return 1/math.sqrt(1 + 3*phi*phi/9.86960440109) # 9.869... is Pi squared
def E(mu, mu_j, phi_j):
return 1/(1 + math.exp(-1 * g(phi... |
gonzolino/heat | contrib/rackspace/rackspace/tests/test_rackspace_cloud_server.py | Python | apache-2.0 | 20,555 | 0 | #
# 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 law or agreed to in writing, software
# ... | f.m.StubOutWithMock(self.fc.servers, 'get')
self.fc.servers.get(return_server.id).MultipleTimes(
).AndReturn(return_server)
server = self._setup_test_server(return_server,
'test_rackconnect_failed')
server.context.roles = ['rack_connect']
... | nner(server.create)
exc = self.assertRaises(exception.ResourceFailure, create)
self.assertEqual('Error: resources.test_rackconnect_failed: '
'RackConnect automation FAILED',
six.text_type(exc))
def test_rackconnect_unprocessable(self):
retur... |
divmain/GitSavvy | tests/test_run_for_timeout.py | Python | mit | 689 | 0.002903 | from GitSav | vy.core.runtime import run_or_timeout
from unittesting import DeferrableTestCase
class TestRunForTimeout(DeferrableTestCase):
def testReturnsFunctionResult(self):
def main():
return "Ok"
self.assertEquals("Ok", run_or_timeout(main, timeout=1.0))
def te | stReraisesException(self):
def main():
1 / 0
self.assertRaises(ZeroDivisionError, lambda: run_or_timeout(main, timeout=1.0))
def testRaisesTimeoutIfFunctionTakesTooLong(self):
def main():
import time
time.sleep(0.1)
1 / 0
self.assert... |
josephsuh/extra-specs | nova/volume/san.py | Python | apache-2.0 | 32,648 | 0.000459 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 Justin Santa Barbara
# All Rights Reserved.
#
# 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.apach... | _export(self, context, volume):
"""Exports the volume."""
pass
def remove_export(self, context, volume):
"""Removes an export for a logical volume."""
pass
def check_for_setup_error(self):
"""Re | turns an error if prerequisites aren't met."""
if not self.run_local:
if not (FLAGS.san_password or FLAGS.san_private_key):
raise exception.NovaException(_('Specify san_password or '
'san_private_key'))
# The san_ip must always be set,... |
rohitranjan1991/home-assistant | homeassistant/components/mill/climate.py | Python | mit | 8,828 | 0.00068 | """Support for mill wifi-enabled home heaters."""
import mill
import voluptuous as vol
from homeassistant.components.climate import ClimateEntity
from homeassistant.components.climate.const import (
CURRENT_HVAC_HEAT,
CURRENT_HVAC_IDLE,
FAN_ON,
HVAC_MODE_HEAT,
HVAC_MODE_OFF,
SUPPORT_FAN_MODE,
... | ater = self.coordinator.data[self._id]
if hvac_mode == HVAC_MODE_HEAT:
await self.coordinator.mill_data_connection.heater_control(
self._id, power_status=1
)
await self.coordinator.async_request_refresh()
elif hvac_mo | de == HVAC_MODE_OFF and not heater.is_gen1:
await self.coordinator.mill_data_connection.heater_control(
self._id, power_status=0
)
await self.coordinator.async_request_refresh()
@property
def available(self) -> bool:
"""Return True if entity is availa... |
Team02-TeamGuinness/BIOE421_RoboHand | ablation-GUI/CONFIG/2015-January-31/05-24-55 PM C3-1-CONFIG.py | Python | gpl-2.0 | 582 | 0.06701 | #File
fname = 'C3-1.gcode'
f=open(fname,'w')
#Laser Parameters
laserPower = 20 #% max power
dwellTime = 25 #ms
x_start = 416
y_start = 343
z_start = 123.10 #mm above home
pauseTime = 500 #ms; time paused after movement before ablation
feedRate = 500 #movement speed
# Rectangle... | tWidth = 10 #mm; y-direction
spaceSmall = 3 #mm; space | between rectangles
hexLength = 0.700 #mm
#Other
relative = 0 #0 for homing before beginning. 1 if machine has already been homed |
Tim-Erwin/marshmallow-jsonapi | docs/conf.py | Python | mit | 1,125 | 0.000889 | # -*- coding: ut | f-8 -*-
from __future__ import unicode_literals
import datetime as dt
import os
import sys
sys.p | ath.insert(0, os.path.abspath('..'))
import marshmallow_jsonapi
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.intersphinx',
'sphinx.ext.viewcode',
'sphinx_issues',
]
primary_domain = 'py'
default_role = 'py:obj'
intersphinx_mapping = {
'python': ('http://python.readthedocs.org/en/latest/', Non... |
qevo/py_file_helper | file_helper/__init__.py | Python | mit | 243 | 0 | """File related wrapper functions to st | reamline common use cases"""
import manage as manage
from manage import find_file, find_file_re, list_dir
import operation as operation
from operation import hash_file, re | ad_file, slice_file, write_file
|
LLNL/spack | var/spack/repos/builtin/packages/perl-sub-identify/package.py | Python | lgpl-2.1 | 547 | 0.005484 | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Proje | ct Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class PerlSubIdentify(PerlPackage):
"""Retrieve names of code references"""
homepage = "https://metacpan.org/pod/Sub::Identify"
url = "http://search.cpan.org/CPAN/author... | 0ef6700039defad6f')
|
netscaler/neutron | neutron/tests/unit/openvswitch/test_agent_scheduler.py | Python | apache-2.0 | 59,767 | 0.00005 | # Copyright (c) 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 law or agreed to... | text=True):
path = "/routers/%s/%s.%s" % (router_id,
l3agentscheduler.L3_AGENTS,
self.fmt)
return self._request_list(path, expected_code=expected_code,
admin_contex | t=admin_context)
def _list_dhcp_agents_hosting_network(self, network_id,
expected_code=exc.HTTPOk.code,
admin_context=True):
path = "/networks/%s/%s.%s" % (network_id,
dhcpagentschedul... |
kralla/django-base | base/urls.py | Python | gpl-2.0 | 180 | 0.005556 | """urlconf for | the base application"""
from django.conf.urls import url, patterns
urlpatterns = pattern | s('base.views',
url(r'^$', 'home', name='home'),
)
|
nirgal/ngw | core/authbackend.py | Python | bsd-2-clause | 1,058 | 0 | from djan | go.contrib.auth.models import update_last_login
from django.contrib.auth.signals import user_logged_in
from ngw.core.models import Contact
# Ugly work around for NOT using update_last_login that is hardcoded in
# crontrib.auth :
user_logged_in.disconnect(update_last_login)
class NgwAuthBackend(object):
"""
... | e
def authenticate(self, request, username=None, password=None):
if not username or not password:
return None
try:
contact = Contact.objects.get_by_natural_key(username)
except (Contact.DoesNotExist, Contact.MultipleObjectsReturned):
return None
... |
jbedorf/tensorflow | tensorflow/compiler/tests/argminmax_test.py | Python | apache-2.0 | 3,905 | 0.002561 | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# 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 applica... | math_ops.argmax,
axis=0,
output_type=output_type,
op_input=np.array([[4, 1, 7], [3, 2, 4]], dtype=dtype),
expected=np.array([0, 1, 0], dtype=output_type))
| self._assertOpOutputMatchesExpected(
math_ops.argmax,
axis=1,
output_type=output_type,
op_input=np.array([[4, 1], [3, 2]], dtype=dtype),
expected=np.array([0, 0], dtype=output_type))
self._assertOpOutputMatchesExpected(
math_ops.argm... |
bretth/django-auth0user | auth0user/urls.py | Python | bsd-3-clause | 147 | 0 | from django. | conf.urls import url
from . import views
ap | p_name = 'auth0user'
urlpatterns = [
url(r'^alogin/', views.alogin, name='alogin'),
]
|
GitYiheng/reinforcement_learning_test | test00_previous_files/gym_test5.py | Python | mit | 47 | 0.021277 | from gym | import envs
print(envs.registry | .all()) |
pdbaines/KepleR | python/wavelets.py | Python | mit | 3,443 | 0.01278 |
import matplotlib.pyplot as plt
from matplotlib import cm
import pywt
import scipy
import numpy as np
import time
import random
import math
import sys
import kplr
import wavelet_funcs
data = np.loadtxt("KIC_7874976_llc.dat")
data.shape # (60020,4)
# From Montet:
# Columns are time, raw-flux, detrended-flux, uncertai... | #for i in range(0,len(fdwt)):
# fdwt_vec = np.append(fdwt_vec,fdwt[i])
#
#plt.plot(fdwt_vec)
#plt.show()
#
# cm.coolwarm
# cm.afmhot
#f_ret = wvanalyze(y,wtype='father',wavelet='haar',mode='zpd',cmap=cm.afmhot)
m_ret = wvanalyze(y,wtype='mother',wavelet='haar',mode='zpd',cmap=cm.afmhot)
assert 0
# Now, REAL Kepl... | xt")
len(data)
data = data - np.median(data)
data = data[0:512]
f_ret = wvanalyze(data,wtype='father',wavelet='haar',mode='zpd',cmap=cm.afmhot)
client = kplr.API()
planet = client.planet("62b")
do_fetch = False
if do_fetch:
all_datasets = []
ndatasets = 0
for dataset in planet.data:
print "F... |
zielmicha/satori | satori.web/satori/web/__init__.py | Python | mit | 616 | 0.001623 | # vim:ts=4:sts=4:sw=4:expandtab
import os
import satori.web.setup
def manage():
from django.core. | management import execute_manager
import satori.web.settings as settings
# HACK
import django.core.management
old_fmm = django.core.management.find_management_module
def find_management_module(app_name):
if app_name == 'satori.web':
return os.path.join(os.path.dirname(__file__... | HACK
execute_manager(settings)
|
lukegb/ehacktivities | eactivities/models/finances.py | Python | mit | 7,365 | 0.000815 | from . import Model, LazyModelMixin, LazyDictFromArrayModel, ArrayModel, Account, Amount, Images, PdfableModelMixin, NoneableModelMixin
from eactivities.parsers.finances import FinancesParser, BankingRecordsParser, SalesInvoicesParser, ClaimsParser, PurchaseOrdersParser, \
TransactionCorrectionsParser, InternalCh... | s
# Transfers #
def transaction_corrections(self):
return self._spawn(TransactionCorrections, TransactionCorrectionsParser)
def internal_charges(self):
return self._spawn(InternalCharges, InternalChargesParser)
def members_funds_redistributions(self):
return self._sp... | return self._spawn(FundingRedistributions, FundingRedistributionsParser)
# TODO: Designated Members Funds Transfers
def _spawn(self, model_cls, parser_cls):
return model_cls(
eactivities=self._eactivities,
parent=self,
data=dict(
club_id=self... |
abram777/torrents-from-xml | examples/geektool script/torrents.geektool.py | Python | mit | 449 | 0 | #!/usr/bin/env python
from sys import argv
from GeekToolKickassTorrentFeed import GeekToolKickassTorrentFeed
if __name__ == "__main__" and len(argv) > 1:
mode = argv[1]
print(str.format("{0}{1}", "\t" * 4, mod | e.capitalize()))
feed = GeekToolKickassTorrentFeed(mode)
if feed:
feed_data = feed.get_top_seeded_torrents().fetch().get_formatted_list()
print | (feed_data)
else:
print("No torrents available")
|
tcoxon/wiitar | midipy_src/test.py | Python | gpl-2.0 | 311 | 0.080386 |
import time
import midipy as midi
midi.open(128, 0, "midipy test", 0)
for (note, t) in [(48,0.5),(48,0.5),(50,1.0),(48,1.0),(53,1.0),(52,1.0),
(48,0.5),(48,0.5),(50,1.0),(48,1.0),(55,1.0),(53,1.0)]:
midi.note_on(note,127)
| time.sleep(t/2)
midi.n | ote_off(note,127)
midi.close()
|
sknepneklab/SAMoS | analysis/batch_nematic/batch_analyze_nematic_R8a.py | Python | gpl-3.0 | 2,379 | 0.045397 | # ################################################################
#
# Active Particles on Curved Spaces (APCS)
#
# Author: Silke Henkes
#
# ICSMB, Department of Physics
# University of Aberdeen
# Author: Rastko Sknepnek
#
# Division of Physics
# School of Engineering, Physics and Mathem... | s),12))
ndefect=np.zeros((len(files),1))
u=0
for f in files:
print f
outname =outfolder +'R_'+ r+ '/v0_' + v0 + '/frame_data' + str(u)+'.vtk'
defects0,ndefect0=getDefects(f,float(r),sigma,outname,False,False)
defects[u,0:3]=defects0[0,:]
defects[u,3:6]=defects0[1,:]
defects[u,6:9]=defects0[2,:]
... | ndefect[u]=ndefect0
#outname = '.'.join((f).split('.')[:-1]) + '_defects.vtk'
#outname =outfolder +'R_'+ r+ '/v0_' + v0 + '/frame_defects' + str(u)+'.vtk'
#print outname
#writeDefects(defects0,ndefect0,outname)
u+=1
outfile2=outfolder + 'defects_v0_' + v0 + '_R_'+ r+ '.dat'
np.savetxt... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.