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 |
|---|---|---|---|---|---|---|---|---|
albertoconnor/website | newsletter/migrations/0001_initial.py | Python | mit | 2,249 | 0.003557 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import django.db.models.deletion
import modelcluster.fields
import wagtail.wagtailcore.fields
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('wagtailcore', '00 | 01_squashed_0016_change_page_url_path_to_text_field'),
('articles', '0024_auto_20150722_1928'),
('images', '0001_in | itial'),
]
operations = [
migrations.CreateModel(
name='NewsletterArticleLink',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('sort_order', models.IntegerField(null=True, editable=Fals... |
maartenq/ansible | test/units/modules/network/f5/test_bigip_profile_http_compression.py | Python | gpl-3.0 | 4,310 | 0.001856 | # -*- coding: utf-8 -*-
#
# Copyright: (c) 2018, F5 Networks Inc.
# GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
import json
import pytest
import sys
from nose.plugins.skip i... | gzip_memory_level=64,
| gzip_level=2,
gzip_window_size=128
)
p = ModuleParameters(params=args)
assert p.name == 'foo'
assert p.parent == '/Common/bar'
assert p.description == 'description1'
assert p.buffer_size == 1024
assert p.gzip_memory_level == 64
assert p... |
xahhy/Django-vod | vodmanagement/apps.py | Python | lgpl-3.0 | 125 | 0 | from django.apps import AppConfig
class VodConfig(AppConfig):
name = 'vodmanagement'
verbose_name = '视频点播' | ||
stvstnfrd/edx-platform | common/test/acceptance/tests/lms/test_account_settings.py | Python | agpl-3.0 | 2,482 | 0.001612 | # -*- coding: utf-8 -*-
"""
End-to-end tests for the Account Settings page.
"""
from common.test.acceptance.pages.common.auto_auth import AutoAuthPage
from common.test.acceptance.pages.lms.account_settings import AccountSettingsPage
from common.test.acceptance.tests.helpers import AcceptanceTest, EventsTestMixin
cl... | of the account settings page.
"""
self.log_in_as_unique_user()
self.visit_account_settings_page()
self.account_settings_page.a11y_audit.config.set_rules({
"ignore": [
'aria-valid-attr', # TODO: LEARNER-6611 & LEARNER-6865
'region', # TODO: A... | ors()
|
goodes/fit4school | fit4school/urls.py | Python | apache-2.0 | 677 | 0.001477 | from django.conf.urls import url, include
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.utils.translation import ugettext_lazy as _
urlpatterns = [
url(r'^i18n/', include('django.conf.urls.i18n')),
| url(r'^fitbit_api/', include('fit4school.fitbit_api.urls')),
url(r'^control/django-rq/', include('django_rq.urls')),
url(r'^control/', include('fit4school.control.urls')),
url(r'^station/', include('fit4school.station.urls')),
url(r'', ... | + staticfiles_urlpatterns()
|
digitalocean/netbox | netbox/tenancy/tests/test_filters.py | Python | apache-2.0 | 3,818 | 0.001833 | from django.test import TestCase
from tenancy.filters import *
from tenancy.models import Tenant, TenantGroup
class TenantGroupTestCase(TestCase):
queryset = TenantGroup.objects.all()
filterset = TenantGroupFilterSet
@classmethod
def setUpTestData(cls):
parent_tenant_groups = (
... | nant-1', 'tenant-2']}
self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)
def test_group(self):
group = TenantGroup.objects.all()[:2]
params = {'group_id': [group[0].pk, group[1].pk]}
se | lf.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)
params = {'group': [group[0].slug, group[1].slug]}
self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)
|
openstack/nova | nova/tests/unit/api/openstack/compute/test_limits.py | Python | apache-2.0 | 24,448 | 0.000286 | # Copyright 2011 OpenStack Foundation
# 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 requ... |
stub_get_project_quotas)
res = request.get_response(self.controller)
body = jsonutils.loads(res.body)
| abs_limits = body['limits']['absolute']
for limit in expected_abs_limits:
value = abs_limits[limit]
r = limits[quota_map[limit]]['reserved'] if reserved else 0
self.assertEqual(limits[quota_map[limit]]['in_use'] + r, value)
def test_used_limits_basic(self):
sel... |
tumbislav/SvgMapper | src/main.py | Python | gpl-3.0 | 2,923 | 0.002396 | # encoding: utf-8
# main.py, copyright 2014 by Marko Čibej <[email protected]>
#
# This file is part of SvgMapper. Full sources and documentation
# are available here: https://github.com/tumbislav/SvgMapper
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General P... |
parser.add_argument('-s', '--simulate', help='Don\'t actually do anything, just parse all the configurations',
ac | tion='store_true')
return parser.parse_args()
def set_logging(the_log, verbosity):
log_levels = [logging.ERROR, logging.WARNING, logging.INFO, logging.DEBUG]
logger.setLevel(logging.DEBUG)
if the_log:
level = log_levels[int(the_log[0])]
lf = logging.FileHandler(the_log[1], mode='w')
... |
Pica4x6/megaradrp | megaradrp/tests/test_products.py | Python | gpl-3.0 | 2,054 | 0.011685 | #
# Copyright 2015 Universidad Complutense de Madrid
#
# This file is part of Megara DRP
#
# Megara DRP 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) an... | P. If not, see <http://www.gnu.org/licenses/>.
#
from megaradrp.products import TraceMap
from tempfile import NamedTemporaryFile
import pytest
import yaml
@pytest.mark.xfail
def test_fail_traceMap(benchmark=None):
my_obj = TraceMap()
my_obj._datatype_load('')
def test_load_traceMap(benchmark=None):
data... | TraceMap()
my_file = NamedTemporaryFile()
with open(my_file.name, 'w') as fd:
yaml.dump(data, fd)
my_open_file = my_obj._datatype_load(my_file.name)
assert (my_open_file == {'A': 'a', 'B': {'C': 'c', 'E': 'e', 'D': 'd'}})
def test_dump_traceMap(benchmark=None):
class aux(object):
... |
lachaka/traffic_sign_recognition | datasets/neg_images/img_gen.py | Python | mit | 644 | 0.021739 | import cv2
import os
import skimage.io
output_dir = '../training_images/Final_Training/Images/00043/'
images_path = './samples/'
if not os.path.exists | (output_dir):
os.makedirs(output_dir)
name = 0;
img_names = [f for f in os.listdir(images_path)
if f.endswith(".ppm")]
for img_name in img_names:
img = cv2.imread(images_path + img_name)
h, w, channel = skimage.io.imread(images_path + img_name).shape
for i in range(0, w - 128, 128):
for j in range(0, h ... |
cv2.imwrite(img_full_path, crop_img)
name += 1
|
ashishtanwer/DFS | reader.py | Python | gpl-2.0 | 600 | 0.011667 | #!/usr/bin/python
import re
fi = open("tree8", "r")
fo = open("tree8.dot", "wb")
fo.write("graph test {\n")
fo.write("\nflowexport=text\n")
line = fi.readline()
line = fi.readline()
line = fi.readline()
while line!= 0:
RouterList = re.sub("[^\w]", " ", line).split()
fo.write('%s[\n\tautoack ... | .0/16"\n];\n' % RouterList[0])
fo.write('%s[\n\tautoack = "False"\n\tipdests = "10.0.0.0/16"\n];\n' % RouterList[1])
fo | .write('\t%s -- %s[weight = 1, capacity = 100000000, delay = 0.001];\n'%(RouterList[0],RouterList[1]))
fo.write("}")
|
glogiotatidis/mozillians-new | mozillians/users/helpers.py | Python | bsd-3-clause | 1,366 | 0.000732 | import base64
import hashlib
import re
def validate_username(username):
"""Validate username.
Import modules here to prevent dependenc | y breaking.
"""
from models import UsernameBlacklist
username = username.lower()
if (UsernameBlacklist.
objects.filter(value=username, is_regex=False).exists()):
return False
for regex_value in UsernameBlacklist.objects.filter(is_regex=True):
if re.match(regex_value.value,... | return True
def calculate_username(email):
"""Calculate username from email address.
Import modules here to prevent dependency breaking.
"""
from models import USERNAME_MAX_LENGTH
from django.contrib.auth.models import User
email = email.split('@')[0]
username = re.sub(r'[^\w.@+-]', '... |
quamis/ExchangeRate | ExchangeRate/ExchangeRate/spiders/Raiffeisen.py | Python | gpl-2.0 | 1,581 | 0.025933 | from scrapy.spider import BaseSpider
from scrapy.selector import Selector
from ExchangeRate.items import ExchangerateItem
import re
class RaiffeisenSpider(BaseSpider):
name = "Raiffeisen"
allowed_domains = ["www.raiffeisen.ro"]
start_urls = [
"http://www.raiffeisen.ro/curs-valutar",
]
def parse(sel... | item['EUR_buy'] = float(hxs.xpath('//div[@class="rzbContentTextNormal"]//table//td[contains(text(), "EUR")]/../td[4]/text()').extract()[0])
item['EUR_sell'] = float(hxs.xpath('//div[@class="rzbContentTextNormal"]//table//td[contains(text(), "EUR")]/../td[5]/text()').e | xtract()[0])
item['USD_buy'] = float(hxs.xpath('//div[@class="rzbContentTextNormal"]//table//td[contains(text(), "USD")]/../td[4]/text()').extract()[0])
item['USD_sell'] = float(hxs.xpath('//div[@class="rzbContentTextNormal"]//table//td[contains(text(), "USD")]/../td[5]/text()').extract()[0])
item['GB... |
alexhayes/django-google-adwords | django_google_adwords/south_migrations/0003_auto__add_field_ad_ad_approval_status.py | Python | mit | 31,311 | 0.006739 | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Ad.ad_approval_status'
db.add_column(u'django_google_adwo... | , [], {'primary_key': 'True'}),
'status': ('django.db.models.fields.CharField', [], {'default': "'active'", 'max_length': '32'}),
'updated': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'auto_now_add': 'True', 'blank': 'True'})
},
u'django_google_adwords.ad'... | b.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'ad_approval_status': ('django.db.models.fields.CharField', [], {'max_length': '20', 'null': 'True', 'blank': 'True'}),
'ad_group': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'ads'", 'to': u"orm['django... |
AdrienVR/ALT | QCM.py | Python | lgpl-3.0 | 2,961 | 0.044917 | #!/usr/bin/python
# -*- coding: utf-8 -*-
from os import getcwd, listdir, path
from PyQt4.QtCore import SIGNAL
from Question import *
from State import State
class QCM():
# Constructeur
def __init__(self):
self.qcm={}
self.charger()
def charger(self):
curr=getcwd()
for x in listdir(curr+"/qc... |
q.question=q.question[:fi]+"\n"+q.question[fi:]
didi[i]=q
return didi
###############
## GETTERS
###############
def getKeyfromInt(self,nb):
i=self.qcm.k | eys();i.sort()
return i[nb]
def getListfromKey(self,key):
return self.qcm[key].keys()
def getChapter(self,x,y):
return self.qcm[x][y]
|
mworks/mworks | examples/Tests/Stimulus/PythonImage/image_gen.py | Python | mit | 1,385 | 0.000722 | import gzip
import math
import numpy as np
class Renderer:
def reset(self):
self.fmt = getvar('pixel_buffer_format')
self.width = int(getvar('pixel_buffer_width'))
self.height = int(getvar('pixel_buffer_height'))
self.period = getvar('period')
with gzip.open('background.... | * pos), round(self.width * pos | )),
(0, 1))
r = Renderer()
reset = r.reset
render = r.render
del r
|
J2897/WinSCP_Updater | Update_WinSCP.py | Python | gpl-3.0 | 4,220 | 0.030095 | # Released under the GNU General Public License version 3 by J2897.
def get_page(page):
import urllib2
source = urllib2.urlopen(page)
return source.read()
title = 'WinSCP Updater'
target = 'Downloading WinSCP'
url = 'http://winscp.net/eng/download.php'
print 'Running: ' + title
print 'Target: ' + target
print ... | g_box('Failed to download ' + FN + ' to ' + tmp + '.', 0)
stop()
else:
print 'Downloaded: ' + FN
try:
RC = sub_proc(command)
except:
RC = None
if RC == None:
msg_box('Failed to execute ' + FN + '.', 0)
stop()
elif RC == 0:
msg_box('Successfully updated to version ' + site_ver | sion + '.', 0)
stop()
else:
msg_box('Successfully spawned new process for ' + FN + '. But the installation appears to have failed.', 0)
stop()
# Check if the WinSCP.exe file exists...
if not os.path.isfile(WinSCP_exe):
# No: Download and install WinSCP, and quit.
print 'WinSCP.exe file doesn\'t exist.'
print... |
JiscPER/jper-oaipmh | setup.py | Python | apache-2.0 | 610 | 0.029508 | from setuptools import setup, find_packages
setup(
name = 'jper-oaipmh',
versio | n = '1.0.0',
packages = find_packages(),
install_requires = [
"octopus==1.0.0",
"esprit",
"Flask"
],
url = 'http://cottagelabs.com/',
author = 'Cottage Labs',
author_email = '[email protected]',
description = 'OAI-PMH endpoint for JPER',
classifiers = [
'... | tware Development :: Libraries :: Python Modules'
],
)
|
TeamUACS1/410Project | tests/testResponse.py | Python | apache-2.0 | 1,144 | 0.012238 | # r | un python freetests.py while server is running
import urllib2
import unittest
BASEURL = "http://cmput410project15.herokuapp.com"
class TestYourWebserver(unittest.TestCase):
"""
Tests some the responses from the server with urllib2
"""
def setUp(self,baseurl=BASEURL):
self.baseurl = baseurl
... | "
req = urllib2.urlopen(url, None, 3)
self.assertTrue( req.getcode() == 200 , "200 OK Not FOUND!")
def test_get_404(self):
"""This tests for a 404 error for a page that dosent exist"""
url = self.baseurl + "/do-not-implement-this-page-it-is-not-found"
try:
req =... |
lidavidm/mathics-heroku | venv/lib/python2.7/site-packages/sympy/core/tests/test_subs.py | Python | gpl-3.0 | 18,518 | 0.00054 | from sympy import (Symbol, Wild, sin, cos, exp, sqrt, pi, Function, Derivative,
abc, Integer, Eq, symbols, Add, I, Float, log, Rational, Lambda, atan2,
cse, cot, tan, S, Tuple, Basic, Dict, Piecewise, oo, Mul)
from sympy.core.basic import _aresame
from sympy.utilities.pytest import XFAIL
from sympy.abc ... | assert (y*exp(3*x/2)).subs(y*exp(x), 2) == 2*exp(x/2)
assert (y*exp(3*x/2)).subs(y*exp(x), 2) == 2*exp(x/2)
assert (A**2*B*A**2*B*A**2).subs(A*B*A, C) == A*C**2*A
assert (x*A**3).subs(x*A, y) == y*A**2
assert (x**2*A**3).subs(x*A, y) == y**2*A
assert (x*A**3).subs(x*A, B) == B*A**2
assert (x... | x*B*exp(B**2)*B*exp(B**2)
assert (x*A*B*C*A*B).subs(x*A*B, C) == C**2*A*B
assert (-I*a*b).subs(a*b, 2) == -2*I
# issue 3262
assert (-8*I*a).subs(-2*a, 1) == 4*I
assert (-I*a).subs(-a, 1) == I
# issue 3342
assert (4*x**2).subs(2*x, y) == y**2
assert (2*4*x**2).subs(2*x, y) == 2*y**2
... |
jdwittenauer/ionyx | tests/averaging_regressor_test.py | Python | apache-2.0 | 1,583 | 0.00379 | import pprint as pp
import p | andas as pd
from sklearn.linear_model import Ridge, Lasso
from sklearn.metrics import mean_absolute_error
from sklearn.model_selection import GridSearchCV, KFold, cross_val_score
from sklearn.svm import LinearSVR
from ionyx.contrib import AveragingRegressor
from ionyx.datasets import DataSetLoader
print('Beginning ave... | estimators = [('ridge', Ridge()), ('lasso', Lasso()), ('svm', LinearSVR())]
ensemble = AveragingRegressor(estimators, weights=[1.0, 1.5, 2.0])
ensemble.fit(X, y)
print('Estimators list:')
pp.pprint(ensemble.estimators_)
print('Named estimators dict:')
pp.pprint(ensemble.named_estimators_)
print('Model 1 score = {0}'.fo... |
girishramnani/pyappbase | tests/test_async.py | Python | mit | 3,468 | 0.00346 | import asyncio
import time
import unittest
from test_sync import setup
from pyappbase import Appbase
async def hello_world(d, data):
while d[0]:
await asyncio.sleep(0.1)
data.append("Hello")
class AsnycTests(unittest.TestCase):
def setUp(self):
self.data = {
"type": "B... | print()
# the async is more fast
self.assertGreater(sync_difference, async_difference)
def test_async_two_methods(self):
"""
simple asynchronously running ping with an async hello_world coroutine
:return:
"""
# some thing multable
wait = [T... | wait[0] = False
async def temp():
await asyncio.sleep(1)
asyncio.get_event_loop().run_until_complete(temp())
print(results)
self.assertNotEquals(len(data), 0)
def test_async_get(self):
async def get_data():
return await self.appbase.get(self... |
tvgdb/pianissimo | backend/endpoints/library_clean_index_endpoint.py | Python | gpl-3.0 | 1,056 | 0.001894 | from flask import current_app as app, request
from flask.ext.restful import Resource, abort
from tasks import library_tasks
from util import inject_user
class LibraryCleanIndexEndpoint(Resource):
@inject_user
def get(self):
task_id = request.args.get('task_id')
if not task_id:
abo... | total"])
return resp | onse
@inject_user
def post(self):
task = library_tasks.clean_library.delay()
return {"task_id": task.id}
|
Ryuno-Ki/BloGTK3 | share/blogtk2/lib/blogtk2/main.py | Python | apache-2.0 | 26,085 | 0.028944 | #!/usr/bin/python
# Copyright 2009 Jay Reding
# 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 ... | tleColumn = gtk.TreeViewColumn("Post Title", gtk.CellRendererText(), t | ext=1)
self.postTitleColumn.set_resizable(True)
self.postDateColumn = gtk.TreeViewColumn("Post Date", renderer2, text=2)
self.tvPosts.append_column(self.postIdColumn)
self.tvPosts.append_column(self.postTitleColumn)
self.tvPosts.append_column(self.postDateColumn)
# Now it's be a Calvinist and predestinate ... |
minervaproject/django-db-mutex | settings.py | Python | mit | 1,916 | 0.000522 | import os
from django.conf import settings
def configure_settings():
"""
Configures settings for manage.py and for run_tests.py.
"""
if not settings.configured:
# Determine the database settings depending on if a test_db var is set in CI mode or not
test_db = os.environ.get('DB', None... |
}
elif test_db == 'postgres':
db_config = {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'USER': | 'postgres',
'NAME': 'db_mutex',
}
elif test_db == 'sqlite':
db_config = {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'db_mutex',
}
else:
raise RuntimeError('Unsupported test DB {0}'.format(test_db))
... |
lluxury/P_U_S_A | 4_documentation/code/authentication_email.py | Python | mit | 647 | 0.006299 | #!/usr/bin/env python
import | smtplib
mail_server = 'smtp.example.com'
mail_server_port = 465
from_addr = '[email protected]'
to_addr = '[email protected]'
from_header = 'From: %s\r\n' % from_addr
to_header = 'To: %s\r\n\r\n' % to_addr
subject_header = 'Subject: Testing SMTP Authentication'
body = 'This mail tests SMTP Authentication'
email_message... | r_port)
s.set_debuglevel(1)
s.starttls()
s.login("fatalbert", "mysecretpassword")
s.sendmail(from_addr, to_addr, email_message)
s.quit()
#set_debuglevel 日志级别
#starttls 启动ssl |
ljschumacher/tierpsy-tracker | tierpsy/analysis/wcon_export/exportWCON.py | Python | mit | 9,522 | 0.014073 | # -*- coding: utf-8 -*-
"""
Created on Mon Aug 15 20:55:19 2016
@author: ajaver
"""
import json
import os
from collections import OrderedDict
import zipfile
import numpy as np
import pandas as pd
import tables
from tierpsy.helper.misc import print_flush
from tierpsy.analysis.feat_create.obtainFeaturesHelper import ... | me
fps = read_fps(features_file)
#get pointers to some usefu | l data
skeletons = fid.get_node('/coordinates/skeletons')
dorsal_contours = fid.get_node('/coordinates/dorsal_contours')
ventral_contours = fid.get_node('/coordinates/ventral_contours')
#let's append the data of each individual worm as a element in... |
hydroffice/hyo_soundspeed | hyo2/soundspeed/formats/readers/simrad.py | Python | lgpl-2.1 | 8,879 | 0.003379 | import logging
import re
import numpy
logger = logging.getLogger(__name__)
from hyo2.soundspeed.formats.readers.abstract import AbstractTextReader
from hyo2.soundspeed.profile.dicts import Dicts
from hyo2.soundspeed.base.callbacks.cli_callbacks import CliCallbacks
from hyo2.soundspeed.temp import coordinates
from h... | (?P<lon>[\d.]+,[EW]),
''', self.lines[-1], re.VERBOSE) # try at the end of file
if m:
location = coordinates.Coordinate(m.group('lat'), m.group('lon'))
meta.update(Profile.getMetaFromCoord(location))
meta['filename'] = self.fid._p... | $ item 1
' Talker ID AA
' Datagram ID, S10,
' Data Set ID, xxxxx, item 2
' Number of measurements, xxxx, item 3
... |
thedrow/invoke | invoke/parser/context.py | Python | bsd-2-clause | 7,616 | 0.000919 | from ..vendor.lexicon import Lexicon
from .argument import Argument
def to_flag(name):
name = name.replace('_', '-')
if len(name) == 1:
return '-' + name
return '--' + name
def sort_candidate(arg):
names = arg.names
# TODO: is there no "split into two buckets on predicate" builtin?
s... | nverse_name] = to_flag(main)
@property
def needs_positional_arg(se | lf):
return any(x.value is None for x in self.positional_args)
def help_for(self, flag):
"""
Return 2-tuple of ``(flag-spec, help-string)`` for given ``flag``.
"""
# Obtain arg obj
if flag not in self.flags:
raise ValueError("%r is not a valid flag for th... |
madelynfreed/rlundo | venv/lib/python2.7/site-packages/IPython/html/services/contents/filecheckpoints.py | Python | gpl-3.0 | 6,869 | 0 | """
File-based Checkpoints implementations.
"""
import os
import shutil
from tornado.web import HTTPError
from .checkpoints import (
Checkpoints,
GenericCheckpointsMixin,
)
from .fileio import FileManagerMixin
from IPython.utils import tz
from IPython.utils.path import ensure_dir_exists
from IPython.utils.py... | ault(self):
try:
return self.parent.root_dir
except AttributeError | :
return getcwd()
# ContentsManager-dependent checkpoint API
def create_checkpoint(self, contents_mgr, path):
"""Create a checkpoint."""
checkpoint_id = u'checkpoint'
src_path = contents_mgr._get_os_path(path)
dest_path = self.checkpoint_path(checkpoint_id, path)
... |
art-solopov/mdwiki | common/admin.py | Python | mit | 369 | 0.01626 | from django.contrib i | mport admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib.auth.models import User
class UserAdmin(BaseUserAdmin):
list_display = ('username', 'email',
'first_name', 'last_name',
'is_staff', 'is_active' | ,
)
admin.site.unregister(User)
admin.site.register(User, UserAdmin)
|
agile-geoscience/striplog | striplog/legend.py | Python | apache-2.0 | 30,661 | 0.000457 | """
Defines a legend for displaying components.
:copyright: 2015 Agile Geoscience
:license: Apache 2.0
"""
# from builtins import object
from io import StringIO
import csv
import warnings
import random
import re
import itertools
try:
from functools import partialmethod
except: # Python 2
from utils import pa... | tplotlib import patches
import matplotlib.p | yplot as plt
from .component import Component
from . import utils
from .defaults import LEGEND__NSDOE
from .defaults import LEGEND__Canstrat
from .defaults import LEGEND__NAGMDM__6_2
from .defaults import LEGEND__NAGMDM__6_1
from .defaults import LEGEND__NAGMDM__4_3
from .defaults import LEGEND__SGMC
from .defaults im... |
Mangopay/mangopay2-python-sdk | tests/test_bankaccounts.py | Python | mit | 18,848 | 0.001061 | # -*- coding: utf-8 -*-
from mangopay.utils import Address
from tests import settings
from tests.resources import BankAccount
from tests.test_base import BaseTest, BaseTestLive
from datetime import date
import responses
import time
class BankAccountsTest(BaseTest):
@responses.activate
def test_create_bankac... |
"OwnerName": "Victor Hugo",
"OwnerAddress": {
"AddressLine1": "AddressLine1",
"AddressLine2": "AddressLine2",
"City": "City",
"Region": "Region",
"PostalCode": "11222",
... | 36016",
"SortCode": "404865",
"Id": "38290008",
"Tag": "custom tag",
"CreationDate": 1383561267
},
'status': 200
})
params = {
"tag": "custom tag",
"user": self.natural_user,
"typ... |
ef-ctx/tornwamp | tornwamp/session.py | Python | apache-2.0 | 5,335 | 0.000937 | """
Abstract websocket connections (dual channel between clients and server).
"""
import socket
import errno
from datetime import datetime
from tornwamp import topic
from tornwamp.identifier import create_global_id
class ConnectionDict(dict):
"""
Connections manager.
"""
@property
def dict(self... | for _, connection in self.items():
if getattr(connection, attr_name) == attr_value:
items.append(connection)
return items
connections = ConnectionDict()
class ClientConnection(object):
"""
Represent a client connection.
"""
existing_ids = []
def __init__(... | ocket (tornado.websocket.WebSocketHandler instance
- details: dictionary of metadata associated to the connection
"""
self.id = create_global_id()
# set connection attributes, if any is given
for name, value in details.items():
setattr(self, name, value)
# m... |
jacebrowning/gdm | tests/test_cli.py | Python | mit | 1,452 | 0.000689 | # pylint: disable=unused-variable,redefined-outer-name,expression-not-assigned
import os
from unittest.mock import call, patch
import pytest
from expecter import expect
from gitman import cli
@pytest.fixture
def config(tmpdir):
tmpdir.chdir()
path = str(tmpdir.join("gdm.yml"))
open(path, 'w').close()
... | _calls) == [call(config), call().__bool__()]
def it_exits_when_no_config_found(tmpdir):
tmpdir.chdir()
with | expect.raises(SystemExit):
cli.main(['edit'])
|
esthermm/odoo-addons | mrp_routing_cost/models/mrp_workcenter.py | Python | agpl-3.0 | 6,237 | 0.00016 | # -*- coding: utf-8 -*-
# © 2016 Oihane Crucelaegui - AvanzOSC
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
from openerp import api, fields, models
from openerp.addons import decimal_precision as dp
class MrpProductionWorkcenterLine(models.Model):
_inherit = 'mrp.production.workcenter.line'
... | e subtotal
subtotal = sum(
mrp.mapped('workcenter_lines.subtotal_hour'))
mrp.routing_hour_total =\
subtotal / mrp.product_qty if by_unit else subtotal
subtotal = sum(
mrp.mapped('workcenter_lines.subtotal_operator'))
mrp.rou... | .routing_hour_total + \
mrp.routing_operator_total
@api.multi
def _compute_production_total(self):
by_unit = self.env['mrp.config.settings']._get_parameter(
'subtotal.by.unit')
for prod in self:
total = prod.routing_total
try:
... |
joonamo/photoplaces | photoplaces/photoplaces_web/migrations/0004_auto_20141105_1236.py | Python | mit | 984 | 0.001016 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('photoplaces_web', '0003_photocluster_normalized_centers_dirty'),
]
operations = [
migrations.AddField(
model_nam... |
),
migrations.AddField(
model_name='normalizedphotoset',
name='month_mean_natural',
field=model | s.FloatField(null=True, blank=True),
preserve_default=True,
),
migrations.AddField(
model_name='photocluster',
name='normalized_set',
field=models.OneToOneField(related_name='+', null=True, blank=True, to='photoplaces_web.NormalizedPhotoSet'),
... |
qbuat/rootpy | rootpy/extern/byteplay.py | Python | gpl-3.0 | 33,903 | 0.004808 | # byteplay - Python bytecode assembler/disassembler.
# Copyright (C) 2006-2010 Noam Yorav-Raphael
# Homepage: http://code.google.com/p/byteplay
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Found... | _NAME = 1,1
LIST_APPEND = 2,0
elif python_version == '2.5':
YIELD_VALUE = 1,1
IMPORT_NAME = 2,1
LIST_APPEND = 2,0
elif python_version == '2.6':
YIELD_VALUE = 1,1
IMPORT_NAME = 2,1
LIST_APPEND = 2,0
elif python_version == '2.7':
YIELD_VALUE = 1,1
IMPORT_N... | p in opcodes
if hasattr(_se, opname[op]))
hasflow = opcodes - set(_se) - \
set([CALL_FUNCTION, CALL_FUNCTION_VAR, CALL_FUNCTION_KW,
CALL_FUNCTION_VAR_KW, BUILD_TUPLE, BUILD_LIST,
UNPACK_SEQUENCE, BUILD_SLICE, DUP_TOPX,
RAISE_VARARGS, MAKE_FUNCTION, MAKE... |
antoinecarme/pyaf | tests/model_control/detailed/transf_RelativeDifference/model_control_one_enabled_RelativeDifference_PolyTrend_Seasonal_DayOfWeek_NoAR.py | Python | bsd-3-clause | 171 | 0.046784 | import tests.model_contr | ol.test_ozone_custom_models_enabled as testmod
testmod.build_model( ['RelativeDifference'] , ['PolyTrend'] , ['Seasonal_DayOfWeek'] , ['No | AR'] ); |
d0ugal-archive/django-formadmin | tests/test_formadmin/admin.py | Python | mit | 375 | 0.002667 | from formadmin.admin import FormAdmin
from formadmin import sites
from test_formadmin.forms import EmailForm, UploadForm
class EmailFormAdmin(FormAdmin):
app_label = "AdminForms | "
verbose_name = "Email Staff"
class UploadFormAdmin(FormAdmi | n):
verbose_name = "Upload Logo"
sites.register(EmailForm, EmailFormAdmin)
sites.register(UploadForm, UploadFormAdmin)
|
WebCampZg/conference-web | people/migrations/0001_initial.py | Python | bsd-3-clause | 2,302 | 0.005213 | # -*- coding: utf-8 -*-
from django.db import models, migrations
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('auth', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='User',
fields=[
('id', ... | ),
('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')),
('groups', models.ManyToManyField(related_query_name='user', related_name='user_set', to='auth.Group', blank=True, | help_text='The groups this user belongs to. A user will get all permissions granted to each of his/her group.', verbose_name='groups')),
('user_permissions', models.ManyToManyField(related_query_name='user', related_name='user_set', to='auth.Permission', blank=True, help_text='Specific permissions for ... |
tjfontaine/linode-python | linode/api.py | Python | mit | 40,693 | 0.007028 | #!/usr/bin/python
# vim:ts=2:sw=2:expandtab
"""
A Python library to perform low-level Linode API functions.
Copyright (c) 2010 Timothy J Fontaine <[email protected]>
Copyright (c) 2010 Josh Wright <[email protected]>
Copyright (c) 2010 Ryan Tucker <[email protected]>
Copyright (c) 2008 James C Sinclair <james@irg... | iled
31: Credit card is expired
40: | Limit of Linodes added per hour reached
41: Linode must have no disks before delete
"""
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
def __reduce__(self):
return (self.__class__, (self.value, ))
class ApiInfo:
valid_commands = {}
valid_params =... |
ewdurbin/pymemcache | pymemcache/client/base.py | Python | apache-2.0 | 39,766 | 0 | # Copyright 2012 Pinterest.com
#
# 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,... | ode-block:: python
def serialize_json(key, value):
if type(value) == st | r:
return value, 1
return json.dumps(value), 2
def deserialize_json(key, value, flags):
if flags == 1:
return value
if flags == 2:
return json.loads(value)
raise Exception("Unknown flags for value: {1}".fo... |
ua-snap/downscale | old/old_bin/convert_tas_hur_to_vap.py | Python | mit | 2,809 | 0.050196 | # script to convert the newly generated Relative Humidity
def convert_to_hur( tas_arr, vap_arr ):
import numpy as np
with np.errstate( over='ignore' ):
esa_arr = 6.112 * np.exp( 17.62 * tas_arr/ (243.12 + tas_arr) )
# esa_arr = 6.112 * np.exp( 22.46 * tas_arr / (272.62 + tas_arr) )
return vap_arr/esa_arr * 100... | _Inputs/project_data/TEM_Data/cru_november_final/ar5'
hur_input_path = '/Dat | a/malindgren/cru_november_final/ar5'
models = [ 'IPSL-CM5A-LR', 'GISS-E2-R', 'MRI-CGCM3', 'CCSM4', 'GFDL-CM3' ]
for model in models:
print model
tas_files = sorted( glob.glob( os.path.join( tas_input_path, model, 'tas', 'downscaled', '*.tif' ) ) )
hur_files = sorted( glob.glob( os.path.join( hur_input_path, m... |
robernom/ptavi-pfinal | proxy_registrar.py | Python | gpl-2.0 | 9,377 | 0.000107 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
"""Programa que actua como proxy-registrar en UDP."""
import socketserver
import socket
import sys
import json
import hashlib as HL
from xml.sax import make_parser
from xml.sax.handler import ContentHandler
from time import time, gmtime, strftime
from random import choice, ran... | f ack(self, data):
"""Metodo ACK."""
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
d | est = data.split()[1][4:]
(ip_port) = (self.user_data[dest]['addr'],
int(self.user_data[dest]['port']))
sock.connect(ip_port)
text = add_header(data)
sock.send(bytes(text, 'utf-8'))
try:
recv = sock.recv(1024).decode('u... |
fisle/django-haystack | test_haystack/simple_tests/test_simple_backend.py | Python | bsd-3-clause | 7,001 | 0.002716 | # coding: utf-8
from __future__ import absolute_import, division, print_function, unicode_literals
from datetime import date
from django.conf import settings
from django.test import TestCase
from django.test.utils import override_settings
from haystack import connection_router, connections, indexes
from haystack.que... | results']], [2, 3, 15, 16, 17, 18])
self.assertEqual(self.backend.search(u'index document')['results'][0].model, MockModel)
# No support for spelling suggestions
self.assertEqual(self.backend.search(u'Indx')['hits'], 0)
self.assertFalse(self.backend.search(u'Indx').get('spelling_suggest... | sertEqual(self.backend.search(u'', facets=['name']), {'hits': 0, 'results': []})
self.assertEqual(self.backend.search(u'daniel', facets=['name'])['hits'], 23)
self.assertEqual(self.backend.search(u'', date_facets={'pub_date': {'start_date': date(2008, 2, 26), 'end_date': date(2008, 2, 26), 'gap': '/MONT... |
Unofficial-Extend-Project-Mirror/openfoam-extend-Breeder-other-scripting-PyFoam | unittests/Applications/test_CommonPlotLines.py | Python | gpl-2.0 | 112 | 0.008929 | import uni | ttest
from PyFoam.Applications.CommonPlotLines import CommonPlotLines
theSuite=un | ittest.TestSuite()
|
zibneuro/brainvispy | IO/vtkio.py | Python | bsd-3-clause | 1,198 | 0.010017 | import vtk
import os
import os.path
from vis.vtkpoly import VtkPolyModel
from vis.vtkvol import VtkVolumeModel
from IO.obj import OBJReader
class VtkIO:
def __get_reader(self, file_extension):
'''Returns a reader that can read the file type having the provided extension. Returns None if no such reader.'''
lo... | y"):
return vtk.vtkPLYReader()
if (lower_file_ext == ".obj"):
return OBJReader()
return None
def load(self, file_name):
"""Loads the data from the file 'file_name' and returns it. Returns None if the file type is not supported."""
# Make sure the file exists
if not file_name or not o... |
return None
# Get the right data reader depending on the file extension
data_reader = self.__get_reader(os.path.splitext(file_name)[1])
if not data_reader:
return None
data_reader.SetFileName(file_name)
data_reader.Update()
return data_reader.GetOutput()
|
sputnick-dev/weboob | modules/bp/pages/pro.py | Python | agpl-3.0 | 3,390 | 0.003542 | # -*- coding: utf-8 -*-
# Copyright(C) 2014 Romain Bignon
#
# This file is part of weboob.
#
# weboob is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your opt... | ativedelta import relativedelta
from decimal import Decimal
from weboob.deprecated.browser import Page
from weboob.deprecated.browser.parsers.csvparser import CsvParser
from weboob.capabilities.bank import Account, AccountNotFound
from .accounthistory import Transaction, AccountHistory
class RedirectPage(Page):
... | t(Page):
ACCOUNT_TYPES = {u'Comptes épargne': Account.TYPE_SAVINGS,
u'Comptes courants': Account.TYPE_CHECKING,
}
def get_accounts_list(self):
for table in self.document.xpath('//div[@class="comptestabl"]/table'):
try:
account_t... |
trevor/calendarserver | txdav/__init__.py | Python | apache-2.0 | 862 | 0 | # -*- test-case-name: txdav -*-
##
# Copyright (c) 2010-2014 Apple Inc. 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 law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitat... | shoul not be
# WebDAV-specific.
#
# (That means txdav.xml should be pulled out, for example, as that is
# WebDAV-specific.)
#
|
ikegami-yukino/shellinford-python | shellinford/__init__.py | Python | bsd-3-clause | 201 | 0 | from . | import shellinford
VERSION = (0, 4, 1)
__version__ = '0.4.1'
__all__ = ['FMIndex', 'bit_vector', 'bwt']
FMIndex = shellinford.FMIndex
bit_vector = shellinford.bit_vector
bwt = sh | ellinford.bwt
|
labase/activnce | main/utils/0_14_0207convertlogformat.py | Python | gpl-2.0 | 2,392 | 0.013854 | # -*- coding: utf-8 -*-
"""
################################################
Plataforma ActivUFRJ
################################################
:Author: *Núcleo de Computação Eletrônica (NCE/UFRJ)*
:Contact: [email protected]
:Date: $Date: 2009-2010 $
:Status: This is a "work in progress"
:Revision: $Revision: 0.0... | from couchdb import Server
from uuid import uuid4
_DOCBASES = ['log', 'log2']
_EMPTYLOG = lambda: dict(
sujeito = "",
verbo = "",
obj | eto = "",
tipo = "",
link = "",
news = "True", # todos os documentos do log velho que não tiverem o campo news
# serão copiados para o log novo com news="True"
... |
overxfl0w/Grampus-Forensic-Utils | Finger-FootPrinting/GrampusHTTP/fingerghttp.py | Python | gpl-2.0 | 1,829 | 0.053581 | import sys
sys.path.append("../../Crawlers/Bing/WAPI/")
from crawlerbing import crawlerbing
sys.path.append("../../Crawlers/Google/")
from crawlergoogle import crawlergoogle
class fingergrampushttp:
def __init__(self,key,header):
self.key = key
self.header = header
self.__selectUrls()
def __searchUrls(s... | data[indexAllow:data.find("\r\n",indexAllow)]
return data
except:
return ""
def __replacedUrl(self,url) | :
url = url.replace("http://","")
url = url[:url.find('/')]
return url
def __selectUrls(self):
self.allUrls = self.__searchUrls()
self.selectedUrls = {}
for key in self.allUrls:
try:
self.allUrls[key] = self.__getHeaders(key)
self.allUrls[key] += self.__getOptions(key)
if self.header ... |
davidnmurray/iris | docs/iris/example_tests/test_polar_stereo.py | Python | gpl-3.0 | 1,351 | 0 | # (C) British Crown Copyright 2013 - 2016, Met Office
#
# This file is part of Iris.
#
# Iris is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation, either version 3 of the License, or
# (at your option) any l... | the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th | e
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Iris. If not, see <http://www.gnu.org/licenses/>.
from __future__ import (absolute_import, division, print_function)
from six.moves import (filter, input, map, range, zip) ... |
nguyenngochuy91/Ancestral-Blocks-Reconstruction | create_operon_tree.py | Python | gpl-3.0 | 9,054 | 0.01712 | #!/usr/bin/env python
''' Author : Huy Nguyen
Program : Create operon tree
Start : 01/01/2018
End :
'''
from Bio import SeqIO
import argparse
import os
import homolog4
import shutil
from ete3 import Tree
## Traverses the genome information directory
def traverseAll(path):
res=[]
for root,dir... | tree_name = tree+name+"/"
try:
os.mkdir(tree_name)
except:
print (tree_name+" directory already created")
temp_align = tree_name +name+ '.aln'
cm1 ="muscle -in "+file+ " -out "+temp_align
os.system(cm1)
#make the tree using clustal
cm... | '.ph' # that's what this file gets named by default, and i'm sick of looking for the cmd line arg to fix.
print(temp_tree)
print("modifying")
#modify for negative branch
modify_tree = tree_name + name+ '.new'
cm3 = "sed -e 's,:-[0-9\.]\+,:0.0,g' "+temp_tree+" > "+modify_tree
... |
VIVEKLUCKY1848/gedit-plugins-1 | plugins/git/git/workerthread.py | Python | gpl-2.0 | 4,422 | 0.000226 | # -*- coding: utf-8 -*-
# Copyright (C) 2014 - Garrett Regier
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
... | ARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc. 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA.
from gi.repository import... | g
import traceback
from .debug import debug
class WorkerThread(threading.Thread):
__metaclass__ = abc.ABCMeta
__sentinel = object()
def __init__(self, callback, chunk_size=1, *args, **kwargs):
super().__init__(*args, **kwargs)
self.__callback = callback
self.__chunk_size = chun... |
levlaz/circleci.py | tests/circle/test_error.py | Python | mit | 951 | 0.001052 | # pylint: disable-all
import unittest
from circleci.err | or import CircleCIException, BadKeyError, BadVerbError, InvalidFilterError
class TestCircleCIError(unittest.TestCase):
def setUp(self):
self.base = Circle | CIException('fake')
self.key = BadKeyError('fake')
self.verb = BadVerbError('fake')
self.filter = InvalidFilterError('fake', 'status')
self.afilter = InvalidFilterError('fake', 'artifacts')
def test_error_implements_str(self):
self.assertTrue(self.base.__str__ is not object.... |
djaodjin/djaodjin-deployutils | deployutils/__init__.py | Python | bsd-2-clause | 1,370 | 0 | # Copyright (c) 2021, DjaoDjin Inc.
# All rights reserved.
#
# Redistri | bution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must repro... | sclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PUR... |
yephper/django | django/contrib/postgres/fields/jsonb.py | Python | bsd-3-clause | 3,093 | 0 | import json
from psycopg2.extras import Json
from django.contrib.postgres import forms, lookups
from django.core import exceptions
from django.db.models import Field, Transform
from django.utils.translation import ugettext_lazy as _
__all__ = ['JSONField']
class JSONField(Field):
empty_strings_all... | rn super(JSONField, self).get_prep_lookup(lookup_type, value)
def validate(self, value, model_instance):
super(JSONField, self).validate(value, model_instance)
try:
json.dumps(value)
except TypeError:
raise exceptions.ValidationError(
self.err... | e='invalid',
params={'value': value},
)
def value_to_string(self, obj):
value = self.value_from_object(obj)
return value
def formfield(self, **kwargs):
defaults = {'form_class': forms.JSONField}
defaults.update(kwargs)
return super... |
Rustem/toptal-blog-celery-toy-ex | celery_uncovered/toyex/models.py | Python | mit | 353 | 0 | class Repository(object):
def __init__(self, obj):
| self._wrapped_obj = obj
self.language = obj[u'language'] or u'unknown'
self.name = obj[u'full_name']
def __getattr__(self, attr):
if attr in self.__dict__:
retu | rn getattr(self, attr)
else:
return getattr(self._wrapped_obj, attr)
|
abramhindle/UnnaturalCodeFork | python/testdata/launchpad/lib/lp/services/webapp/doc/__init__.py | Python | agpl-3.0 | 186 | 0.005376 | # Copyright 2009 Canonical Ltd. This software is lic | ensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).
| # Make this directory into a Python package.
|
crisisking/udbraaains | brains/mapping/views.py | Python | bsd-3-clause | 3,478 | 0 | import cPickle as pickle
import datetime
import json
from django.conf import settings
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
import redis
from mapping.tasks import process_data
CONN = redis.Redis(host=settings.BROKER_HOST, port=settings.BROKER_PORT, db=6)
def pr... | ion[name_in]
else:
annotation[age_name] = None
@csrf_exempt
def receive_data(request):
if request.method == 'POST' and 'data' in request.POST:
data = json.loads(request.POST['data'])
# Grab the player's position and IP, process data in background
origin_x = data['surroundings']... | gin_y = data['surroundings']['position']['coords']['y']
if origin_x < 0 or origin_x > 99 or origin_y < 0 or origin_y > 99:
return HttpResponse('STOP IT', status=400)
if 'HTTP_X_REAL_IP' in request.META:
ip = request.META['HTTP_X_REAL_IP']
else:
ip = request.... |
JoltLabs/django-web-sugar | web_sugar/templatetags/jslint.py | Python | bsd-3-clause | 2,355 | 0.000849 | import os.path
import subprocess
from django import template
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.templatetags.static import StaticNode
from django.contrib.staticfiles import finders
from django.contrib.staticfiles.storage import staticfiles_storage
from... | ] + [path] + getattr(settings, 'JSLINT_ARGS', [])
if ext | ra_args:
cmd.append(extra_args)
proc = subprocess.Popen(' '.join(cmd), shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
stdout, stderr = proc.communicate()
proc.wait()
if stderr:
raise ImproperlyConfigured(stderr + '\n' +... |
agilemobiledev/mongo-orchestration | setup.py | Python | apache-2.0 | 2,438 | 0 | #!/usr/bin/python
import os
import sys
extra_opts = {'test_suite': 'tests'}
extra_deps = []
extra_test_deps = []
if sys.version_info[:2] == (2, 6):
extra_deps.append('argparse')
extra_deps.append('simplejson')
extra_test_deps.append('unittest2')
extra_opts['test_suite'] = 'unittest2.collector'
try:
... | st', 'r') as fd:
extra_opts['long_description'] = fd.read()
except IOError:
pass # Install without README.rst
setup(
| name='mongo-orchestration',
version='0.4.dev0',
author='MongoDB, Inc.',
author_email='[email protected]',
description='Restful service for managing MongoDB servers',
keywords=['mongo-orchestration', 'mongodb', 'mongo', 'rest', 'testing'],
license="http://www.apache.org/licenses/L... |
CanalTP/flask-restful | tests/test_api.py | Python | bsd-3-clause | 27,561 | 0.00381 | import unittest
from flask import Flask, views
from flask.signals import got_request_exception, signals_available
try:
from mock import Mock, patch
except:
# python3
from unittest.mock import Mock, patch
import flask
import werkzeug
from flask.ext.restful.utils import http_status_message, challenge, unautho... | ue))
])
marshal_fields = OrderedDict([('foo', 'bar'), ('bat', 'baz'), ('fee', None)])
output = flask_restful.marshal(marshal_fields, fields)
exp | ected = OrderedDict([('foo', 'bar'), ('fee', None)])
self.assertEquals(output, expected)
def test_marshal_nested_with_non_null_and_no_display_empty(self):
fields = OrderedDict([
('foo', flask_restful.fields.Raw),
('fee', flask_restful.fields.Nested(
Ordered... |
tornadozou/tensorflow | tensorflow/python/keras/applications/__init__.py | Python | apache-2.0 | 1,675 | 0 | # Copyright 2016 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... | sorflow.python.keras.applications.inception_v3 import InceptionV3
from t | ensorflow.python.keras.applications.mobilenet import MobileNet
from tensorflow.python.keras.applications.resnet50 import ResNet50
from tensorflow.python.keras.applications.vgg16 import VGG16
from tensorflow.python.keras.applications.vgg19 import VGG19
from tensorflow.python.keras.applications.xception import Xception
... |
DimensionDataCBUSydney/mist.io | scripts/get_rackspace_pricing.py | Python | agpl-3.0 | 3,267 | 0.010713 | # -*- coding: utf-8 -*-
#get pricing for rackspace providers by asking rackspace.
#Outputs dicts with providers and pricing per size, per image type, suitable for mist.io's config.py
import urllib
import urllib2
import cookielib
import json
#username and password as you login in https://mycloud.rackspace.com
userna... | nSQL',
"Windows -": 'mswin',
"RHEL": 'rhel',
"Linux": 'linux',
"Vyatta": 'vyatta',
}
#available da | tacenters/regions
#rackspace dict on pricing.json refers to first generation cloud servers and is manually
#created from http://www.rackspace.com/cloud/pricing/ First Gen...
rackspace = {
'rackspacenovalon': {},
'rackspacenovaiad': {},
'rackspacenovasyd': {},
'rackspacenovaord': {},
'rackspacenovadfw': {},
... |
GetBlimp/boards-backend | manage.py | Python | agpl-3.0 | 584 | 0 | #!/usr/bin/env python
import os
import sys
import dotenv
dotenv.read_dotenv()
if __name__ == "__main__":
ENVIRONMENT = os.get | env('ENVIRONMENT')
if ENVIRONMENT == 'STAGING':
settings = 'staging'
elif ENVIRONMENT == 'PRODUCTION':
settings = 'production'
else:
settings = 'development'
|
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'blimp_boards.settings')
os.environ.setdefault('DJANGO_CONFIGURATION', settings.title())
from configurations.management import execute_from_command_line
execute_from_command_line(sys.argv)
|
dalanlan/calico-docker | calico_containers/calico_ctl/node.py | Python | apache-2.0 | 18,774 | 0.001438 | # Copyright 2015 Metaswitch Networks
#
# 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 w... | ME> Docker image to use for Calico's per-node
container. Default is calico/node:latest.
Default for Calico with | libnetwork is
calico/node-libnetwork:latest.
--detach=<DETACH> Set "true" to run Calico service as detached,
"false" to run in the foreground. [default: true]
--log-dir=<LOG_DIR> The directory for logs [default: /var/log/calico]
--ip=... |
dsiroky/snakemq | tests/performance/packeter_connections.py | Python | mit | 3,249 | 0.003693 | #!/usr/bin/env python
"""
High amount of parallel connections.
@author: David Siroky ([email protected])
@license: MIT License ( | see LICENSE.txt or
U{http://www.opensource.org/licenses/mit-license.php})
"""
import time
import logging
import sys
import os
import threading
import multiprocessing
import random
sys.path.insert(0, "../..")
import snakemq
import snakemq.link
import snakemq.packeter
import snakemq.exceptions
############... | T = 10
CLI_THR_COUNT = 20
PACKETS_COUNT = 1000
PORT = 4000
###########################################################################
barrier = multiprocessing.Value("i", 0)
###########################################################################
def check_barrier():
barrier.acquire()
barrier.value += 1... |
intelxed/xed | scripts/apply_legal_header.py | Python | apache-2.0 | 5,516 | 0.012509 | #!/usr/bin/env python
# -*- python -*-
# BEGIN_LEGAL
#
# Copyright (c) 2021 Intel 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/license... | for | file in sources:
if re.search(".svn",file) == None and re.search(".new$",file) == None:
apply_header_to_data_file(header, file.strip())
else:
print("2nd argument must be -s or -t\n")
sys.exit(1)
|
firemark/zephryos | zephryos/wtform/controller.py | Python | mit | 3,101 | 0.002257 | from wtforms.validators import input_required
from wtforms import fields as wtform_fields
from ..serializers import serialize_field
from ..abstract.controller import AbstractController
from wtforms_json import flatten_json
class DummyMultiDict(dict):
def getlist(self, key):
return [self[key]]
class WTF... | tion,
attrs=attrs,
widget=field.widget
)
@classmethod
def add_new_type(cls, name, cls_type, func=None):
cls.field_types[cls_type] = (name, func)
def ou | ter(decorated_func):
cls.field_types[cls_type] = (name, decorated_func)
return decorated_func
return outer
WTFormController.add_new_type("text", wtform_fields.StringField)
WTFormController.add_new_type("bool", wtform_fields.BooleanField)
WTFormController.add_new_type("integer", wtform... |
klahnakoski/cloc | cloc/util/queries/es_query_aggop.py | Python | mpl-2.0 | 3,106 | 0.001932 | # encoding: utf-8
#
#
# 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/.
#
# Author: Kyle Lahnakoski ([email protected])
#
from __future__ import unicode_literals
from __... | ilter": simplify(query.where)
}
| else:
unwrap(esQuery.facets)[s.name] = {
"statistical": {
"script": mvel.compile_expression(s.value, query)
},
"facet_filter": simplify(query.where)
}
value2facet[s.value] = s.name
... |
woodshop/chainer | tests/optimizers_tests/test_optimizers_by_linear_model.py | Python | mit | 4,152 | 0 | import unittest
import numpy as np
import six
import chainer
from chainer import cuda
import chainer.functions as F
from chainer import optimizers
from chainer import testing
from chainer.testing import attr
from chainer.testing import condition
if cuda.available:
cuda.init()
class LinearModel(object):
UNI... | ad(OptimizerTestBase, unittest.TestCase):
def create(self):
return optimizers.AdaGrad(0.1)
class TestAdam(OptimizerTestBase, unittest.TestCase): |
def create(self):
return optimizers.Adam(0.1)
class TestMomentumSGD(OptimizerTestBase, unittest.TestCase):
def create(self):
return optimizers.MomentumSGD(0.1)
class TestRMSprop(OptimizerTestBase, unittest.TestCase):
def create(self):
return optimizers.RMSprop(0.1)
class TestR... |
woutersmet/Zeosummer | share/plugins/molecular/sketch.py | Python | gpl-3.0 | 21,326 | 0.003189 | # Zeobuilder is an extensible GUI-toolkit for molecular model construction.
# Copyright (C) 2007 - 2009 Toon Verstraelen <[email protected]>, Center
# for Molecular Modeling (CMM), Ghent University, Ghent, Belgium; all rights
# reserved unless otherwise stated.
#
# This file is part of Zeobuilder.
#
# Zeobuilde... | self.init_callbacks(self.__class__)
self.init_proxies([
"cb_object",
"cb_vector",
"cb_erase_filter",
"bu_edit_erase_filter",
"la_current",
"bu_set_atom",
"cb_bondtype",
"hbox_atoms",
"hbox_quickpicks",
... | "cb_fragment"
])
self.erase_filter = Expression("True")
#Initialize atom number - this can be changed anytime with the edit_atom_number dialog
self.atom_number = 6;
# Initialize the GUI
# 1) common parts of the comboboxes
def render_icon(column, cel... |
haoqili/MozSecWorld | apps/examples/views.py | Python | bsd-3-clause | 186 | 0 | """Example views. Fe | el free to delete this app."""
from django import http
import jingo
def home(request):
data = {}
return jin | go.render(request, 'examples/home.html', data)
|
karrtikr/ete | sdoc/tutorial/examples/measuring_evolution_trees.py | Python | gpl-3.0 | 7,121 | 0.01292 | #!/usr/bin/python
# Author: Francois-Jose Serra
# Creation Date: 2010/04/26 17:17:06
from ete3 import CodemlTree
import sys, re
typ = None
while typ != 'L' and typ != 'S':
typ = raw_input (\
"choose kind of example [L]ong or [S]hort, hit [L] or [S]:\n")
TREE_PATH = "./measuring_%s_tree.nw" % (ty... | in the alignment,'
print '\
Colors represent significantly conserved sites (cyan to blue), neutral sites (greens), or under \n\
positive selection (orange | to red). \n\
Lower face also represents values of omega (red line) and bars represent the error of the estimation.\n\
Also significance of belonging to one class of site can be painted in background (here lightgrey for\n\
evrething significant)\n\
Both representation are done according to BEB estimation of M2, M1 or M... |
ManageIQ/integration_tests | scripts/install_vddk.py | Python | gpl-2.0 | 1,303 | 0.002302 | #!/usr/bin/env python3
"""SSH into a running appliance and install VMware VDDK.
"""
import argparse
import sys
from urllib.parse import urlparse
from cfme.utils.appliance import get_or_create_current_appliance
from cfme.utils.appliance import IPAppliance
def log(message):
print(f"[VDDK-INSTALL] {message}")
def... | dk_url', help='url to download vddk pkg')
parser.add_argument('--reboot', help='reboot after installation ' +
'(required for proper operation)', action="store_true")
parser.add_argument('--force',
help='force installation if version detected', action="store_true")... | t args.address:
appliance = get_or_create_current_appliance()
else:
appliance = IPAppliance(hostname=urlparse(args.address).netloc)
appliance.install_vddk(
reboot=args.reboot, force=args.force, vddk_url=args.vddk_url, log_callback=log)
if __name__ == '__main__':
sys.exit(main())
|
Proggie02/TestRepo | tests/regressiontests/indexes/models.py | Python | bsd-3-clause | 238 | 0 | from django.db | import models
class Article(models.Model):
headline = models.CharField(max_length=100)
pub_date = models.DateTimeField()
class Meta:
index_together = [
["headline", "pu | b_date"],
]
|
othreecodes/MY-RIDE | app/models.py | Python | mit | 11,305 | 0.002565 | from __future__ import unicode_literals
import re
from django.contrib.auth.models import (AbstractBaseUser, PermissionsMixin,
UserManager)
from django.core import validators
from django.core.mail import send_mail
from django.utils.translation import ugettext_lazy as _
from noti... | '^[0-9]+$'), _('Only numbers are allowed.'), 'invalid')
])
user_choices = (('Driver', 'Driver'), ('Passenger', 'Passenger'))
user_type = models.CharField(_('user type'), max_length=30, blank=False, choices=user_choices)
address = models.TextField(_('location'), max_length=400, blank=False)
is_s... | t=False,
help_text=_('Designates whether the user can log into this admin '
'site.'))
is_verified = models.BooleanField(_('user verified'), default=False,
help_text=_('Designates whether the user... |
cpausmit/Kraken | filefi/043/mc-notrig.py | Python | mit | 9,131 | 0.013033 | import FWCore.ParameterSet.Config as cms
#---------------------------------------------------------------------------------------------------
# M A I N
#---------------------------------------------------------------------------------------------------
# create the process
pro... | TreeFiller)
# Electron likelihood-based id
from RecoEgamma.ElectronIdentification.ElectronMVAValueMapProducer_cfi import electronMVAValueMapProducer
process.load('RecoEgamma.ElectronIdentification.ElectronMVAValueMapProducer_cfi')
MitTreeFiller.Electrons.eIDLikelihoodName = 'electronMVAValueMapProducer:ElectronMVAEsti... | Used for rho calculation
from CommonTools.ParticleFlow.goodOfflinePrimaryVertices_cfi import goodOfflinePrimaryVertices
from CommonTools.ParticleFlow.pfParticleSelection_cff import pfParticleSelectionSequence, pfPileUp, pfNoPileUp, pfPileUpIso, pfNoPileUpIso
from CommonTools.ParticleFlow.pfPhotons_cff import pfPhotonSe... |
fredzannarbor/pagekicker-community | scripts_python_3/bin/sanitize.py | Python | apache-2.0 | 2,661 | 0.010147 | from beautifulsoup4 import beautifulsoup4
import re
def sanitize(html):
# allow these tags. Other tags are removed, but their child elements remain
whitelist = ['em', 'i', 'strong', 'u', 'a', 'b', 'p', 'br', 'code', 'pre', 'table', 'tr', 'td' ]
# allow only these attributes on these tags. No other tags ar... | nts and break the rest of the page.
soup = BeautifulSoup(html)
# now strip HTML we don't like.
for tag in soup.findAll():
| if tag.name.lower() in blacklist:
# blacklisted tags are removed in their entirety
tag.extract()
elif tag.name.lower() in whitelist:
# tag is allowed. Make sure all the attributes are allowed.
for attr in tag.attrs:
# allowed attributes are... |
ProfessionalIT/professionalit-webiste | sdk/google_appengine/google/appengine/tools/devappserver2/static_files_handler.py | Python | lgpl-3.0 | 13,838 | 0.005853 | #!/usr/bin/env python
#
# Copyright 2007 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 o... | allow_weak_ | match=False):
# http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.24
start_response('412 Precondition Failed',
[('ETag', '"%s"' % etag)])
return []
elif if_none_match and self._check_etag_match(if_none_match,
etag,
... |
ivmech/iviny-scope | lib/xlsxwriter/test/comparison/test_cond_format03.py | Python | gpl-3.0 | 2,548 | 0.000392 | ###############################################################################
#
# Tests for XlsxWriter.
#
# Copyright (c), 2013, John McNamara, [email protected]
#
import unittest
import os
from ...workbook import Workbook
from ..helperfunctions import _compare_xlsx_files
class TestCompareXLSXFiles(unittest.TestC... | dd_format({'underline': 1, 'dxf_index': 0})
worksheet.write('A1', 10)
worksheet.write('A2', 20)
worksheet.write('A3', 30)
worksheet.write('A4', 40)
worksheet.conditional_format('A1',
{'type': 'cell',
| 'format': format1,
'criteria': 'between',
'minimum': 2,
'maximum': 6,
})
worksheet.conditional_format('A1',
{'t... |
m4tto/pyrsyncgui | pyrsyncgui.py | Python | gpl-2.0 | 8,640 | 0.035069 | #!/usr/bin/python
'''
*
* Copyright (C) 2013 Simone Denei <[email protected]>
*
* This file is part of pyrsyncgui.
*
* pyrsyncgui 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 ... | self.window.hide()
if self.currentwizard != None:
self.currentwizard.stop()
def cleanup(self):
print('Closing')
self.bckeng.stop()
self.config.save()
self.schedconfig.save()
self.serverconfig.save()
@pyqtSlot()
def addSync(self):
self.currentwizard = addsyncwizard(self.window, ... | .currentwizard.start()
@pyqtSlot()
def manageSync(self):
self.currentwizard = managesyncwizard(self.window, self.config, self.serverconfig,self.schedconfig)
self.currentwizard.start()
@pyqtSlot()
def config(self):
self.currentwizard = configurationwizard(self.window, self.config)
self.current... |
ElementalAlchemist/txircd | txircd/modules/rfc/cmd_connect.py | Python | bsd-3-clause | 1,451 | 0.035837 | from twisted.plugin import IPlugin
from twisted.words.protocols import irc
from txircd.module_interface import Command, ICommand, IModuleData, ModuleData
from zope.interface import implements
class ConnectCommand(ModuleData, Command):
implements(IPlugin, IModuleData, ICommand)
name = "ConnectCommand"
core = True
... | self.ircd.runActionUntilValue("userhasoperpermission", user, "command-connect", users=[user]):
user.sendMessage(irc.ERR_NOPRIVILEGES, "Permission denied - You do not have the correct op | erator privileges")
return False
return None
def parseParams(self, user, params, prefix, tags):
if not params:
user.sendSingleError("ConnectParams", irc.ERR_NEEDMOREPARAMS, "CONNECT", "Not enough parameters")
return None
return {
"server": params[0]
}
def execute(self, user, data):
serverNam... |
sungyism/sungyism | gmond/python_modules/memcached/memcached.py | Python | bsd-3-clause | 11,706 | 0.009568 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import traceback
import os
import threading
import time
import socket
import select
descriptors = list()
Desc_Skel = {}
_Worker_Thread = None
_Lock = threading.Lock() # synchronization lock
Debug = False
def dprint(f, *v):
if Debug:
print >>sys.s... | "type" not in params:
params["type"] = "memcached"
if "metrix_prefix" not in params:
if params["type"] == "memcached":
params["metrix_prefix"] = "mc"
elif params["type"] == "Tokyo Tyrant":
| params["metrix_prefix"] = "tt"
print params
# initialize skeleton of descriptors
Desc_Skel = {
'name' : 'XXX',
'call_back' : metric_of,
'time_max' : 60,
'value_type' : 'float',
'format' : '%.0f',
'units' : 'XXX',
's... |
garrettcap/Bulletproof-Backup | wx/tools/Editra/plugins/Launch/launch/launchxml.py | Python | gpl-2.0 | 4,699 | 0.003831 | # -*- coding: utf-8 -*-
###############################################################################
# Name: launchxml.py #
# Purpose: Launch Xml Interface #
# Author: Cody Precord <[email protected]> ... | h.GetHandler('C')
# print hndlr.GetCommands()
# print hndlr.GetHotspotPattern()
# print hndlr.GetErrorPat | tern()
# print hndlr.GetDefaultCommand()
|
SalesforceFoundation/CumulusCI | cumulusci/tasks/salesforce/tests/test_UninstallLocal.py | Python | bsd-3-clause | 625 | 0.0032 | from unittest import mock
import unittest
from cumulusci.tasks.salesforce import UninstallLocal
from cumulusci.utils import temporary_dir
from . | util import create_task
class TestUninstallLocal(unittest.TestCase):
@mock.patch("cumulusci.tasks.metadata.package.PackageXmlGenerator.__call__")
def test_get_destructiv | e_changes(self, PackageXmlGenerator):
with temporary_dir() as path:
task = create_task(UninstallLocal, {"path": path})
PackageXmlGenerator.return_value = mock.sentinel.package_xml
self.assertEqual(mock.sentinel.package_xml, task._get_destructive_changes())
|
mapycz/python-mapnik | test/python_tests/shapefile_test.py | Python | lgpl-2.1 | 5,190 | 0.000385 | import os
from nose.tools import assert_almost_equal, eq_, raises
import mapnik
from .utilities import execution_path, run_all
def setup():
| # All of the paths used are relative, if we run the tests
# from another directory we need to chdir()
os.chdir(execution_path('.'))
if 'shape' in mapnik.DatasourceCache.plugin_names():
# Shapefile initialization
def test_shapefile_init():
s = mapnik.Shapefile(file='../data/shp/ | boundaries')
e = s.envelope()
assert_almost_equal(e.minx, -11121.6896651, places=7)
assert_almost_equal(e.miny, -724724.216526, places=6)
assert_almost_equal(e.maxx, 2463000.67866, places=5)
assert_almost_equal(e.maxy, 1649661.267, places=3)
# Shapefile properties
def ... |
unlessbamboo/grocery-shop | language/python/src/package/abs_import/unable/unable_module.py | Python | gpl-3.0 | 104 | 0.012821 | # | coding:utf8
"""
无法从上层目录进行导入操作
"""
class UnableTest(obj | ect):
pass
|
sxjscience/tvm | python/tvm/auto_scheduler/search_policy.py | Python | apache-2.0 | 7,529 | 0.001992 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | size of sampled population
Returns
-------
states: List[State]
The sampled states
"""
states = _ffi_api.SketchPolicySampleInitialPopulation(self, pop_size)
return states
def evolutionary_search(self, init_populations, out_size):
"""Evolutionary s... | sed for debugging and testing.
The actual search is all done in c++.
Parameters
----------
init_populations: List[State]
The initial population states
out_size : int
The size of generated states
Returns
-------
states: List[State]
... |
namhyung/uftrace | tests/t198_lib_arg_float.py | Python | gpl-2.0 | 799 | 0.002503 | #!/usr/bin/env python
from runtest import TestBase
class TestCase(TestBase):
def __init__(self):
TestBase.__init__(self, 'float-libcall', result="""
# DURATION TID FUNCTION
[18276] | main() {
0.3 | 71 ms [18276] | expf(1.000000) = 2.718282;
0.118 ms [18276] | log(2.718282) = 1.000000;
3.281 ms [18276] | } /* main */
""")
def build(self, name, cflags='', ldflags=''):
# cygprof doesn't support arguments now
if cflags.find('-finstrument-func | tions') >= 0:
return TestBase.TEST_SKIP
ldflags += " -lm"
return TestBase.build(self, name, cflags, ldflags)
def setup(self):
self.option = '-A "expf@fparg1/32" -R "expf@retval/f32" '
self.option += '-A "log@fparg1/64" -R "log@retval/f64" '
|
ldjebran/robottelo | tests/foreman/cli/test_logging.py | Python | gpl-3.0 | 11,539 | 0.001907 | """CLI tests for logging.
:Requirement: Logging
:CaseAutomation: Automated
:CaseLevel: Acceptance
:CaseComponent: logging
:TestType: Functional
:CaseImportance: Medium
:Upstream: No
"""
import re
from fauxfactory import gen_string
from robottelo import (
manifests,
ssh,
)
from robottelo.cli.factory impor... | og_2, connection)
# get the log lines of interest, put them in test_logfile_1
cut_lines(line_count_start_1, line_count_end_1, source_log_1, test_logfile_1,
connection)
# get the log lines of interest, put them in test_logfile_2
cut_lines(line_count_s... | 2,
connection)
# use same location on remote and local for log file extract
ssh.download_file(test_logfile_1)
# use same location on remote and local for log file extract
ssh.download_file(test_logfile_2)
# search the log file extract for the line with PUT t... |
JcDelay/pycr | libpycr/builtin/accounts/ls-diff-prefs.py | Python | apache-2.0 | 3,136 | 0 | """List diff preferences associated with one's account"""
# pylint: disable=invalid-name
import argparse
import logging
from libpycr.exceptions import PyCRError
from libpycr.gerrit.client import Gerrit
from libpycr.meta import GerritAccountBuiltin
from libpycr.pager import Pager
from libpycr.utils.commandline import... | _highlighting)])
table.add_row(['Tab size', prefs.tab_size])
with Pager(command=self.name):
print 'Account: {}'.format(account.username)
print table
| |
animekita/selvbetjening | selvbetjening/core/events/migrations/0006_auto__chg_field_attend_user__chg_field_payment_signee__chg_field_payme.py | Python | mit | 17,577 | 0.008136 | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Changing field 'Attend.user'
db.alter_column(u'events_attend', 'user_id', self.gf('django.db.models.field... | ', [], {'max_length': '100'}),
u'id': ('django.db.models.fields.AutoField', [], { | 'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
u'countries.country': {
'Meta': {'ordering': "('name',)", 'object_name': 'Country', 'db_tabl... |
caderache2014/django-rest-tutorial | tutorial/snippets/models.py | Python | mit | 819 | 0.001221 | from django.db import models
from pygments.lexers import get_all_lexers
from pygments.styles import get_all_styles
LEXERS = [item for item in get_all_lexers() if item[1]]
LANGUAGE_CHOICES = sorted([(item[1][0], item[0]) for item in LEXERS])
STYLE_CHOICES = sorted((item, item) for item in get_all_styles())
class Snip... | e = models.CharField(
choices=LANGUAGE_CHOICES,
default='python',
max_length=100)
style = models.CharField(
choices=STYLE_CHOICES,
| default='friendly',
max_length=100)
class Meta:
ordering = ('created',) |
lcrees/twoq | twoq/tests/auto/ordering.py | Python | bsd-3-clause | 2,838 | 0.0074 | # -*- coding: utf-8 -*-
'''auto ordering call chain test mixins'''
from inspect import ismodule
from twoq.support import port
class ARandomQMixin(object):
def test_choice(self):
self.assertEqual(len(list(self.qclass(1, 2, 3, 4, 5, 6).choice())), 1)
def test_sample(self):
self.assertEqual(l... | 30), (40, 50), (True, 'x')]
)
def test_reversed(self):
self.assertEqual(
self.qclass(5, 4, 3, 2, 1).reverse().end(), [1, 2, 3, 4, 5],
)
def test_sort(self):
from math import sin
self.assertEqual(
self. | qclass(1, 2, 3, 4, 5, 6).tap(
lambda x: sin(x)
).sort().end(),
[5, 4, 6, 3, 1, 2],
)
self.assertEqual(
self.qclass(4, 6, 65, 3, 63, 2, 4).sort().end(),
[2, 3, 4, 4, 6, 63, 65],
)
__all__ = sorted(name for name, obj in port.items(l... |
epfl-lts2/pygsp | examples/fourier_transform.py | Python | bsd-3-clause | 1,371 | 0 | r"""
Fourier transform
=================
The graph Fourier transform :meth:`pygsp.graphs.Graph.gft` transforms a
signal from the vertex domain to the spectral domain. The smoother the signal
(see :meth:`pygsp.graphs.Graph.dirichlet_energy`), the lower in the frequencies
its energy is concentrated.
"""
import numpy as... |
axes[1, i].plot(G.e, np.abs(x_hat), '.-')
axes[1, i].set_xticks(range(0, 16, 4))
axes[1, i].set_xlabel(r'graph frequency $\lambda$')
axes[1, i].set_ylim(-0.05, 0.95)
axes[1, 0].set_ylabel(r'frequency content $\hat{x}(\lambda)$')
# axes[0, 0].set_title(r'$x$: signal in the vertex domain')
# axes[1, 0]... | yout()
|
appleseedhq/cortex | test/IECoreScene/MeshAlgoNormalsTest.py | Python | bsd-3-clause | 4,040 | 0.036139 | ##########################################################################
#
# Copyright (c) 2019, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistribu... | "N"]
normals = IECoreScene.MeshAlgo.calculateNormals( s )
self.assertEqual( normals.interpolation, IECoreScene.PrimitiveVariable.Interpolation.Vertex )
self.assert_( normals.data.isInstanceOf( IECore.V3fVectorData.staticTypeId() ) )
self.assertEqual( normals.data.size(), s.variableSize( IECoreScene.Primitive... | tion.Normal )
points = s["P"].data
for i in range( 0, normals.data.size() ) :
self.assertTrue( math.fabs( normals.data[i].length() - 1 ) < 0.001 )
p = points[i].normalize()
self.assertTrue( normals.data[i].dot( p ) > 0.99 )
self.assertTrue( normals.data[i].dot( p ) < 1.01 )
def testUniformInterpola... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.