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
saurabh6790/frappe
frappe/build.py
Python
mit
14,371
0.025277
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt import os import re import json import shutil import subprocess from tempfile import mkdtemp, mktemp from distutils.spawn import find_executable import frappe from frappe.utils.minify import JavascriptMinify import cl...
click.secho("\nExtracting assets...\n", fg="yellow") with tarfile.open(assets_archive) as tar: for file in tar: if not file.isdir(): dest = "." + file.name.replace("./frappe-bench/sites", "") asset_directory = os.path.dirname
(dest) show = dest.replace("./assets/", "") if asset_directory not in directories_created: if not os.path.exists(asset_directory): os.makedirs(asset_directory, exist_ok=True) directories_created.add(asset_directory) tar.makefile(file, dest) print("{0} Restored {1}"...
greenape/disclosure-game
python/disclosuregame/disclosuregame/Agents/__init__.py
Python
mpl-2.0
81
0.024691
__all__ =
["bayes", "cpt", "heuristic", "payoff", "recognition", "rl", "sharin
g"]
beefoo/still-i-rise
sort_audio.py
Python
mit
3,221
0.003726
# -*- coding: utf-8 -*- # Description: sort audio clips by intensity, frequency, or duration; outputs .csv file for use in sequence.ck via ChucK # python sort_audio.py -sort syllables # python sort_audio.py -sort syllables -by frequency # python sort_audio.py -sort syllables -by duration -fixed 0 import argpars...
d in data["words"]: clips += word["syllables"] # add duration for i, clip in enumerate(clips): clips[i]["duration"] = clip["end"] - clip["start"] # sort clips clips = sorted(clips, key=lambda c: SORT_DIRECTION * c[SORT_BY]) # generate a sequence sequence = [] ms = 0 for clip in clips: dur =
int(clip["duration"] * 1000) filename = CLIP_DIR + SORT_FIELD + "/" + clip["name"] + FILE_EXT if os.path.isfile(filename): sequence.append({ "elapsed_ms": ms, "gain": 1.0, "file": filename }) else: print "%s not found" % filename if FIXED_MS >...
Amyantis/SocialNewspaper
ArticleManagement/urls.py
Python
gpl-3.0
1,336
0.001497
"""SocialNewspaper 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') ...
ass-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.ur
ls')) """ from django.conf.urls import url from django.contrib import admin from ArticleManagement import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^share_article/$', views.share_article, name="share_article"), url(r'^print_sharing/(?P<article_id>[0-9]+)$', views.print_sharing, name="p...
mhellmic/davix
test/pywebdav/lib/AuthServer.py
Python
lgpl-2.1
3,349
0
"""Authenticating HTTP Server This module builds on BaseHTTPServer and implements basic authentication """ import base64 import binascii import BaseHTTPServer DEFAULT_AUTH_ERROR_MESSAGE = """ <head> <title>%(code)s - %(message)s</title> </head> <body> <h1>Authorization Required</h1> this server could not verify th...
redentials.split(':', 2) if not self.get_userinfo(user, password, self.command): self.send_autherro
r(401, "Authorization Required") return False return True def send_autherror(self, code, message=None): """Send and log an auth error reply. Arguments are the error code, and a detailed message. The detailed message defaults to the short entry matching the r...
lyw07/kolibri
kolibri/core/auth/test/test_datasets.py
Python
mit
2,905
0.000688
""" Tests related specifically to the FacilityDataset model. """ from django.db.utils import IntegrityError from django.test import TestCase from ..models import Classroom from ..models import Facility from ..models import FacilityDataset from ..models import FacilityUser from ..models import LearnerGroup class Faci...
def test_manually_passing_dataset_for_new_facility(self): dataset = FacilityDataset.objects.create() facility = Facility(name="blah", dataset=dataset) facility.full_clean() facilit
y.save() self.assertEqual(dataset, facility.dataset) def test_dataset_representation(self): self.assertEqual( str(self.facility.dataset), "FacilityDataset for {}".format(self.facility.name), ) new_dataset = FacilityDataset.objects.create() self.assert...
Brazelton-Lab/lab_scripts
esom_tracer2.py
Python
gpl-2.0
12,317
0.000568
#!/usr/bin/env python """Color ESOM data points by Phylogeny Usage: esom_tracer2.py [--bam] [--names] [--taxonomy] [--taxa_level] [--output] Synopsis: Takes alignment data from short reads mapped to an assembly in BAM format and the phylogeny of those short reads from the Phylosift sequence_taxa_su...
umber of RGB values to generate :type scale: int """ hsv_tuples = [(float(i) / float(scale), 1.0, 1.0) for i in range(scale)] rgb_tuples = map(lambda x: tuple(i * 255 for i in \ colorsys.hsv_to_rgb(*x)), hsv_tuples) return rgb_tuples def taxa_dict(taxa_handle): """Returns...
:type taxa_handle: File Object Dictionary Structure (YAML format) ---------------------------------- short_read_name: taxa_level: [taxa_name,probability_mass] """ temp_dict = defaultdict(dict) taxa_handle.readline() for line in taxa_handle: columns = line.strip().split('\t...
xenobyter/xbWeatherSocket
SocketFrame.py
Python
isc
3,029
0.002311
# -*- coding: UTF-8 -*- # # generated by wxGlade 0.6.8 on Thu Apr 2 20:01:32 2015 # import wx # begin wxGlade: dependencies # end wxGlade # begin wxGlade: extracode # end wxGlade class SocketFrame(wx.Frame): def __init__(self, *args, **kwds): # begin wxGlade: SocketFrame.__init__ kwds["style"] ...
_FRAME_STYLE wx.Frame.__init__(self, *args, **kwds) self.button_aquarium = wx.ToggleButton(self, wx.ID_ANY, "Aquarium") self.button_kitchen = wx.ToggleButton(self, wx.ID_ANY, u"K\xfcche") sel
f.button_bedroom = wx.ToggleButton(self, wx.ID_ANY, "Schlafstube") self.button_back = wx.Button(self, wx.ID_ANY, u"Zur\xfcck") self.button_livingroom = wx.ToggleButton(self, wx.ID_ANY, "Wohnstube") self.__set_properties() self.__do_layout() self.Bind(wx.EVT_TOGGLEBUTTON, self.O...
atagar/ReviewBoard
reviewboard/accounts/tests.py
Python
mit
2,192
0
from django.contrib.auth.models import User from djblets.testing.decorators import add_fixtures from djblets.testing.testcases import TestCase from reviewboard.accounts.models import LocalSiteProfile from reviewboard.reviews.models import ReviewRequest class ProfileTests(TestCase): """Testing the Profile model."...
h public profiles.""" user1 = User.objects.get(username='admin') user2 = User.objects.get(username='doc') self.assertTrue(user1.is_profile_visible(user2)) def test_is_profile_visible_with_private(self): """Testing User.is_profile_public with private profiles.""" user1 = Use...
username='doc') profile = user1.get_profile() profile.is_private = True profile.save() self.assertFalse(user1.is_profile_visible(user2)) self.assertTrue(user1.is_profile_visible(user1)) user2.is_staff = True self.assertTrue(user1.is_profile_visible(user2)) ...
yaxu/patternlib
pattern/migrations/0015_pattern_json.py
Python
gpl-3.0
444
0
# -*- coding: utf-8 -*- #
Generated by Django 1.10.4 on 2017-05-30 22:20 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('pattern', '0014_pattern_editnumber'), ] operations = [ migrations.AddField( model_name='p...
field=models.TextField(null=True), ), ]
michelts/aloe_django
tests/integration/django/dill/leaves/features/steps.py
Python
gpl-3.0
1,684
0
# import io import json import sys from django.core.management import call_command from leaves.models import ( Harvester, Panda, ) from aloe import after, step from aloe.tools import guess_types from aloe_django.steps.models import ( test_existence, tests_existence, write_models, writes_mode...
'The database dump is as follows') def database_dump(step): if sys.version_info
>= (3, 0): output = io.StringIO() else: output = io.BytesIO() call_command('dumpdata', stdout=output, indent=2) output = output.getvalue() assert_equals(json.loads(output), json.loads(step.multiline)) @step(r'I have populated the database') def database_populated(step): pass @ste...
mitsei/dlkit
tests/authorization/test_searches.py
Python
mit
5,434
0.001472
"""Unit tests of authorization searches.""" import pytest from ..utilities.general import is_never_authz, is_no_authz, uses_cataloging, uses_filesystem_only from dlkit.abstract_osid.osid import errors from dlkit.primordium.id.primitives import Id from dlkit.primordium.type.primitives import Type from dlkit.runtime ...
izationSearch""" @pytest.mark.skip('unimplemented te
st') def test_search_among_authorizations(self): """Tests search_among_authorizations""" pass @pytest.mark.skip('unimplemented test') def test_order_authorization_results(self): """Tests order_authorization_results""" pass @pytest.mark.skip('unimplemented test') def...
pdeesawat/PSIT58_test_01
Test_Python_code/last/02_Indonesia/total_death_indonesia.py
Python
apache-2.0
1,399
0.010722
import plotly.plotly as py import plotly.graph_objs as go data = open('Real_Final_database_02.csv') alldata = data.readlines() listdata = [] for i in alldata: listdata.append(i.strip().split(',')) type_z = ['Flood', 'Epidemic', 'Drought', 'Earthquake', 'Storm'] size_fill = [15,20,25,30,35] fill_colors = ['#00d0f5'...
death_z] ) ) ) data = trace layout = go.Layout( title='Total Death In Indonesia', showlegend=True, height=600, width=600, xaxis=dict( # set x-axis' labels direction at 45 degree angle tickangle=-45, ), yaxis=dict( title="Total D...
ayout=layout) plot_url = py.plot(fig, filename='Total_Death_in_Indonesia')
balanced/balanced-python
scenarios/debit_update/executable.py
Python
mit
284
0.003521
import balanced balanced.configure('ak-test-2eKlj1ZDfAcZSARMf3NMhBHywDej0avSY') debit = balanced.Debit.fetch('/debits/WD5EW7vbyXlTsudIGF5AkrEA') debit.description =
'New description for d
ebit' debit.meta = { 'facebook.id': '1234567890', 'anykey': 'valuegoeshere', } debit.save()
Aeronautics/aero
aero/commands/install.py
Python
bsd-3-clause
1,362
0.002937
# -*- coding: utf-8 -*- from aero.__version__ import __version_info__ __author__ = 'nickl-' from .base import CommandProcessor as CommandProcessor class InstallCommand(CommandProcessor): from .base import coroutine package = '' adapter = '' def wiring(self): self.out = self.write() ...
) def seen(self, command, adapter, package, result=False): self.package = package self.adapter = adapter return result @coroutine def res(self): while True: res = (yield) if res[1] == 0: print 'Successfully installed package: {} wit
h {}'.format(self.package, self.adapter) else: print 'Aborted: Error while installing package: {} {} returned exit code {}'.format( self.package, self.adapter, res[1] ) @coroutine def write(self): import sys out = sys.stdout ...
Fly-Style/metaprog_univ
Lab1/polls/migrations/0004_auto_20161201_1743.py
Python
mit
487
0.002053
# -*- coding: utf-8 -*- # Generated by Django 1.10.1 on 2016-12-01 17:43 from __future__ import unicode_literals from django.db import migrations, models class Migra
tion(migrations.Migration): dependencies = [ ('polls',
'0003_bettoride_success'), ] operations = [ migrations.AlterField( model_name='bet', name='isBetSuccessful', field=models.NullBooleanField(default=None, verbose_name='BetSuccess'), ), ]
jwhitlock/web-platform-compat
webplatformcompat/tests/test_cache.py
Python
mpl-2.0
27,278
0
#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for `web-platform-compat` fields module.""" from datetime import datetime from pytz import UTC from django.contrib.auth.models import User from django.test.utils import override_settings from webplatformcompat.cache import Cache from webplatformcompat.history imp...
mdn_uri='{"en": "https://example.com/page1"}') page2 = self.create( Feature, slug='page2', parent=child2, mdn_uri='{"en": "https://example.com/page2"}') feature = Feature.objects.get(id=feature
.id) out = self.cache.feature_v1_serializer(feature) self.assertEqual(out['descendant_count'], 5) self.assertEqual( out['descendant_pks'], [child1.pk, child2.pk, child21.pk, page2.pk, page1.pk]) self.assertEqual( out
DNFcode/edx-platform
common/djangoapps/student/views.py
Python
agpl-3.0
91,790
0.002528
""" Student Views """ import datetime import logging import re import uuid import time import json from collections import defaultdict from pytz import UTC from django.conf import settings from django.contrib.auth import logout, authenticate, login from django.contrib.auth.models import User, AnonymousUser from django...
disable=invalid-name def csrf_token(context): """A csrf token that can be included in a form.""" token = context.get('csrf_token', '') if token == 'NOTPROVIDED': return '' return (u'<div style="display:none"><input type="hidden"' ' name="csrfmiddlewaretoken" value="%s" /></div>' % ...
ched for anonymous users. # This means that it should always return the same thing for anon # users. (in particular, no switching based on query params allowed) def index(request, extra_context=None, user=AnonymousUser()): """ Render the edX main page. extra_context is used to allow immediate display of ce...
ksmaheshkumar/grr
client/client_actions/tempfiles_test.py
Python
apache-2.0
6,106
0.003439
#!/usr/bin/env python """Tests for grr.client.client_actions.tempfiles.""" import os import tempfile import time from grr.client.client_actions import tempfiles from grr.lib import config_lib from grr.lib import flags from grr.lib import rdfvalue from grr.lib import test_lib from grr.lib import utils class GRRTempF...
TempFile(filename="process.42.exe", mode="wb") fd.close() self.assertTrue(os.path.exists(fd.name)) self.assertTrue(os.path.basen
ame(fd.name) == "process.42.exe") tempfiles.DeleteGRRTempFile(fd.name) self.assertFalse(os.path.exists(fd.name)) fd = open(os.path.join(self.temp_dir, "notatmpfile"), "w") fd.write("something") fd.close() self.assertTrue(os.path.exists(fd.name)) self.assertRaises(tempfiles.ErrorNotTempFile,...
trmccart/py-jnprwlc
examples/maker.py
Python
apache-2.0
369
0.00813
import demowlcutils from demowlcutils import ppxml, WLC_login from
pprint import pprint as pp from jnpr.wlc import WirelessLanController as WLC wlc = WLC(host='a', user='b', password='c') r = wlc.RpcMaker( target='vlan', name='J
eremy') # you can access the following attributes, refer to the jnpr.wlc.builder # file for more details # r.cmd # r.target # r.args
uranusjr/django-crispy-forms-ng
crispy_forms/tests/urls.py
Python
mit
292
0
import django if
django.VERSION >= (1, 5): from django.conf.urls import patterns, url else: from django.conf.urls.defaults import patterns, url def simpleAction(request): pass urlpatterns = patterns( '', url(r'^simple/action/$', simpleAction, n
ame='simpleAction'), )
fabio-otsuka/invesalius3
invesalius/gui/task_tools.py
Python
gpl-2.0
5,584
0.008596
#-------------------------------------------------------------------------- # Software: InVesalius - Software de Reconstrucao 3D de Imagens Medicas # Copyright: (C) 2001 Centro de Pesquisas Renato Archer # Homepage: http://www.softwarepublico.gov.br # Contact: invesalius@cti.gov.br # License: GNU ...
def OnLinkAngularMeasure(self): Publisher.sendMessage('Enable style', constants.STATE_MEASURE_ANGLE) def OnButton(self, evt): id = evt.GetId() if id == ID_BTN_MEASURE_LINEAR: self.OnLink
LinearMeasure() elif id == ID_BTN_MEASURE_ANGULAR: self.OnLinkAngularMeasure() else: # elif id == ID_BTN_ANNOTATION: self.OnTextAnnotation()
mjames-upc/python-awips
dynamicserialize/dstypes/com/raytheon/uf/common/message/Header.py
Python
bsd-3-clause
611
0.003273
## ## # File auto-generated against equivalent DynamicSerialize Java clas
s from .Property import Property class
Header(object): def __init__(self, properties=None, multimap=None): if properties is None: self.properties = [] else: self.properties = properties if multimap is not None: for k, l in multimap.items(): for v in l: self...
yedivanseven/bestPy
tests/algorithms/similarities/test_similarities.py
Python
gpl-3.0
2,753
0
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import unittest as ut import numpy as np import scipy.spatial.distance as spd from .mock_data import Data
from ....algorithms.similarities import cosine_binary, cosine, dice, jac
card from ....algorithms.similarities import kulsinski, russellrao, sokalsneath MATRIX = np.array([[1, 0, 3, 5, 0, 2], [0, 1, 2, 0, 4, 1], [3, 4, 0, 0, 1, 1], [5, 0, 1, 2, 3, 0], [2, 0, 4, 2, 0, 0], [0, 7, 0, 1, 2, 5], ...
nmz787/microfluidic-cad
implicitCAD/process_all_escad.py
Python
gpl-2.0
1,723
0.007545
import subprocess import os # setup the path to extopenscad (aka implicitCAD) cad_bin=os.path.expanduser('~/.cabal/bin/extopenscad') # set the current input dir to this script file's dir inp_dir = '.' # set the output to a directory next to this script file out_dir = './output' # set the output file extension to .stl ...
# go through each item in the input dir for f in os.listdir(inp_dir): # if the item is a .escad file, process if '.escad' in f: # remove .escad from the filename
n=f[0:f.index('.escad')] # join the output dir with the stripped file and the output filetype out= os.path.join(out_dir, n + out_type ) # join the input directory and the current dir list item inp=os.path.join(inp_dir, f) # emit...
gmenegoz/pycraft
projects/test.py
Python
gpl-3.0
1,511
0.001324
from pycraft_minetest import * pos = where() chat(pos) maze("maze1.csv") t = turtle(obsidian) t.forward(10) move(3, 10, 5) chat(where()) sphere(ice, y=-20) circle([wool, 5], direction="horizontal") line(gold, 0, 0, 0, 0, 50, 0) block(iron, y=3) blocks(wood, x=5, y=6, z=10) size = readnumber("tell the size......
readstring("say something...") chat("I said: " + text) pyramid(sandstone) polygon(obsidian, 12, 30) chat("Hello Minecraf
t!") color = 0 uga = turtle([wool, color]) while True: for i in range(18): uga.forward(5) uga.up(20) uga.up(30) color += 1 uga.penblock([wool, color % 12]) # GOLD in ICE # while True: # if over(ice): # chat("ice") # block(gold, y=-1) # if near(gold): # ...
apehua/pilas
pilasengine/fondos/color.py
Python
lgpl-3.0
498
0
# pila
s engine: un motor para hacer videojuegos # # Copyright 2010-2014 - Hugo Ruscitti # License: LGPLv3 (see http://www.gnu.org/licenses/lgpl.html) # # Website - http://www.pilas-engine.com.ar from pilasengine.fondos import fondo class Color(fondo.Fondo): def __init__(self, pilas, color): fondo.Fondo.__init...
rficie(ancho, alto) self.imagen.pintar(color)
szha/mxnet
benchmark/python/sparse/updater.py
Python
apache-2.0
2,695
0.001484
# 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...
e mx.gpu() ones = mx.nd.ones((dim_in, dim_out), ctx=ctx) if not args.dense_grad: weight = ones.tostype('row_sparse') indices = np.arange(dim_in) np.random.shuffle(indices) indices = np.unique(indices[:nnr]) indices = mx.nd.array(indices, ctx=ctx) grad = mx.nd.sparse.retain(weight, indices) els...
es.copy() grad = ones.copy() if args.dense_state: mean = ones.copy() else: mean = ones.tostype('row_sparse') var = mean.copy() # warmup for i in range(10): adam_update(weight, grad, mean, var, out=weight, lr=1, wd=0, beta1=0.9, beta2=0.99, rescale_grad=0.5, epsilon=1e-8) weight.wait_...
gkabbe/cMDLMC
mdlmc/LMC/output.py
Python
gpl-3.0
1,858
0.004306
# coding=utf-8 import numpy as np class CovalentAutocorrelation: def __init__(self, lattice): self.reset(lattice) def reset(self, lattice): self.lattice = lattice.copy() def calculate(self, lattice): return np.sum((lattice == self.lattice) & (lattice != 0)) class MeanSquareDis...
0) self.snapshot = np.zeros((proton_number, 3)) self.displacement = np.zeros_like(self.snapshot) self.snapshot = self.determine_proton_positions(atom_positions, lattice) self.atombox = atombox def determine_proton_positions(self, atom_positions, lattice): proton_positions = ...
idx] return proton_positions def update_proton_positions(self, atom_positions, lattice): self.snapshot[:] = self.determine_proton_positions(atom_positions, lattice) def update_displacement(self, new_positions, lattice): """Update the current position of each proton while considering pe...
natefoo/pulsar
tools/bootstrap_history.py
Python
apache-2.0
3,345
0.001794
#!/usr/bin/env python # Little script to make HISTORY.rst more easy to format properly, lots TODO # pull message down and embed, use arg parse, handle multiple, etc... import os import sys try: import requests except ImportError: requests = None import urllib.parse import textwrap PROJECT_DIRECTORY = os.path.j...
rl = urllib.parse.urljoin(PROJECT_API, "pulls/%s" % pull_request) req = requests.get(api_url).json() m
essage = req["title"] login = req["user"]["login"] if login not in AUTHORS_SKIP_CREDIT: message = message.rstrip(".") message += " (thanks to `@%s`_)." % req["user"]["login"] elif requests is not None and ident.startswith("issue"): issue = ident[len("issue"):] ...
xtao/code
vilya/libs/emoji.py
Python
bsd-3-clause
8,756
0.000457
#!/usr/bin/env python # coding=utf-8 import re import os from cgi import escape EMOJIS = [ ':Aquarius:', ':two_women_in_love:', ':bus_stop:', ':speak_no_evil_monkey:', ':chicken:', ':heart_eyes:', ':Scorpius:', ':smiley_confused:', ':cat_face_with_wry_smile:', ':GAKUEngine:', ':pistol:', ':relieved:', ...
':tangerine:', ':person_bowing_deeply:', ':stuck_out_tongue_closed_eyes:', ':dog_face:', ':circled_ideograph_secret:', ':Libra:', ':jumping_spider:', ':disappointed_face:', ':hamburger:', ':octocat:', ':sleeping:', ':crescent_moon:', ':no_one_under_eighteen_symbol:', ':kissing:', ':unamused:', ':co...
_with_heart:', ':fisted_hand_sign:', ':smiling_cat_face_with_heart_shaped_eyes:', ':anguished:', ':groupme:', ':expressionless:', ':phone_book:', ':full_moon:', ':bactrian_camel:', ':snowboarder:', ':microphone:', ':Gemini:', ':fearful_face:', ':pensive_face:', ':jack_o_lantern:', ':Aries:', ':palm_pre3...
bsipocz/ginga
ginga/misc/plugins/FBrowserBase.py
Python
bsd-3-clause
5,421
0.003689
# # FBrowserBase.py -- Base class for file browser plugin for fits viewer # # Eric Jeschke (eric@naoj.org) # # Copyright (c) Eric R. Jeschke. All rights reserved. # This is open-source software licensed under a BSD license. # Please see the file LICENSE.txt for details. # import os, glob import stat, time from ging...
return bnch def browse(self, path): self.logger.debug("path: %s" % (path)) if os.path.isdir(path): dirname = path globname = None else: dirname, globname = os.path.split(path) dirname = os.path.abspath(dirname) # ...
name): self.fv.show_error("Not a valid path: %s" % (dirname)) return if not globname: globname = '*' path = os.path.join(dirname, globname) # Make a directory listing self.logger.debug("globbing path: %s" % (path)) filelist = list(glo...
citrix-openstack-build/cinder
cinder/tests/test_solidfire.py
Python
apache-2.0
9,057
0.00011
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012 OpenStack LLC. # 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/...
ry: sfv.create_volume(testvol) self.fail("Should have thrown Error") except Exception: pass def test_create_sfaccount(self): sfv = SolidFire() self.stubs.Set(SolidFire, '_issue_api_request', self.fake_issue_api_request) acco...
olidFire, '_issue_api_request', self.fake_issue_api_request_fails) account = sfv._create_sfaccount('project-id') self.assertEqual(account, None) def test_get_sfaccount_by_name(self): sfv = SolidFire() self.stubs.Set(SolidFire, '_issue_api_request', ...
grahamgilbert/Crypt-Server
server/migrations/0018_auto_20201029_2134.py
Python
apache-2.0
873
0
# Generated by Django 2.2.13 on 2020-10-29 21:34 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [("server", "0017_merge_20181217_1829")] operations = [ migrations.AlterField( model_name="computer",
name="serial", field=models.CharField( max_length=200, unique=True, verbose_name="Serial Number" ), ), migrations.AlterField( model_name="secret", name="secret_type", field=models.Ch
arField( choices=[ ("recovery_key", "Recovery Key"), ("password", "Password"), ("unlock_pin", "Unlock PIN"), ], default="recovery_key", max_length=256, ), ), ]
PetePriority/home-assistant
homeassistant/components/device_tracker/tplink.py
Python
apache-2.0
16,061
0
""" Support for TP-Link routers. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/device_tracker.tplink/ """ import base64 from datetime import datetime import hashlib import logging import re from aiohttp.hdrs import ( ACCEPT, COOKIE, PRAGMA, REFERER...
queries a wireless router running TP-Link firmware.""" def __init__(self, config): """Initialize the scanner.""" host = config[CONF_HOST] username, password = c
onfig[CONF_USERNAME], config[CONF_PASSWORD] self.parse_macs = re.compile('[0-9A-F]{2}-[0-9A-F]{2}-[0-9A-F]{2}-' + '[0-9A-F]{2}-[0-9A-F]{2}-[0-9A-F]{2}') self.host = host self.username = username self.password = password self.last_results = ...
bobthebutcher/iosxe
tests/test_iosxe.py
Python
gpl-3.0
1,026
0.003899
""" Tests are performed against csr1000v-universalk9.03.15.00.S.155-2.S-std. """ import unittest from iosxe.iosxe import IOSXE from iosxe.exceptions import AuthError node = '172.16.92.134' username = 'cisco' password = 'cisco' port = 55443 class TestIOSXE(unittest.TestCase): def setUp(self): self.xe = ...
(self): self.assertIsInstance(self.xe, IOSXE) def test_invalid_user_pass_returns_auth_error(self): self.assertRaises(AuthError, IOSXE, node=node, username='stuff', password='things', disable_warnings=True) def test_url_base(self): self.assertEqual(self.xe.url...
lf.xe.token_uri, '/auth/token-services') def test_save_config_success(self): resp = self.xe.save_config() self.assertEqual(204, resp.status_code)
Codex-/Octo-SFTP
OctoSFTP/file.py
Python
mit
4,433
0.000451
import glob import logging import os import shutil from threading import Thread, Lock class ClientFiles: """Processes the clients files to be moved etc""" def __init__(self, settings, clients): self.settings = settings self.clients = clients # Logging self._logger = logging....
self._logger.log(logging.WARNING, file +
" exists. " "Current file removed") try: shutil.move(file, self.settings.local_queue) # self.files.append(os.path.basename(file)) except OSError as error: self._logger.log(logging.CRITICAL, ...
pcu4dros/pandora-core
workspace/lib/python3.5/site-packages/pycparser/c_parser.py
Python
mit
63,805
0.001489
#------------------------------------------------------------------------------ # pycparser: c_parser.py # # CParser class: Parser and AST builder for the C language # # Copyright (C) 2008-2015, Eli Bendersky # License: BSD #------------------------------------------------------------------------------ import re from ...
self._parse_error( "Typedef %r previously decl
ared as non-typedef " "in this scope" % name, coord) self._scope_stack[-1][name] = True def _add_identifier(self, name, coord): """ Add a new object, function, or enum member name (ie an ID) to the current scope """ if self._scope_stack[-1].get(name, Fals...
tectronics/chimerascan
chimerascan/deprecated/nominate_spanning_reads_v01.py
Python
gpl-3.0
5,222
0.003447
''' Created on Jan 30, 2011 @author: mkiyer chimerascan: chimeric transcript discovery using RNA-seq Copyright (C) 2011 Matthew Iyer 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 ...
ead1 is not None) and (read2 is not None): continue # update read fastq r1, r2 = check_fragment(frag, tx5p, tx3p) if read1 is None: read1 = r1 if read2 is None: read2 = r2 prev_qname = qname if read1 is not None: print >>fastq_fh, read1 if read2
is not None: print >>fastq_fh, read2 def main(): from optparse import OptionParser logging.basicConfig(level=logging.DEBUG, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s") parser = OptionParser("usage: %prog [options] <qname_sorted_discordant_reads> <chimeras...
NESCent/dplace
dplace_app/load.py
Python
mit
5,554
0.004681
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys from itertools import groupby from time import time from functools import partial import re import django django.setup() from django.db import transaction from clldutils.dsv import reader from clldutils.text import split_text from clldutils.path import Path fro...
attr.ib() name = attr.ib() year = attr.ib() author = attr.ib() reference = attr.ib() base_dir = attr.ib() @property def dir(self): return self.base_dir.joinpath(self.id) def as_source(self): return Source.objects.create(
**{k: getattr(self, k) for k in 'year author name reference'.split()}) @attr.s class RelatedSociety(object): dataset = attr.ib(convert=lambda s: s.strip()) name = attr.ib(convert=lambda s: s.strip()) id = attr.ib(convert=lambda s: s.strip()) @classmethod def from_string(cls, s): match =...
laufercenter/meld
meld/system/protein.py
Python
mit
7,985
0.004258
# # Copyright 2015 by Justin MacCallum, Alberto Perez, Ken Dill # All rights reserved # import numpy as np import math class ProteinBase(object): ''' Base class for other Protein classes. Provides functionality for translation/rotation and adding H-bonds. ''' def __init__(self): self._t...
d.append((res_index_i, res_index_j,atom_name_i,atom_name_j,bond_type)) def add_disulfide(self, res_index_
i, res_index_j): ''' Add a disulfide bond. :param res_index_i: one-based index of residue i :param res_index_j: one-based index of residue j .. note:: indexing starts from one and the residue numbering from the PDB file is ignored. When loading from a PD...
peap/gnucash_explorer
gnucash_explorer/settings.py
Python
mit
2,089
0
""" Django settings for gnucash_explorer project. For more information on this file, see https://docs.djangoproject.com/en/1.6/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.6/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR...
ontrib.messages', 'django.contrib.staticfiles', ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMid
dleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) ROOT_URLCONF = 'gnucash_explorer.urls' WSGI_APPLICATION = 'gnucash_explorer.wsgi.application' # Database # https://docs.djangoproject.com/en/1.6/ref/settings/#databases DATABASES = ...
russellb/nova
nova/api/openstack/compute/contrib/virtual_storage_arrays.py
Python
apache-2.0
23,474
0.001406
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright (c) 2011 Zadara Storage Inc. # Copyright (c) 2011 OpenStack LLC. # # 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 # # ...
splayName') elem.set('displayDescription') elem.set('createTime') elem.set('status') elem.set('vcType') elem.set('vcCount') elem.set('driveCount') elem.set('ipAddress') class VsaTemplate(xmlutil.TemplateBuilder): def construct(self): root = xmlutil.TemplateElement('vsa', select...
lateElement('vsaSet') elem = xmlutil.SubTemplateElement(root, 'vsa', selector='vsaSet') make_vsa(elem) return xmlutil.MasterTemplate(root, 1) class VsaController(object): """The Virtual Storage Array API controller for the OpenStack API.""" def __init__(self): self.vsa_api = v...
google-research/google-research
non_semantic_speech_benchmark/export_model/tf_pad.py
Python
apache-2.0
2,326
0.007739
# coding=utf-8 # Copyright 2022 The Google Research Authors. # # 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 applicab...
OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """A TensorFlow pad function that works like numpy. Specifically, tf.pad can't more than double the length of a Tensor, while numpy's can. For example: x = np.array(range(3))...
.constant(range(3)) tf.pad(x, [(0, 5)], mode='symmetric') -> fails """ from typing import Union import tensorflow as tf def tf_pad(samples, padding, mode): if samples.shape.ndims != 2: raise ValueError(f'tensor must be rank 2: {samples.shape}') if mode == 'SYMMETRIC': return tf_pad_symmetric(s...
harshilasu/LinkurApp
y/google-cloud-sdk/platform/gcutil/lib/google_compute_engine/gcutil_lib/mock_api_parser.py
Python
gpl-3.0
7,467
0.006964
# Copyright 2013 Google 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 a...
y_object_type): """Parses properties of a discovery document object tyoe.""" assert discovery_object_type.get('type') == 'object' properties = [] for property_name, property_type in ( discovery_object_type.get('properties', {}).iteritems()): properties.append(mock_api_types.Property( ...
name, self._ParseType(property_type))) additional = None additional_properties = discovery_object_type.get('additionalProperties') if additional_properties is not None: additional = self._ParseType(additional_properties) return properties, additional def _ParseSchemas(self, discovery_schemas):...
OCA/event
event_mail/models/__init__.py
Python
agpl-3.0
482
0
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from . import res_co
mpany # WARNING: Order of imports matters on this module, so don't put res_company # below the other modules since it will lead to a missing column error when # the module is initialized for the first time since there are fields with # default values wich refer to this new res.company field. from . import event from ....
pe from . import res_config_settings
SalmonMode/contextional
contextional/test_resources/verbose_fixtures.py
Python
mit
7,418
0
from contextional import GCM with GCM("A") as A: @GCM.add_setup def setUp(): pass @GCM.add_teardown def tearDown(): pass with GCM.add_group("B"): @GCM.add_setup def setUp(): pass @GCM.add_test("some test") def test(case): ...
("teardown w/ description") def tearD
own(): pass A.create_tests() with GCM("A") as A: @GCM.add_setup("setup w/ description") def setUp(): pass @GCM.add_teardown("teardown w/ description") def tearDown(): pass with GCM.add_group("B"): @GCM.add_setup("setup w/ description") def setUp():...
zzeleznick/zDjango
Poller/urls.py
Python
mit
396
0.002525
from django.conf.urls import include, url from django.contrib import admin from Poller import views urlpatterns = [ url(r'^$', views.IndexView.as_view(), name='index'), url(r'^(?P<pk>\d+)/$', views.DetailView.as_view(), name='detail'), url(r'^(?P<pk>\d+)/results/$', views.ResultsView.as_view()
, name='results'), url(r'^(?P<question_id>\d+)/vote/$', views.vote, name='vote'),
]
mainakibui/kobocat
onadata/apps/logger/management/commands/sync_deleted_instances_fix.py
Python
bsd-2-clause
1,551
0
#!/usr/bin/env python # vim: ai ts=4 sts=4 et sw=4 fileencoding=utf-8 import json from django.conf import settings from django.core.management import BaseCommand from django.utils import timezone from django.utils.dateparse import parse_datetime from django.utils.
translation import ugettext_lazy from onadata.apps.logger.models import Instance class Command(BaseCommand): help = ugettext_lazy("Fixes deleted instances by syncing " "deleted items from mongo.") def handle(self, *args, **kwargs): # Reset all sql deletes to None Ins...
jects.exclude( deleted_at=None, xform__downloadable=True).update(deleted_at=None) # Get all mongo deletes query = '{"$and": [{"_deleted_at": {"$exists": true}}, ' \ '{"_deleted_at": {"$ne": null}}]}' query = json.loads(query) xform_instances = settings.MONGO_...
hantek/BinaryConnect
cifar10.py
Python
gpl-2.0
9,943
0.023836
# Copyright 2015 Matthieu Courbariaux, Zhouhan Lin """ This file is adapted from BinaryConnect: https://github.com/MatthieuCourbariaux/BinaryConnect Running this script should reproduce the results trained on CIFAR10 shown in the paper. To train a vanilla ConvNet with ordinary backprop: 1. type "g...
n2_gcn_whitened/train.pkl"), preprocessor = preprocessor, start=0, stop = 45000) valid_set = ZCA_Dataset( preprocessed_dataset= serial.load("${PYLEARN2_DATA_PATH}/cifar10/pylearn2_gcn_whitened/train.pkl"), preprocessor = preprocessor, start=45000, stop = 50000) ...
et = ZCA_Dataset( preprocessed_dataset= serial.load("${PYLEARN2_DATA_PATH}/cifar10/pylearn2_gcn_whitened/test.pkl"), preprocessor = preprocessor) # bc01 format # print train_set.X.shape train_set.X = train_set.X.reshape(45000,3,32,32) valid_set.X = valid_set.X.reshape(5000,3...
wrobell/btzen
btzen/bluez.py
Python
gpl-3.0
1,239
0
# # BTZen - library to asynchronously access Bluetooth devices. # # Copyright (C) 2015-2021 by Artur Wroblewski <wrobell@riseup.net> # # 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 vers...
on) any later version. # # This program is distributed in 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 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, see <http://www.gnu.org/licenses/>. # """ Bluetooth services implemented by BlueZ protocol stack. """ from .data import Make, ServiceType, Trigger, TriggerCo...
soltanmm-google/grpc
tools/run_tests/run_interop_tests.py
Python
bsd-3-clause
33,477
0.009111
#!/usr/bin/env python2.7 # Copyright 2015, Google 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: # # * Redistributions of source code must retain the above copyright # notice, this lis...
me(sys.argv[0]), '../..')) os.c
hdir(ROOT) _DEFAULT_SERVER_PORT=8080 _SKIP_CLIENT_COMPRESSION = ['client_compressed_unary', 'client_compressed_streaming'] _SKIP_SERVER_COMPRESSION = ['server_compressed_unary', 'server_compressed_streaming'] _SKIP_COMPRESSION = _SKIP_CLIENT_COMPRESSION + _SKI...
gmist/ctm-5studio
main/auth/yahoo.py
Python
mit
2,148
0.008845
# coding: utf-8 from __future__ import absolute_import import flask import auth import model import util from main import app yahoo_config = dict( access_token_url='https://api.login.yahoo.com/oauth/v2/get_token', authorize_url='https://api.login.yahoo.com/oauth/v2/request_auth', base_url='https://query.yaho...
oo/') def yahoo_authorized(): response = yahoo.authorized_response() if response is None: flask.flash('You denied the request to sign in.') return flask.redirect(util.get_next_url()) flask.session['oauth_token'] = ( response['oauth_token'], response['oauth_token_secret'], ) fields = 'guid, e...
ocial.profile where guid = me;' % fields, 'realm': 'yahooapis.com', }, ) user_db = retrieve_user_from_yahoo(me.data['query']['results']['profile']) return auth.signin_user_db(user_db) @yahoo.tokengetter def get_yahoo_oauth_token(): return flask.session.get('oauth_token') @app.route('/signin/yahoo/...
widelands/widelands
cmake/codecheck/rules/assert0.py
Python
gpl-2.0
293
0
#!/usr/bin/env python -tt # encoding: utf-8 # """Use a descriptive macro ins
tead of assert(fa
lse);""" error_msg = 'Use NEVER_HERE() from base/macros.h here.' regexp = r"""assert *\( *(0|false) *\)""" forbidden = [ 'assert(0)', 'assert(false)', ] allowed = [ 'NEVER_HERE()', ]
hperala/kontuwikibot
mwparserfromhell/string_mixin.py
Python
mit
4,073
0.000491
# -*- coding: utf-8 -*- # # Copyright (C) 2012-2016 Ben Kurtovic <ben.kurtovic@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software
"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copi
es of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY ...
gEt-rIgHt-jR/voc
voc/python/types/python.py
Python
bsd-3-clause
8,387
0.000119
from ...java import opcodes as JavaOpcodes, Classref as JavaClassref from . import java as Java ########################################################################## # Python types and their operations ########################################################################## class Callable: class invoke: ...
java/lang/Class;'], returns='Lorg/python/types/Type;' ) ) clas
s for_name: def __init__(self, name): self.name = name def process(self, context): context.add_opcodes( JavaOpcodes.LDC_W(self.name), JavaOpcodes.INVOKESTATIC( 'org/python/types/Type', 'pythonType', ...
chatcannon/scipy
benchmarks/benchmarks/go_benchmark_functions/go_funcs_B.py
Python
bsd-3-clause
21,639
0.000185
# -*- coding: utf-8 -*- from __future__ import division, print_function, absolute_import from numpy import abs, cos, exp, log, arange, pi, roll, sin, sqrt, sum from .go_benchmark import Benchmark class BartelsConn(Benchmark): r""" Bartels-Conn objective function. The BartelsConn [1]_ global optimizatio...
ith :math:`x_i \in [-500, 500]` for :math:`i = 1, 2`. *Global optimum*: :math:`f(x) = 1` for :math:`x = [0, 0]` .. [1] Jamil, M. & Yang, X.-S. A Literature Survey of Benchmark Functions For Global Optimization Problems Int. Journal of Mathematical Modelling and Numerical Optimisation, 2013, 4, 150-194...
self._bounds = zip([-500.] * self.N, [500.] * self.N) self.global_optimum = [[0 for _ in range(self.N)]] self.fglob = 1.0 def fun(self, x, *args): self.nfev += 1 return (abs(x[0] ** 2.0 + x[1] ** 2.0 + x[0] * x[1]) + abs(sin(x[0])) + abs(cos(x[1]))) class Beal...
apanda/NetBricks
scripts/tuning/read_cpu_dma_latency.py
Python
isc
588
0.022109
#!/usr/bin/python import os import signal import struct import sys import time A
LLOWED_INTERFACES = [ "cpu_dma_latency", "network_latency", "network_throughput" ] def read_pmqos(name): filename = "/dev/%s" % name old = open(filename) old_value = struct.unpack("i", old.read())[0] print "PMQOS value for %s is %d"%(name, old_value) if __name__=="__main__": if len(sys.argv) < 2: print ...
ALLOWED_INTERFACES: print "Cannot read %s"%read sys.exit(1) read_pmqos(read)
yfede/gimp-plugin-export-layers
export_layers/pylibgimpplugin/tests/test_settings.py
Python
gpl-3.0
23,801
0.013361
#------------------------------------------------------------------------------- # # This file is part of pylibgimpplugin. # # Copyright (C) 2014 khalim19 <khalim19@gmail.com> # # pylibgimpplugin is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published ...
', "") def test_changed_attributes(self): for attr, val in [('value', "png"), ('ui_enabled', False), ('ui_visible', True)]: setattr(self.setting,
attr, val) for attr in ['value', 'ui_enabled', 'ui_visible']: self.assertTrue(attr in self.setting.changed_attributes, msg=("'" + attr + "' not in " + str(self.setting.changed_attributes))) def test_can_be_registered_to_pdb(self): self.setting.gimp_pdb_type = gimpenums.PDB_...
xaratustrah/iq_suite
iqtools/tools.py
Python
gpl-2.0
10,337
0.000871
""" Collection of tools for the IQTools library Xaratustrah 2017 """ import os import logging as log from scipy.signal import hilbert from scipy.io import wavfile import xml.etree.ElementTree as et import numpy as np import types import uproot3 import uproot3_methods.classes.TH1 from iqtools.iqbase import IQBase fr...
tor to write to filename fs: sampling Frequency center: center Frequency write_header: if set to true, then the first 4 bytes of the file are 32-bit sampling Frequency and then follows the center frequency also in 32-bit. the Data follows afterwards in I, Q format each 32-bit as well. """ # ...
oats # insert header if write_header: cx = np.insert(cx, 0, complex(fs, center)) cx = cx.astype(np.complex64) cx.tofile(filename + '.bin') def write_signal_to_csv(filename, cx, fs=1, center=0): # insert ascii header which looks like a complex number cx = np.insert(cx, 0, complex(fs, ce...
amolkahat/pandas
pandas/core/groupby/generic.py
Python
bsd-3-clause
58,252
0.000223
""" Define the SeriesGroupBy, DataFrameGroupBy, and PanelGroupBy classes that hold the groupby interfaces (and some implementations). These are user facing as the result of the ``df.groupby(...)`` operations, which here returns a DataFrameGroupBy object. """ import collections import copy import warnings from functoo...
axis != obj._info_axis_number: try: for name, data in self: result[name] = self._try_cast(func(data, *args, **kwargs), data) except Exception: return self._aggregate_item_by_item(func, *args, **...
= self._try_cast(func(data, *args, **kwargs), data) except Exception: wrapper = lambda x: func(x, *args, **kwargs) result[name] = data.apply(wrapper, axis=axis) return self._wrap_generic_output(result, obj...
harmsm/thefarm
thefarm/farm.py
Python
mit
853
0.009379
import json, logging class Farm:
""" Main class holding the who
le farm. """ def __init__(self,json_file): """ """ # load in json file data = json.loads(open(json_file,'r').read()) # Make sure required data is in the json file required_attr_list = ["latitude","longitude"] for a in required_attr_list: if...
hidat/audio_pipeline
audio_pipeline/test/TagFormatTest.py
Python
mit
12,551
0.006454
import os import unittest import mutagen import shutil import audio_pipeline.test.References as ref from . import TestUtil from ..util import format vorbis_files = dict(t1=os.path.join(ref.format_testing_audio, "t1.flac"), picard=os.path.join(ref.format_testing_audio, "picard.flac"), ...
class TestReadGenericTag
sVorbis_picard(TestReadGenericTags, unittest.TestCase): @classmethod def setUpClass(self): self.meta = mutagen.File(vorbis_files["picard"]) self.tags = ref.picard_tags self.format = format.Vorbis.Format class TestReadGenericTagsVorbis_NOMETA(TestReadGenericTags, unittest....
davelab6/pyfontaine
fontaine/charsets/noto_glyphs/notokufiarabic_regular.py
Python
gpl-3.0
33,355
0.022875
# -*- coding: utf-8 -*- class Charset(object): common_name = 'NotoKufiArabic-Regular' native_name = '' def glyphs(self): glyphs = [] glyphs.append(0x0261) #uni0759.fina glyphs.append(0x007F) #uni0625 glyphs.append(0x00D4) #uni0624 glyphs.append(0x0005) #uni0627...
d(0x018A) #uni06A0.medi
glyphs.append(0x01AC) #uni06AC.fina glyphs.append(0x018E) #uni06A2.init glyphs.append(0x0088) #uni0628.fina glyphs.append(0x00F0) #uni06C2.fina glyphs.append(0x0196) #uni06A4.medi glyphs.append(0x0295) #uni0767.medi glyphs.append(0x0141) #uni0682.init gl...
GabrielFortin/ansible-module-f5bigip
library/f5bigip_ltm_traffic_class.py
Python
apache-2.0
5,265
0.002849
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright 2016-2018, Eric Jacob <erjac77@gmail.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/LICENS...
=dict(type='str'), classification=dict(type='str'), description=dict(type='str'), destination_address=dict(type='str'), destination_mask=dict(type='str'), destination_port=dict(type='int'), file_name=dict(type='str'), protocol=dict(type...
type='str'), source_port=dict(type='int') ) argument_spec.update(F5_PROVIDER_ARGS) argument_spec.update(F5_NAMED_OBJ_ARGS) return argument_spec @property def supports_check_mode(self): return True class F5BigIpLtmTrafficClass(F5BigIpNamedObject): def _s...
garrettr/securedrop
securedrop/tests/test_db.py
Python
agpl-3.0
2,826
0
# -*- coding: utf-8 -*- from flask_testing import TestCase import mock import journalist from utils import db_helper, env from db import (Journalist, Submission, Reply, get_one_or_else, LoginThrottledException) class TestDatabase(TestCase): def create_app(self): return journalist.app ...
Journalist.throttle_login(journalist)
mitsuhiko/fungiform
setup.py
Python
bsd-3-clause
1,459
0.020562
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Fungiform ~~~~~~~~~ A form handling system that previously was used for Pocoo's Zine and Plurk's Solace software. Unbundled into a separate library that is framework independent. This is still a preview release. Check the source for more info...
etuptools import setup except ImportError: from distutils.core i
mport setup setup( name = 'Fungiform', version = '0.2', url = 'http://github.com/mitsuhiko/fungiform', license = 'BSD License', author = 'Armin Ronacher', author_email = 'armin.ronacher@active-4.com', description = 'form library', long_description = __doc__, keywords = 'form librar...
bernard357/shellbot
shellbot/stores/sqlite.py
Python
apache-2.0
5,489
0
# -*- coding: utf-8 -*- # 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 "Li...
this bot. """ assert prefix self.prefix = prefix self.id = id if id else '*id' if db: self.context.set(self.prefix+'.db', db) def check(self): """ Checks configuration """ self.context.check(self.prefix+'.db', 'store.db') de...
= self.context.get(self.prefix+'.db', 'store.db') return sqlite3.connect(db) def bond(self, id=None): """ Creates or uses a file to store data :param id: the unique identifier of the related space :type id: str """ if id: self.id = id ...
xmedius/xmedius-mailrelayserver
xmediusmailrelayserver/__init__.py
Python
mit
38
0.026316
from xmediu
smailrela
yserver import *
singingwolfboy/flask-dance
tests/contrib/test_reddit.py
Python
mit
3,475
0.001151
import pytest import responses from urlobject import URLObject from flask import Flask from flask_dance.contrib.reddit import make_reddit_blueprint, reddit from flask_dance.consumer import OAuth2ConsumerBlueprint from flask_dance.consumer.storage import MemoryStorage @pytest.fixture def make_app(): "A callable to...
(responses.GET, "https://google.com") # set up two apps with two d
ifferent set of auth tokens app1 = make_app( "foo1", "bar1", redirect_to="url1", storage=MemoryStorage({"access_token": "app1"}), ) app2 = make_app( "foo2", "bar2", redirect_to="url2", storage=MemoryStorage({"access_token": "app2"}), ) ...
CPedrini/TateTRES
erapi.py
Python
apache-2.0
11,009
0.004906
#-*- encoding: utf-8 -*- import csv, math, time, re, threading, sys try: from urllib.request import urlopen except ImportError: from urllib import urlopen class ErAPI(): # Metodo constructor, seteos basicos necesarios de configuracion, instancia objetos utiles def __init__(self): self.data = ...
2000, "Commander**": 67000, "Commander***": 85000, "Lt Colonel": 110000, "Lt Colonel*": 140000, "Lt Colonel**": 180000,
"Lt Colonel***": 225000, "Colonel": 285000, "Colonel*": 355000, "Colonel**": 435000, "Colonel***": 540000, "General": 660000, "General*": 800000, "General**": 950000, "General***": 1140000, "Field Marshal": 135...
manhhomienbienthuy/scikit-learn
examples/linear_model/plot_omp.py
Python
bsd-3-clause
2,054
0.000974
""" =========================== Orthogonal Matching Pursuit =========================== Using orthogonal matching pursuit for recovering a sparse signal from a noisy measurement encoded with a dictionary """ import matplotlib.pyplot as plt import numpy as np from sklearn.linear_model import OrthogonalMatchingPursuit...
fs, normalize=False) omp.fit(X, y) coef = omp.coef_ (idx_r,) = coef.nonzero() plt.subplot(4, 1, 2) plt.xlim(0, 512) plt.title("Recovered signal from noise-free measurements") plt.
stem(idx_r, coef[idx_r], use_line_collection=True) # plot the noisy reconstruction omp.fit(X, y_noisy) coef = omp.coef_ (idx_r,) = coef.nonzero() plt.subplot(4, 1, 3) plt.xlim(0, 512) plt.title("Recovered signal from noisy measurements") plt.stem(idx_r, coef[idx_r], use_line_collection=True) # plot the noisy reconstr...
Crowdcomputer/CroCoAPI
ui/views.py
Python
gpl-2.0
3,534
0.005376
import logging from django.contrib import messages from django.contrib.auth import authenticate from django.core.urlresolvers import reverse from django.http.response import Http404, HttpResponseRedirect from django.shortcuts import render, redirect, render_to_response # Create your views here. from django.template.co...
key+"&id="+crowduser.user.pk return HttpResponseRedirect(redirect_to) else: app = App.objects.get(callback=callback) return render_to_response('ui/app.html', {'app': app,'callback':callback,'token':token}, context_instance=RequestCont
ext(request))
tsileo/blobstash-python-docstore
blobstash/docstore/attachment.py
Python
mit
2,286
0.002625
"""Attachment utils.""" from pathlib import Path from uuid import uuid4 from blobstash.docstore.error import DocStoreError from blobstash.filetree import FileTreeClient _FILETREE_POINTER_FMT = "@filetree/ref:{}" _FILETREE_ATTACHMENT_FS_PREFIX = "_filetree:docstore" class Attachment: """An attachment represents ...
nt(pointer, node) def fadd_attachment(client, name, fileobj, content_type=None): """Creates a new attachment from the fileobj content with name as filename and returns a pointer object.""" node = FileTreeClient(client=client).fput_node(n
ame, fileobj, content_type) pointer = _FILETREE_POINTER_FMT.format(node.ref) return Attachment(pointer, node) def fget_attachment(client, attachment): """Returns a fileobj (that needs to be closed) with the content off the attachment.""" node = attachment.node if node.is_dir(): raise DocSt...
demharters/git_scripts
calc_movement_HO.py
Python
apache-2.0
795
0.021384
#! /usr/bin/python import MDAnalysis import sys from pylab import * my_traj = sys.argv[1] myTitle = sys.argv[2] u = MDAnalysis.Universe(my_traj,my_traj) OH = u.selectAtoms("segid B and resid 18 and name HO") xArr = [] yArr = [] zArr = [] data = [] for ts in u.trajectory: xArr.append(OH.coordinates()[0,0]) ...
a.append(newArray) boxplot(data) xticks([1,2,3],["x","y","z"]) ylim(-0.4,0.4) title("%s_HO"%myTitle)
savefig("%s_HO.png"%myTitle)
Madpilot0/Flask-Simpleauth
lib/Users.py
Python
gpl-3.0
1,789
0.035774
from flask import Flask, render_template, request, jsonify, session, redirect, escape, url_for import bcrypt class ServerError(Exception):pass def loginForm(db, form): error = None try: username = form['username'] cur = db.query("SELECT COUNT(1) FROM users WHERE user = %s", [username]) if not cur.fetchone()...
cur = db.query("SELECT COUNT(*) FROM users WHERE user = %s",[username]) c = cur.fetchone() if c[0] == 0: cur = db.query("INSERT INTO users (`user`, `email`, `pass`) VALUES (%s,%s,%s)", [username, email, password]) return None else: return "User exists" except ServerError as e: error = str(e) retu...
r = None try: userlist = [] cur = db.query("SELECT user, email FROM users") for row in cur.fetchall(): userlist.append({'name': row[0], 'email': row[1]}) return userlist except: error = "Failed" return error def deleteUser(db, user): error = None try: cur = db.query("DELETE FROM users WHERE user =...
taedori81/e-commerce-template
saleor/product/migrations/0001_initial.py
Python
bsd-3-clause
7,464
0.005761
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import versatileimagefield.fields import jsonfield.fields from decimal import Decimal import saleor.product.models.fields import django.core.validators import django_prices.models import satchless.item class Migr...
leimagefield.fields.
PPOIField(default='0.5x0.5', max_length=20, editable=False)), ('alt', models.CharField(max_length=128, verbose_name='short description', blank=True)), ('order', models.PositiveIntegerField(editable=False)), ('product', models.ForeignKey(related_name='images', to='product....
pcu4dros/pandora-core
workspace/lib/python3.5/site-packages/psycopg2/errorcodes.py
Python
mit
13,241
0.000076
"""Error codes for PostgresSQL This module contains symbolic names for all PostgreSQL error codes. """ # psycopg2/errorcodes.py - PostgreSQL error codes # # Copyright (C) 2006-2010 Johan Dahlin <jdahlin@async.com.br> # # psycopg2 is free software: you can redistribute it and/or modify it # under the terms of the GNU ...
UTINE_EXCEPTION = '38' CLASS_EXTERNAL_ROUTINE_INVOCATION_EXCEPTION = '39' CLASS_SAVEPOI
NT_EXCEPTION = '3B' CLASS_INVALID_CATALOG_NAME = '3D' CLASS_INVALID_SCHEMA_NAME = '3F' CLASS_TRANSACTION_ROLLBACK = '40' CLASS_SYNTAX_ERROR_OR_ACCESS_RULE_VIOLATION = '42' CLASS_WITH_CHECK_OPTION_VIOLATION = '44' CLASS_INSUFFICIENT_RESOURCES = '53' CLASS_PROGRAM_LIMIT_EXCEEDED = '54' CLASS_OBJECT_NOT_IN_PREREQUISITE_ST...
Eraldo/django-autocomplete-light
src/dal_queryset_sequence/fields.py
Python
mit
4,390
0
"""Autocomplete fields for QuerySetSequence choices.""" from dal_contenttypes.fields import ( ContentTypeModelMultipleFieldMixin, GenericModelMixin, ) from django import forms from django.contrib.contenttypes.models import ContentType from queryset_sequence import QuerySetSequence class QuerySetSequenceFie...
_id) if queryset is None: self.raise_invalid_choice() try: return queryset.get(pk=object_id) except queryset.model.DoesNotExist: self.raise_invalid_choice() class QuerySetSequenceModelMultipleField(ContentTypeModelMultipleFieldMixin, ...
Field with support for QuerySetSequence choices.""" def _deduplicate_values(self, value): # deduplicate given values to avoid creating many querysets or # requiring the database backend deduplicate efficiently. try: return frozenset(value) except TypeError: #...
atmtools/typhon
typhon/utils/sphinxext.py
Python
mit
1,221
0
# -*- coding: utf-8 -*- """This module contains custom roles to use in Sphinx. """ from docutils import nodes def setup(app): """Install the extension. Parameters: app: Sphinx application context. """ app.add_role('arts', arts_docserver_role) def arts_docserver_role(name, rawtext, text, li...
instance that called us. optio
ns (dict): Directive options for customization. content (list): The directive content for customization. Returns: list, list: Nodes to insert into the document, System messages. """ if content is None: content = [] if options is None: options = {} url = 'http://radiat...
dana-i2cat/felix
expedient/src/python/expedient/common/federation/geni/ch.py
Python
apache-2.0
15,839
0.00423
#---------------------------------------------------------------------- # Copyright (c) 2010 Raytheon BBN Technologies # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and/or hardware specification (the "Work") to # deal in the Work without restriction, including witho...
r, keyfile, certfile,
ca_certs_onefname) self._server.register_instance(SampleClearinghouseServer(self)) self.logger.info('GENI CH Listening on port %d...' % (addr[1])) self._server.serve_forever() def _make_server(self, addr, keyfile=None, certfile=None, ...
afronski/playground-other
python/books/learn-python-the-hard-way/projects/ex48/ex48/parser.py
Python
mit
1,663
0.004811
class ParserError(Exception): pass class Sentence(object): def __init__(self, subject, verb, obj): # We take ('noun','thing') tuples and convert them. self.subject = subject[1] self.verb = verb[1] self.object = obj[1] def peek(word_list): if word_list: word = word_...
un': return match(word_list, 'noun') elif next_word == 'verb': return ('noun
', 'player') else: raise ParserError("Expected a verb next.") def parse_sentence(word_list): subj = parse_subject(word_list) verb = parse_verb(word_list) obj = parse_object(word_list) return Sentence(subj, verb, obj)
edx-solutions/edx-platform
lms/djangoapps/instructor/tests/views/test_instructor_dashboard.py
Python
agpl-3.0
27,999
0.002357
""" Unit tests for instructor_dashboard.py. """ import datetime import re import ddt import six from django.conf import settings from django.contrib.sites.models import Site from django.test.utils import override_settings from django.urls import reverse from mock import patch from pyquery import PyQuery as pq from p...
hows up for certain roles """ download_section = '<li class="nav-item"><button type="button" class="btn-link data_download" '\ 'data-section="data_download">Data Download</button></li>' user = UserFactory.create(is_st
aff=access_role == 'global_staff') CourseAccessRoleFactory( course_id=self.course.id, user=user, role=access_role, org=self.course.id.org ) self.client.login(username=user.username, password="test") response = self.client.get(self.url) ...
gtest-org/test10
jenkins_jobs/modules/zuul.py
Python
apache-2.0
6,120
0.00049
# Copyright 2012 Hewlett-Packard Development Company, L.P. # # 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...
OLDREV'}}, {'string': {'description': 'Zuul provided new reference for
ref-updated', 'name': 'GERRIT_NEWREV'}}, {'string': {'description': 'New SHA at this reference', 'name': 'ZUUL_NEWREV'}}, {'string': {'description': 'Shortened new SHA at this reference', 'name': 'ZUUL_SHORT_NEWREV'}}, ] DEFAULT_URL = 'http://127.0.0.1:8001/jenkins_e...
lidel/mmda
tags/urls.py
Python
cc0-1.0
145
0.006897
from django.conf.urls.defaults import * urlpatterns =
patterns('mmda.tags.views', url(r'^(?P<tag_id>.+?)/$'
, 'show_tag', name='show-tag') )
MariaSolovyeva/inasafe
safe/impact_functions/generic/continuous_hazard_population/impact_function.py
Python
gpl-3.0
10,346
0
# coding=utf-8 """ InaSAFE Disaster risk assessment tool by AusAid - **Generic Impact Function on Population for Continuous Hazard.** Contact : ole.moller.nielsen@gmail.com .. note:: This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as publi...
uousHazardPopulationFunction(ContinuousRHContinuousRE): # noinspection PyUnresolvedRef
erences """Plugin for impact of population as derived by continuous hazard.""" _metadata = ContinuousHazardPopulationMetadata() def __init__(self): super(ContinuousHazardPopulationFunction, self).__init__() self.impact_function_manager = ImpactFunctionManager() # AG: Use the proper...
Laurawly/tvm-1
tests/python/contrib/test_cutlass.py
Python
apache-2.0
18,515
0.002268
# 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...
, inp) rt_mod.run() return rt_mod.get_output(0).asnumpy() def get_output_vm(vm, names, in
puts): params = dict(zip(names, inputs)) return vm.invoke("main", **params).numpy() def get_dense_with_shape(data_shape, weight_shape, out_dtype="float16"): data = relay.var("data", shape=data_shape, dtype="float16") weight = relay.var("weight", shape=weight_shape, dtype="float16") return relay.nn...
rafasashi/userinfuser
serverside/fantasm/utils.py
Python
gpl-3.0
4,909
0.006926
""" Fantasm: A taskqueue-based Finite State Machine for App Engine Python Docs and examples: http://code.google.com/p/fantasm/ Copyright 2010 VendAsta Technologies 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 ob...
se for the specific language governing permissions and limitations under the License. """ from fantasm import constants from google.appengine.api.taskqueue.taskqueue import Queue class NoOpQueue( Queue ): """ A Queue instance that does not Queue """ def add(self, task, transactional=False): """...
nction for integers.""" return (number * 2654435761) % 2**32 def boolConverter(boolStr): """ A converter that maps some common bool string to True """ return {'1': True, 'True': True, 'true': True}.get(boolStr, False) def outputAction(action): """ Outputs the name of the action @param action...
enthought/etsproxy
enthought/plugins/remote_editor/i_remote_shell.py
Python
bsd-3-clause
114
0
# proxy module from __future__ import absolute_import from envisage.plugins.remote_editor.i_remote_shell import
*
ideascube/pibox-installer
ansiblecube/tests/conftest.py
Python
gpl-3.0
733
0
import os def get_files(extension): for root, dirnames, filenames in os.walk("."): for filename in filenames: if filename.endswith(extension): yield os.path.join(root, filename) def get_roles(): return sorted(os.listdir("./roles")) def pytest_generate_tests(metafunc): ...
.fixturenames: metafunc.parametrize("jinja2_file", get_files(".j2")) if "json_file" in metafunc.fixturenames: metafunc.parametrize("json_file", get_files(".json")) if "ini_file" in metafunc.fixturenames: metafunc.parametrize("ini_file", get_files(".fact")) if "role" in metafunc.
fixturenames: metafunc.parametrize("role", get_roles())
oldani/nanodegree-blog
app/models/datastore_adapter.py
Python
mit
2,094
0
from flask_user import DBAdapter class DataStoreAdapter(DBAdapter): """ An Wrapper to be use by Flask User to interact with the database in this case, the DataStore """ def __init__(self, db, objMOdel): super().__init__(db, objMOdel) def get_object(self, ObjectClass, pk): """ Ret...
return ObjectClass.fetch() def find_first_object(self, ObjectClass, **kwargs): """ Retrieve the first Entity matching the filters in kwargs or None. """ # TODO: # The filters should be case sensitive for field, value in kwargs.items(): ObjectClass.add_query_filte...
"" Retrieve the first Entity matching the filters in kwargs or None. """ # TODO: # The filters should be case insensitive for field, value in kwargs.items(): ObjectClass.add_query_filter(field, "=", value) entity = ObjectClass.fetch(limit=1) return entity ...
bgruening/gemini
gemini/tool_homozygosity_runs.py
Python
mit
7,165
0.00321
from __future__ import absolute_import import os import sys from collections import defaultdict from .gemini_constants import * from . import GeminiQuery class Site(object): def __init__(self, row): self.chrom = row['chrom'] self.end = int(row['end']) self.gt_type = None def _prune_run(ru...
y = "SELECT chrom, start, end, gt_types, gt_depths \ FROM variants \ WHERE type = 'snp' \ AND filter is NULL \ AND depth >= " + str(args.min_total_depth) + \ " ORDER BY chrom, end" sys.stderr.write("LOG: Querying and ordering variants by ch...
_genotypes=True) print("\t".join(['chrom', 'start', 'end', 'sample', 'num_of_snps','density_per_kb', 'run_length_in_bp'])) variants_seen = 0 samples = defaultdict(list) prev_chrom = None curr_chrom = None for row in gq: variants_seen += 1 if variants_see...
gamesbrewer/kegger
kegger/myapp/flaskmyappname/models.py
Python
cc0-1.0
496
0.008065
from google.appengine.ext import ndb class Users(ndb.Model): password = ndb.StringProperty(required=True) full_name = ndb.StringProperty(required=True) phone_no = ndb.StringProperty(required=False) timestamp = ndb.DateTimeProperty(auto_now
_add=True) @classmethod def query_user(cls, ancestor_key): return cls.query(ancestor=ancestor_key).order(c
ls.full_name) @classmethod def user_key(cls, user_email): return ndb.Key('MyAppName_User', user_email)
hanlin-he/UTD
leetcode/py/053.py
Python
mit
1,020
0.013725
# 053. Maximum Subarray # The simple O(n) solution. import unittest class Solution(object): def maxSubArray(self, nums)
: """ :type nums: List[int] :rtype: int """ ret = nums[0] pre = nums[0] for i in nums[1:]: if ret < i and ret < 0: ret = pre = i continue cur = pre + i if ret < cur: ret = pre = cu...
pre = cur continue # if cur < 0: # Better start over. pre = 0 return ret class SolutionUnitTest(unittest.TestCase): def setup(self): pass def tearDown(self): pass def testMaxSubArray(self): s = Solution() self.asser...
nacl-webkit/chrome_deps
tools/telemetry/telemetry/trace_event_importer.py
Python
bsd-3-clause
386
0.015544
# Copyright (c) 2012 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. impor
t json from telemetry import timeline_model def Import(data): trace = json.loads(data) # pylint: disable=W0612 model = timeli
ne_model.TimelineModel() # TODO(nduca): Actually import things. return model
SEL-Columbia/commcare-hq
corehq/apps/adm/reports/__init__.py
Python
bsd-3-clause
6,857
0.003354
import logging from django.core.urlresolvers import reverse from django.utils.safestring import mark_safe from corehq.apps.adm.dispatcher import ADMSectionDispatcher from corehq.apps.adm.models import REPORT_SECTION_OPTIONS, ADMReport from corehq.apps.reports.datatables import DataTablesHeader, DataTablesColumn, DTSort...
base_template = "reports/base_template.html" dispatcher = ADMSectionDispatcher fix_left_col = True fields = ['corehq.apps.reports.filters.users.UserTypeFilter',
'corehq.apps.reports.filters.select.GroupFilter', 'corehq.apps.reports.filters.dates.DatespanFilter'] hide_filters = False # adm-specific stuff adm_slug = None @property @memoized def subreport_data(self): default_subreport = ADMReport.get_default(self.subreport_s...
Z2PackDev/TBmodels
tests/test_constructors.py
Python
apache-2.0
8,064
0.00124
#!/usr/bin/env python # (c) 2015-2018, ETH Zurich, Institut fuer Theoretische Physik # Author: Dominik Gresch <greschd@gmx.ch> """ Test the Model constructors. """ import itertools import pytest import numpy as np import tbmodels def test_on_site_too_long(get_model): """ Check that error is raised when th...
an error is raised when the given hoppings do not correspond to a hermitian Hamiltonian. """ with pytest.raises(ValueError): tbmodels.Model( size=2, hop={(0, 0, 0): np.eye(2), (1, 0, 0): np.eye(2), (-1, 0, 0): 2 * np.eye(2)}, ) def test_wrong_key_length(): """ ...
size=2, hop={(0, 0, 0): np.eye(2), (1, 0, 0): np.eye(2), (-1, 0, 0, 0): np.eye(2)}, contains_cc=False, ) def test_wrong_pos_length(): """ Check that an error is raised when the number of positions does not match the given size. """ with pytest.raises(ValueError...
yephper/django
tests/admin_docs/views.py
Python
bsd-3-clause
404
0
from django.contrib.admindocs.middleware import XViewMiddleware from django.http import HttpResponse from django.utils.decorators import decorator_from_middleware from django.views.generic import View xview_dec = decorator_from_middleware(XViewMiddleware) def xvie
w(request): return HttpResponse() class XViewClas
s(View): def get(self, request): return HttpResponse()
klashxx/PyConES
rspace/rspace/docs/conf.py
Python
mit
1,487
0.001346
# -*- coding: utf-8 -*- #pylint: skip-file import sys import os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.inser...
o_documents = [ ('index'
, 'rspace', u'cptab Docs', u'Juan Diego Godoy Robles', 'rspace', 'PyConES 2016 - Almería', 'Miscellaneous'), ]
paddycarey/stretch
stretch/exceptions.py
Python
mit
710
0
class StretchException(Exception): """Common base class for all exceptions raised explicitly by stretch. Exceptions which are subclasses of this type will be handled nicely by stretch and will not cause the program to exit. Any exceptions raised
which are not a subclass of this type will exit(1) and print a traceback to stdout. """ level = "error" def __init__(self, message, **kwarg
s): Exception.__init__(self, message) self.message = message self.kwargs = kwargs def format_message(self): return self.message def __unicode__(self): return self.message def __str__(self): return self.message.encode('utf-8')