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
nanolearning/edx-platform
lms/djangoapps/courseware/features/video.py
Python
agpl-3.0
20,986
0.001525
# -*- coding: utf-8 -*- # pylint: disable=C0111 from lettuce import world, step, before, after import json import os import time import requests from nose.tools import assert_less, assert_equal, assert_true, assert_false from common import i_am_registered_for_the_course, visit_scenario_item from django.utils.translati...
a=None, display_name='Video'): if not parent_location: parent_location = add_vertical_to_course(course) kwargs = get_metadata(parent_location, player_mode, data, display_name=display_name) world.scenario_dict['VIDEO'] = world.ItemFactory.create(**kwargs) def add_vertical_to_course(course_num): ...
display_name='Test Vertical-{}'.format(len(set(world.video_sequences.values()))), ) return last_vertical_location(course_num) def last_vertical_location(course_num): return world.scenario_dict['LAST_VERTICAL'].location.replace(course=course_num) def upload_file(filename, location): path = os.pat...
linjinxin/paas
app/api.py
Python
apache-2.0
1,134
0.037313
#coding:UTF-8 """ API模块,用于对外调用 2015-04-25 """ from flask import Blueprint,request,jsonify from lib.db import db,sqlDeal,objToDict from lib import client app=Blueprint("api",__name__) def getAppFromToken(apiKey,secretKey): "获取应用信息" sql="select aid from paas_app_token where apiKey = '%s' AND secretKey = '%s'"...
o.close() obj['createTime
']=obj['createTime'].strftime("%Y-%m-%d") return jsonify(obj)
LLNL/spack
var/spack/repos/builtin/packages/libgcrypt/package.py
Python
lgpl-2.1
2,211
0.005427
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class Libgcrypt(AutotoolsPackage): """Cryptographic library based on the code from GnuPG.""" ...
256='3b4a2a94cb637eff5bdebbcaf46f4d95c4f25206f459809339cdada0eb577ac3') version('1.8.4', sha256='f638143a0672628fde0cad745e9b14deb85dffb175709cacc1f4fe24b93f2227') version('1.8.1', sha256='7a2875f8b1ae0301732e878c0cca2c9664ff09ef71408f085c50e332656a78b3') version('1.7.6', sha256='626aafee84af9d2ce253d2c143d...
lf): # Without this hack, `make check` fails on macOS when SIP is enabled # https://bugs.gnupg.org/gnupg/issue2056 # https://github.com/Homebrew/homebrew-core/pull/3004 if self.spec.satisfies('platform=darwin'): old = self.prefix.lib.join('libgcrypt.20.dylib') new...
velorientc/git_test7
tortoisehg/hgqt/qreorder.py
Python
gpl-2.0
7,443
0.001478
# qreorder.py - reorder unapplied MQ patches # # Copyright 2010 Steve Borho <steve@borho.org> # # This software may be used and distributed according to the terms of the # GNU General Public License version 2, incorporated herein by reference. import os from hgext import mq from tortoisehg.hgqt import qtlib, qrename...
cached = patchnames, applied if cw == ulw: alw.setCurrentRow(ar) ulw.setCurrentRow(ur) self.ulw.setFocus() else: ulw.setCurrentRow(ur) alw.setCurrentRow(ar) self.alw.setFocus() def showSummary(self, item): if item is No...
else: ctx = self.repo.changectx(item.patchname) self.summ.setText(hglib.tounicode(ctx.description())) def accept(self): self._writesettings() applied = [self.alw.item(x).patchname for x in xrange(self.alw.count())] unapplied = [self.ulw.item(x...
ekadhanda/bin
python/pts-test.py
Python
mit
11,854
0.010798
#! /usr/bin/env python # Written by Vasaant S/O Krishnan. Friday, 18 March 2016. import re from pylab import * import sys from mpldatacursor import datacursor usrFile = sys.argv[1:] if len(usrFile) == 0: print "" print "# pts-test.py takes input from a single .PTS file to study the" print "# component a...
mp.append(float(reqInfo.group(4))) pTmp.append(float(reqInfo.group(5))) xTmp.append(float(reqInfo.gr
oup(8))) xeTp.append(float(reqInfo.group(9))) yTmp.append(float(reqInfo.group(10))) yeTp.append(float(reqInfo.group(11))) if line == '\n': # This statement allows each component to exist as its own list within the complete array comp.append(mTmp) ...
corntoole/gradedash-backend-py
gradedash/models.py
Python
mit
268
0.026119
from sqlalchemy im
port Column, Integer, S
tring from gradedash.database import Base class Student(Base): __tablename__ = 'students' id = Column(Integer, primary_key=True) first_name = Column(String(45)) last_name = Column(String(45)) email = Column(String(128))
Yadnyawalkya/integration_tests
cfme/tests/services/test_service_catalogs.py
Python
gpl-2.0
16,850
0.002196
# -*- coding: utf-8 -*- import fauxfactory import pytest from cfme import test_requirements from cfme.infrastructure.provider import InfraProvider from cfme.markers.env_markers.provider import ONE from cfme.markers.env_markers.provider import ONE_PER_TYPE from cfme.services.service_catalogs import ServiceCatalogs from...
provider).cleanup_on_provider() ) request.addfinalizer(catalog_item.delete) catalog = appliance.rest_api.collections.service_catalogs.find_by(name=catalog.name) assert len(catalog) == 1 catalog, = catalog template = catalog.service_templates.find_by(name=cat...
emplate req = template.action.order() assert_response(appliance) @wait_for_decorator(timeout="15m", delay=5) def request_finished(): req.reload() logger.info("Request status: {}, Request state: {}, Request message: {}".format( req.status, req.request_state, req.message)) ...
braintree/braintree_python
braintree/credit_card_verification_gateway.py
Python
mit
3,076
0.004551
from braintree.credit_card_verification import CreditCardVerification from braintree.credit_card_verification_search import CreditCardVerificationSearch from braintree.exceptions.not_found_error import NotFoundError from braintree.ids_search import IdsSearch from braintree.resource_collection import ResourceCollection ...
get(term.name):
criteria[term.name] = dict(list(criteria[term.name].items()) + list(term.to_param().items())) else: criteria[term.name] = term.to_param() return criteria def __fetch(self, query, ids): criteria = self.__criteria(query) criteria["ids"] = CreditCar...
tanglei528/nova
nova/api/openstack/compute/plugins/v3/ips.py
Python
apache-2.0
2,828
0
# 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...
._get_instance(context, server_id) networks = common.get_networks_for_instance(context, instance) if id not in networks: msg = _("Instance is not a member of specified network") raise exc.HTTPNotFound(explanation=msg) return self._view_builder.show(networks[id], id) cl...
lf): parent = {'member_name': 'server', 'collection_name': 'servers'} resources = [ extensions.ResourceExtension( 'ips', IPsController(), parent=parent, member_name='ip')] return resources def get_controller_extensions(self): return []
Tendrl/commons
tendrl/commons/tests/jobs/test_jobs_init.py
Python
lgpl-2.1
4,525
0
import etcd import maps from mock import MagicMock from mock import patch import threading import time from tendrl.commons import jobs from tendrl.commons.objects import BaseObject from tendrl.commons.tests import test_init from tendrl.commons.utils import alert_utils from tendrl.commons.utils import etcd_utils from t...
: with patch.object(obj._complete, "is_set", is_set): NS.tendrl_context.integration_id = \ "b0b18359-3444-40b7-aa99-853f1b7308de" tc_load.return_value = NS.tendrl_context obj.run() @patch.object(logger, "log") def test_process_job_fail(lo...
NS.tendrl.objects.Job.load = MagicMock() job = NS.tendrl.objects.Job( job_id="808a4162-4b70-4ff0-b218-45dbe371e545", payload={"status": "new", "type": "node"} ) NS.tendrl.objects.Job.load.return_value = job with patch.object(job, "save") as save: save.return_value = None ...
gsnbng/erpnext
erpnext/controllers/selling_controller.py
Python
agpl-3.0
16,561
0.024757
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe from frappe.utils import cint, flt, cstr, comma_or from frappe import _, throw from erpnext.stock.get_item_details import get_bin_details ...
self.validate_for_duplicate_items() self.validate_target_warehouse() def set_missing_values(self, for_validate=False): super(SellingController, self).set_missing_values(for_validate) # set contact and address detai
ls for customer, if they are not mentioned self.set_missing_lead_customer_details() self.set_price_list_and_item_details(for_validate=for_validate) def set_missing_lead_customer_details(self): customer, lead = None, None if getattr(self, "customer", None): customer = self.customer elif self.doctype == "O...
NeCTAR-RC/cinder
cinder/tests/integrated/integrated_helpers.py
Python
apache-2.0
4,234
0
# Copyright 2011 Justin Santa Barbara # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requ...
else: image_href = image['id'] image_href = 'http://fake.server/%s' % image_href # We now have a valid imageId server['imageRef'] = image_href # Set a valid flavorId flavor = self.api.get_flavors()[0] LOG.debug("Using flavor: %s" % flav
or) server['flavorRef'] = 'http://fake.server/%s' % flavor['id'] # Set a valid server name server_name = self.get_unused_server_name() server['name'] = server_name return server
jcastillocano/python-route53
tests/test_integration.py
Python
mit
5,689
0.001934
import unittest import route53 from route53.exceptions import AlreadyDeletedError from route53.transport import BaseTransport from tests.utils import get_route53_connection import datetime import os from test_basic import BaseTestCase try: from .credentials import AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY except Im...
for zone in self.conn.list_hosted_zones(): if zone.name == self.test_zone_ame: zone.delete(force=True) class IntegrationHostedZoneTestCase(IntegrationBaseTestCase): """ Tests for manipulating hosted zones. """ def test_sequence(s
elf): """ Runs through a sequence of calls to test hosted zones. """ if self.skip: self.SkipTest("There is no api credentials") # Create a new hosted zone. new_zone, change_info = self.conn.create_hosted_zone( self.test_zone_name, comment='A comme...
coreos/chromite
scripts/cros_portage_upgrade_unittest.py
Python
bsd-3-clause
137,400
0.005349
#!/usr/bin/python # Copyright (c) 2012 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Unit tests for cros_portage_upgrade.py.""" from __future__ import print_function import exceptions import filecmp import mox im...
{}, 'dev-libs/D-1': {'RDEPEND': '!dev-libs/E'}, 'dev-libs/D-2': {}, '
dev-libs/D-3': {}, 'dev-libs/E-2': {'RDEPEND': '!dev-libs/D'}, 'dev-libs/E-3': {}, 'dev-libs/F-1': {'SLOT': '1'}, 'dev-libs/F-2': {'SLOT': '2'}, 'dev-libs/F-2-r1': {'SLOT': '2', 'KEYWORDS': '~amd64 ~x86 ~arm', }, 'dev-apps/X-1': { 'EAPI': '3', 'SLOT': '0...
kstaniek/csm
csmserver/platform_matcher.py
Python
apache-2.0
8,457
0.005439
# ============================================================================= # Copyright (c) 2016, Cisco Systems, 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 ...
.\d+\.\d+", name) if matches: return matches[0] return UNKNOWN def get_NCS6K_release(name): """ Example, input: ncs6k-xr-5.0.1
ncs6k-5.0.1.CSCul51055-0.0.2.i ncs6k-sysadmin-xr-5.0.1 ncs6k-sysadmin-5.0.1.CSCul51055-0.0.2.i ASR9K-iosxr-px-k9-5.0.1.tar ASR9K-iosxr-px-5.0.1-bridge_smus.tar output: 5.0.1 """ matches = re.findall("\d+\.\d+\.\d+", name) ...
ICTSTUDIO/accounting-addons
account_operating_unit_invoice_line/__openerp__.py
Python
agpl-3.0
588
0.001704
# -*- coding: utf-8 -*- # Copyright© 2016 ICTSTUDIO <http://www.ictstudio.eu> # License: AGPL-3.0 or later (http://www.gnu.org/lic
enses/agpl) { "name": 'Operating Unit - Changeable Invoice Line', "version": "8.0.1.0.0", "summary": "Default use operating unit of Invoice but be able to change per line", "author": "ICTSTUDIO", "website": "http://www.ictstudio.eu", "category": "
Accounting & Finance", "depends": ['account_operating_unit', 'account_anglo_saxon_stock_move'], "license": "AGPL-3", "data": [ "views/account_invoice.xml", ], }
burlog/py-static-callgraph
callgraph/hooks.py
Python
mit
1,125
0.003556
# -*- coding: utf-8 -*- # # LICENCE MIT # # DESCRIPTION Callgraph hooks for evetns during building callgraph. # # AUTHOR Michal B
ukovsky <michal.bukovsky@trilogic.cz> # class Event(object): def __init__(self, builder, **kwargs): self.filename = builder.tot.filename self.lineno = builder.current_lineno self.function_qualname = builder.tot.qualname self.function_nam
e = builder.tot.name self.line = builder.tot.source_line(file_lineno=self.lineno) for k, v in kwargs.items(): setattr(self, k, v) class Hook(object): def __init__(self, builder, name): self.name = name self.builder = builder self.events = [] def __call__(self, **kwargs)...
apophys/freeipa
ipatests/test_ipapython/test_dn.py
Python
gpl-3.0
48,955
0.001021
import contextlib import unittest import pytest from cryptography import x509 import six from ipapython.dn import DN, RDN, AVA if six.PY3: unicode = str def cmp(a, b): if a == b: assert not a < b assert not a > b assert not a != b assert a <= b ...
, 'self') self.assertEqual(ava1, self.ava1) # Create with list [attr, value] ava1 = AVA([self.attr1, self.value1]) self.assertExpectedClass(AVA, ava1, 'self') self.assertEqual(ava1, self.ava1) # Create with no args should fail with self.assertRaises(TypeError): ...
# Create with 1 arg which is not string should fail with self.assertRaises(TypeError): AVA(1) # Create with malformed AVA string should fail with self.assertRaises(ValueError): AVA("cn") # Create with non-string parameters, should convert ava1 = AVA(1...
crawfordsm/pysalt
saltred/salt2iraf.py
Python
bsd-3-clause
2,648
0.024924
################################# LICENSE ################################## # Copyright (c) 2009, South African Astronomical Observatory (SAAO) # # All rights reserved. # # # ############...
he data ou
t saltio.writefits(odu, oimg, clobber=clobber) # ----------------------------------------------------------- # main code if not iraf.deftask('salt2iraf'): parfile = iraf.osfn("saltred$salt2iraf.par") t = iraf.IrafTaskFactory(taskname="salt2iraf",value=parfile,function=salt2iraf, pkgname='saltred')
sserrot/champion_relationships
venv/Lib/site-packages/tests/test_queries.py
Python
mit
13,676
0.000366
import pytest from datapipelines import Query, QueryValidationError, QueryValidatorStructureError, validate_query def test_has(): valid = Query.has("test") with pytest.raises(QueryValidationError): valid({}) with pytest.raises(QueryValidationError): valid({"dog": "cat"}) assert val...
yValidationError): valid({"test": 0.0}) assert valid({"test": 0}) assert valid({"test": "test"}) assert valid({"test": "test", "dog": "cat"}) def test_can_have_as_any_of(): valid = Query.can_have("test").as_any_of({str, int}) with pytest.raises(QueryValidationError): valid({"test...
({"test": "test", "dog": "cat"}) def test_repeat_as_any_of(): with pytest.raises(QueryValidatorStructureError): Query.has("test").as_any_of({int, str}).as_any_of({int, str}) with pytest.raises(QueryValidatorStructureError): Query.can_have("test").as_any_of({int, str}).as_any_of({int, str}) ...
Scarygami/gae-gcs-push2deploy-secrets
lib/simplekv/crypt.py
Python
apache-2.0
6,188
0.000646
#!/usr/bin/env python # coding=utf8 import hashlib import hmac import os import tempfile from .decorator import StoreDecorator class _HMACFileReader(object): def __init__(self, hm, source): self.hm = hm self.source = source # "preload" buffer self.buffer = source.read(self.hm.di...
` and :meth:`put_file` methods and alters the data that is store in the follow way: First, the original data is stored while being fed to an hmac instance. The resulting hash is appended to the data as a binary string, every value stored theref
ore takes up an additional :prop:`HMACDecorator.hmac_digestsize` bytes. Upon retrieval using any of :meth:`get`, :meth:`get_file` or :meth:`open` methods, the data is checked as soon as the hash is readable. Since hashes are stored at the end, almost no extra memory is used when using streaming met...
david-ragazzi/nupic
nupic/research/monitor_mixin/monitor_mixin_base.py
Python
gpl-3.0
5,503
0.005633
# ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2014, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This progra...
abc import numpy from prettytable import PrettyTable from nupic.research.monitor_mixin.plot import Plot class MonitorMixinBase(object): """ Base class for MonitorMixin. Each subclass will be a mixin for a particular algorithm. All arguments, variables, and methods in monitor mixin classes should be pref...
def __init__(self, *args, **kwargs): """ Note: If you set the kwarg "mmName", then pretty-printing of traces and metrics will include the name you specify as a tag before every title. """ self.mmName = kwargs.get("mmName") if "mmName" in kwargs: del kwargs["mmName"] super(Monito...
sunqm/pyscf
pyscf/geomopt/geometric_solver.py
Python
apache-2.0
9,525
0.00252
#!/usr/bin/env python # Copyright 2014-2019 The PySCF Developers. 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 # # U...
dump_mol_geometry, symmetrize) # noqa from pyscf import __config__ from pyscf.grad.rhf import GradientsMixin try: from geome
tric import internal, optimize, nifty, engine, molecule except ImportError: msg = ('Geometry optimizer geomeTRIC not found.\ngeomeTRIC library ' 'can be found on github https://github.com/leeping/geomeTRIC.\n' 'You can install geomeTRIC with "pip install geometric"') raise ImportError(msg)...
deMenschRutger/sapling
public/__init__.py
Python
mit
101
0
from flask import
Flask app = Flask('sapling', static_folder='public/static') i
mport views # noqa
J216/gimp_be
gimp_be/draw/draw.py
Python
mit
26,770
0.012813
import random, math import gimp_be #from gimp_be.utils.quick import qL from gimp_be.image.layer import editLayerMask from effects import mirror import numpy as np import UndrawnTurtle as turtle def brushSize(size=-1): """" Set brush size """ image = gimp_be.gimp.image_list()[0] drawable = gimp_be.p...
coord.append(int(nt.position()[0]*10)+center[0]) coord.append(int(nt.position()[1]*10)+center[1]) nt.forward(step) nt.left(angle)
coord.append(int(nt.position()[0]*10)+center[0]) coord.append(int(nt.position()[1]*10)+center[1]) drawLine(coord) def drawRays(rays=32, rayLength=100, centerX=0, centerY=0): """" draw N rays from center in active drawable with current brush """ image = gimp_be.gimp.image_list()[0] ...
anaran/olympia
apps/stats/db.py
Python
bsd-3-clause
1,314
0
from django.db import models import phpserialize as ph
p import json class StatsDictField(models.TextField): description = 'A dictionary of counts stored as serialized php.' __metaclass__ = models.SubfieldBase def db_type(self, connection): return 'text' def to_python(self, value): # object case if v
alue is None: return None if isinstance(value, dict): return value # string case if value and value[0] in '[{': # JSON try: d = json.loads(value) except ValueError: d = None else: # p...
diagramsoftware/l10n-spain
l10n_es_facturae/models/__init__.py
Python
agpl-3.0
173
0
# -*- coding: utf-8 -*- # License
AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). fro
m . import res_partner from . import res_company from . import payment_mode
markriedl/easygen
lstm.py
Python
mit
20,858
0.019896
import time import math import os import torch import codecs import torch.nn as nn import torch.optim as optim import pdb ######################################################## ### MODEL ######################################################## class RNNModel(nn.Module): """Container module with an encoder, a r...
model = model.to(device) model.eval() # Load the dictionary dictionary = None with open(dictionary_path, 'rb') as f: dictionary = torch.load(f) ntokens = len(dictionary) hidden
= model.init_hidden(1) input = torch.randint(ntokens, (1, 1), dtype=torch.long).to(device) if seed is not None: seed_words = seed.strip().split() if len(seed_words) > 1: for i in range(len(seed_words)-1): word = seed_words[i] if word in dictionary.i...
Infinidat/infi.clickhouse_orm
src/infi/clickhouse_orm/__init__.py
Python
bsd-3-clause
490
0.018367
__import__("pkg_resources").declare_namespace(__name__) from infi.clickhouse_orm.database import * from infi.clickhouse_orm.engines import * from infi.clickhouse_orm.fields import * from infi.cl
ickhouse_orm.funcs import * from infi.clickhouse_orm.migrations import * from infi.clickhouse_orm.models import * from infi.clickhouse_orm.query imp
ort * from infi.clickhouse_orm.system_models import * from inspect import isclass __all__ = [c.__name__ for c in locals().values() if isclass(c)]
Anomalous-Software/mygui
Scripts/vera++/vera++.py
Python
mit
1,126
0.033748
# run from root sources directory: python Scripts/vera++/vera++.py import os ignoredEndings = [] ignoredContent = [ "CMakeFiles", "MyGUI_UString", "pugixml", "sigslot", "Wrappers", "MyGUI_KeyCode.h:58", "InputConverter.h:896", "MyGUI_RTTLayer.h:21", "HotKeyManager.cpp:44", "HotKeyManager.cpp:45", "Common/Ba...
if warning.find(ignore) != -1: return True return False def parseOutput(): file = open("temp.vera++", 'r') line = file.readline() while line != "": line = line[0:len(line)-1] if (not isIgnoredWarning(line)): print line line = file.readline() file.close () def checkDir(folder): os.system("vera++ ....
ir("Platforms/*/*/*/*.h") checkDir("Platforms/*/*/*/*.cpp") os.chdir("../..")
kanakb/pyhelix
tests/mockclient.py
Python
apache-2.0
4,413
0.000227
import kazoo.client import kazoo.exceptions class MockStruct(object): """ Basic object to allow adding arbitrary properties """ class MockKazooClient(object): """ In-memory version of the kazoo client for unit testing """ def __init__(self): self.store = {'/': None} self...
sion = -1 if path in self.versions: existversion = self.versions[path] if version != -1 and existversion > version: raise kazoo.exceptions.BadVersionError to_pop = [] for existpath in self.store.iterkeys(): if existpath.startswith(path): ...
r subpath in to_pop: self.store.pop(subpath) if subpath in self.versions: self.versions.pop(subpath) if subpath in self.ephemerals: self.ephemerals.pop(subpath) if path == '/': self.store = {'/': None} def add_listener(self, un...
hamzehd/edx-platform
common/djangoapps/student/admin.py
Python
agpl-3.0
6,073
0.001482
""" Django admin pages for student app """ from django import forms from django.contrib.auth.models import User from ratelimitbackend import admin from xmodule.modulestore.django import modulestore from opaque_keys import InvalidKeyError from opaque_keys.edx.keys import CourseKey from config_models.admin import Config...
king_code',) class CourseEnrollmentAdmin(admin.ModelAdmin): """ Admin interface for the CourseEnrollment model. """ list_display = ('id', 'course_id', 'mode', 'user', 'is_active',) list_filter = ('mode', 'is_active',) raw_id_fields = ('user',) search_fields = ('course_id', 'mode', 'user__username'...
t): return super(CourseEnrollmentAdmin, self).queryset(request).select_related('user') class Meta(object): model = CourseEnrollment class UserProfileAdmin(admin.ModelAdmin): """ Admin interface for UserProfile model. """ list_display = ('user', 'name',) raw_id_fields = ('user',) s...
aviarypl/mozilla-l10n-addons-server
src/olympia/addons/tests/test_commands.py
Python
bsd-3-clause
31,508
0
from contextlib import contextmanager from django.conf import settings from django.core.management import call_command from django.core.management.base import CommandError from django.forms import ValidationError from django.utils import translation import mock import pytest from olympia import amo from olympia.acti...
AddonLog from olympia.addons.management.commands import ( approve_addons, process_addons as pa) from olympia.addons.models import Addon
from olympia.amo.tests import ( AMOPaths, TestCase, addon_factory, version_factory) from olympia.applications.models import AppVersion from olympia.files.models import FileValidation, WebextPermission from olympia.reviewers.models import AutoApprovalSummary, ReviewerScore from olympia.versions.models import Applica...
thaddeustaylor/catkin
test/unit_tests/test_environment_cache.py
Python
bsd-3-clause
3,047
0.001313
import os import stat import unittest import tempfile import shutil from mock import Mock try: import catkin.environment_cache from catkin.environment_cache import _append_header, _set_variable, _append_comment, _is_not_windows, generate_environment_script except ImportError as impe: raise ImportError( ...
winplatform code = [] _append_header(code) self.assertEqual(['@echo off', 'REM generated from catkin/python/catkin/environment_cache.py',
''], code) code = [] _append_comment(code, 'foo') self.assertEqual(['REM foo'], code) code = [] _set_variable(code, 'foo', 'bar') self.assertEqual(['set foo=bar'], code) def test_generate_environment_script(self): try: fake_environ...
FCP-INDI/nipype
nipype/interfaces/fsl/tests/test_auto_BEDPOSTX5.py
Python
bsd-3-clause
2,691
0.028986
# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT from ....testing import assert_equal from ..dti import BEDPOSTX5 def test_BEDPOSTX5_inputs(): input_map = dict(all_ard=dict(argstr='--allard', xor=('no_ard', 'all_ard'), ), args=dict(argstr='%s', ), burn_in=dict(argstr='-b %d', ), b...
viron
=dict(nohash=True, usedefault=True, ), f0_ard=dict(argstr='--f0 --ardf0', xor=['f0_noard', 'f0_ard', 'all_ard'], ), f0_noard=dict(argstr='--f0', xor=['f0_noard', 'f0_ard'], ), force_dir=dict(argstr='--forcedir', usedefault=True, ), fudge=dict(argstr='-w %d', ), gr...
aitjcize/cppman
cppman/formatter/cppreference.py
Python
gpl-3.0
12,272
0.001059
# -*- coding: utf-8 -*- # # formatter.py - format html from cplusplus.com to groff syntax # # Copyright (C) 2010 - 2015 Wei-Ning Huang (AZ) <aitjcize@gmail.com> # All Rights reserved. # # This file is part of cppman. # # This program is free software; you can redistribute it and/or modify # it under the terms of the G...
, 0), (r'\\([^\^nE])', r'\\\\\1', 0), (r'>/">', r'', 0), (r'/">', r'', 0), # Remove empty sections (r'\n.SH (.+?)\n+.SE', r'', 0), # Remove empty lines (r'\n\s*\n+', r'\n', 0), (r'\n\n+', r'\n', 0), # Preserve \n" in EXAMPLE (r'\\n', r'\\en', 0), #
Remove leading whitespace (r'^\s+', r'', re.S), # Trailing white-spaces (r'\s+\n', r'\n', re.S), # Remove extra whitespace and newline in .SH/SS/IP section (r'.(SH|SS|IP) "\s*(.*?)\s*\n?"', r'.\1 "\2"', 0), # Remove extra whitespace before .IP bullet (r'(.IP \\\\\[bu\] 3)\n\s*(.*?)\n', r'\1\...
gerruz/DeepConvSep
examples/bach10/compute_features_bach10sibelius.py
Python
agpl-3.0
5,850
0.016068
""" This file is part of DeepConvSep. Copyright (c) 2014-2017 Marius Miron <miron.marius at gmail.com> DeepConvSep 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 Lic...
ure_path,style[s])) for co in combo: c = np.array(co) for i in range(len(sources)): #read the audio file
sounds,sampleRate,bitrate = util.readAudioScipy(os.path.join(db,f,f+'_'+style[s]+'_'+sources[i]+'.wav')) if sampleRate != 44100: print 'sample rate is not consistent' if i==0: tt=...
endlessm/chromium-browser
third_party/ffmpeg/tools/python/convert_from_tensorflow.py
Python
bsd-3-clause
18,670
0.005088
# Copyright (c) 2019 Guo Yejun # # This file is part of FFmpeg. # # FFmpeg 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 2.1 of the License, or (at your option) any later version. # #...
# if activation is None, and BiasAdd.next is the last op which is Identity if conv2d_scope_name + '/BiasAdd' in
self.edges: anode = self.edges[conv2d_scope_name + '/BiasAdd'][0] if anode.op not in self.conv_activations: anode = None else: anode = None return knode, bnode, dnode, anode def dump_complex_conv2d_to_file(self, node, f): assert(node.op =...
LonamiWebs/Telethon
telethon/_events/newmessage.py
Python
mit
4,114
0.000729
import re from .base import EventBuilder from .._misc import utils from .. import _tl from ..types import _custom class NewMessage(EventBuilder, _custom.Message): """ Represents the event of a new message. This event can be treated to all effects as a `Message <telethon.tl.custom.message.Message>`, s...
... # In this case, the result is a ``Match`` object ... # since the `str` pattern was converted into ... # the ``re.compile(
pattern).match`` function. ... print('Welcomed', event.pattern_match.group(1)) ... >>> Example .. code-block:: python import asyncio from telethon import events @client.on(events.NewMessage(pattern='(?i)hello.+')) asy...
cahudson94/django-imager
imagersite/imager_profile/urls.py
Python
mit
514
0
"""URL managment for profile based pages.""" from django.conf.urls import url from i
mager_profile.views import ( ProfileView, PublicProfileView, ProfileEditView ) from django.contrib.auth.decorators import login_required urlpatterns = [ url(r'^$', login_required(ProfileView.as_view()), name='profile'), url(r'^edit/$', ProfileEditView.as_view(), name='profile_edit'...
PublicProfileView.as_view(), name='public_profile'), ]
sunnychaudhari/gstudio
gnowsys-ndf/gnowsys_ndf/mobwrite/mobwrite_core.py
Python
agpl-3.0
9,136
0.01018
#!/usr/bin/python """MobWrite - Real-time Synchronization and Collaboration Service Copyright 2009 Google Inc. http://code.google.com/p/google-mobwrite/ 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...
on":3, "client_version":3, "echo_username":False } """ # Passin
g a Unicode string is an easy way to cause numerous subtle bugs. if type(data) != str: LOG.critical("parseRequest data type is %s" % type(data)) return [] if not (data.endswith("\n\n") or data.endswith("\r\r") or data.endswith("\n\r\n\r") or data.endswith("\r\n\r\n")): # There must...
pararthshah/libavg-vaapi
src/samples/asyncload.py
Python
lgpl-2.1
3,390
0.00767
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' Shows how to use BitmapManager to asynchronously load a Bitmap from a file. Run this snippet providing a list of filenames of (high resolution) pictures: $ ./asyncload.py /path/to/mypics/*.jpg anotherpic.png nonexistent.png Press space to sequentially load the pictur...
pace to load the first image', fontsize=11, pos=(10, 5), parent=self._parentNode) self.__pics = sys.argv[1:] self.__currentPic = -1 player.subscribe(player.ON_FRAME, self.__onFrame) def onKeyDown(self, event): ''' Intercept a space keypress and t...
if event.keystring == 'space': self.__requestNextBitmap() def __requestNextBitmap(self): ''' Ask the BitmapManager to load a new file. loadBitmap() call returns immediately. ''' self.__currentPic = (self.__currentPic + 1) % len(self.__pics) libavg.avg.Bi...
takeshineshiro/keystone
keystone/token/persistence/backends/memcache_pool.py
Python
apache-2.0
1,016
0
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under t...
ed. See the # License for the specific language governing permissions and limitations # under the License. from oslo_config import cfg from keystone.token.persistence.backends import memcache CONF = cfg.CONF class Token(memcache.Token): memcached_backend = 'pooled_memcached' def __init__(self, *args, **k...
rgs[arg] = getattr(CONF.memcache, arg) super(Token, self).__init__(*args, **kwargs)
gnuworldman/site-analytics
doc/conf.py
Python
gpl-3.0
12,791
0.000156
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Site Analytics documentation build configuration file, created by # sphinx-quickstart. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # #...
itle = 'Site Analytics v1.0.0' # A shorter title for the navigation bar. Default is the same as html_title. # # html_short_title = None # The name of an image file (relative to this directory) to plac
e at the top # of the sidebar. # # html_logo = None # The name of an image file (relative to this directory) to use as a favicon of # the docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. # # html_favicon = None # Add any paths that contain custom static files (such as style s...
TheArchives/Nexus
core/globals.py
Python
bsd-2-clause
18,259
0.002684
# The Nexus software is licensed under the BSD 2-Clause license. # # You should have recieved a copy of this license with the software. # If you did not, you can find one at the following link. # # http://opensource.org/licenses/bsd-license.php import time def Rank(self, parts, fromloc, overriderank, server=None): ...
(): return ("You are not a high enough rank!") else: if fromloc != "console": if not factory.isModPlus(parts[-1]): return ("You are not a high enough rank!") factory.members.add(username) if username in factory.usernames: ...
elif parts[1] == "globalbuilder": if not server: if not self.client.isModPlus(): return ("You are not a high enough rank!") else: if fromloc != "console": if not factory.isModPlus(parts[-1]): return ("You are not a high enou...
yoer/hue
apps/impala/src/impala/conf.py
Python
apache-2.0
5,222
0.008809
#!/usr/bin/env python # Licensed to Cloudera, Inc. under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. Cloudera, Inc. licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you ma...
, private=True, type=coerce_password_from_script, default=None) def config_validator(user): # dbms is dependent on beeswax.conf (this file) # import in method to avoid circular dependency from beeswax.server import dbms from beeswax.server.dbms import get_query_server_config res = [] try: if no...
name='impala') server = dbms.get(user, query_server) server.get_databases() except: msg = "No available Impalad to send queries to." LOG.exception(msg) res.append((NICE_NAME, _(msg))) return res
hoffie/gnucash-ofx-export
gce/ofx.py
Python
gpl-2.0
3,118
0.001283
from datetime import datetime from hashlib import sha1 from xml.sax.saxutils import escape as xml_escape from .common import CHARSET def xml_template(template, data): """ return template % data but with proper escaping """ escaped_data = {} for key, value in data.items(): escaped_data[key] ...
<STMTTRNRS> <TRNUID>0</TRNUID> <STMTRS> <CURDEF>EUR</CURDEF> <BANKACCTFROM> <BANKID>info.hoffmann-christian.gnucash-export</BANKID> <ACCTID>%(acctid)s</ACCTID>
<ACCTTYPE>CHECKING</ACCTTYPE> </BANKACCTFROM> <BANKTRANLIST> <DTSTART>%(dtstart)s</DTSTART> <DTEND>%(dtend)s</DTEND>""" TRANSACTION = """ <STMTTRN> <TRNTYPE>%(trntype)s</TRNTYPE> <DTPOSTED>%(dtposted)s</DTPOSTED> <DTUSER>%(dtuser)...
eduNEXT/edx-platform
openedx/core/djangoapps/util/tests/test_user_messages.py
Python
agpl-3.0
5,683
0.003167
""" Unit tests for user messages. """ import warnings import ddt from django.contrib.messages.middleware import MessageMiddleware from django.test import RequestFactory, TestCase from common.test.utils import normalize_repr from openedx.core.djangolib.markup import HTML, Text from common.djangoapps.student.tests.fa...
assert len(messages) == 1 assert messages[0].message_html == expected_message_html @ddt.data( (UserMessageType.ERROR, 'alert-danger', 'fa fa-warning'), (UserMessageType.INFO, 'alert-info', 'fa fa-bullhorn'), (UserMessageType.SUCCESS, 'a
lert-success', 'fa fa-check-circle'), (UserMessageType.WARNING, 'alert-warning', 'fa fa-warning'), ) @ddt.unpack def test_message_icon(self, message_type, expected_css_class, expected_icon_class): """ Verifies that a user message returns the correct CSS and icon classes. """ ...
arenadata/ambari
ambari-server/src/main/resources/common-services/MAHOUT/1.0.0.2.3/package/scripts/service_check.py
Python
apache-2.0
3,213
0.015562
""" 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 n
ot 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 ...
OWASP/django-DefectDojo
dojo/management/commands/dedupe.py
Python
bsd-3-clause
902
0.001109
from django.core.management.base import BaseCommand from pytz import timezone from dojo
.models import Finding from dojo.utils import get_system_setting from dojo.utils import sync_dedupe locale = timezone(get_system_setting('time_zone')) """ Author: Aaron Weaver This script will update the hashcode and dedupe findings in DefectDojo: """ class Command(BaseCommand):
help = 'No input commands for dedupe findings.' def handle(self, *args, **options): findings = Finding.objects.all() print("######## Updating Hashcodes ########") for finding in findings: finding.hash_code = finding.compute_hash_code() finding.save() fin...
chaosct/GestureAgents
Apps/TestComposition/RecognizerTT_Test.py
Python
mit
3,983
0.002009
#!/usr/bin/env python # -*- coding: utf-8 -*- from GestureAgents.Recognizer import Recognizer, newHypothesis from GestureAgents.Agent import Agent import math from GestureAgentsTUIO.Gestures2D.RecognizerTap import RecognizerTap def build_and_register_TT(RTKlass=RecognizerTap): class RecognizerTT_Test(Recognizer...
self.fail(cause="Max distance") el
se: self.unregister_event(self.system.newAgent(RTKlass)) self.register_event(Tap.newTap, RecognizerTT_Test.ThirdTap) def ThirdTap(self, Tap): if self.dist(Tap.pos, self.firstap.pos) > self.maxd: self.fail(cause="Max distance") else: ...
iulian787/spack
var/spack/repos/builtin/packages/r-png/package.py
Python
lgpl-2.1
793
0.002522
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class RPng(RPackage): """This package provides an easy and simple way to read, write and display...
bitmap images stored in the PNG format. It can read and write both files and in-memory ra
w vectors.""" homepage = "http://www.rforge.net/png/" url = "https://cloud.r-project.org/src/contrib/png_0.1-7.tar.gz" list_url = "https://cloud.r-project.org/src/contrib/Archive/png" version('0.1-7', sha256='e269ff968f04384fc9421d17cfc7c10cf7756b11c2d6d126e9776f5aca65553c') depends_on('r@2....
CyanogenMod/android_kernel_htc_flounder
scripts/tracing/dma-api/smmu.py
Python
gpl-2.0
7,013
0.001854
"""Low-level memory management tracking""" VERBOSITY = 0 # TODO: use logging class Bitmap(object): """Just a raw bitmap for reserving the pages""" def __init__(self, size, verbosity): self._size = size self._bits = 0 self._verbosity = verbosity self._bits_allocd = 0 def _m...
from an internal bitmap""" return bitmap.free(self.to_bit(addr - self._addr), self.to_bit(size)) class Device(object): """Keep track of allocations per device/process This needs more tricky work for tracking inter-process maps/unmaps :( """ def __init__(self, name, mem): self._name ...
addr, size): pages = self._mem.alloc(self, addr, size) if pages is not False: self._cur_alloc += size self._max_alloc = max(self._max_alloc, self._cur_alloc) self._alloc_history.append(self._cur_alloc) if addr in self._addresses: if VERBOS...
lukasjuhrich/sipa
tests/base.py
Python
mit
5,721
0.000175
import logging import os from contextlib import contextmanager from flask import Flask, url_for from flask_testing import TestCase from sipa import create_app, model from sipa.defaults import WARNINGS_ONLY_CONFIG from sipa.model.sample.user import User as SampleUser class AppInitialized(TestCase): """A frontend...
extended by the values of the attribute :py:attr:`app_config`. """ test_app = Flask('sipa') test_app.config['SECRET_KEY'] = os.urandom(100) test_app.config['TESTING'] = True test_app.config['LOG_CONFIG'] = WARNINGS_ONLY_CONFIG test_app.config['WTF_CSRF_ENABLED'] =...
test_app.config['PRESERVE_CONTEXT_ON_EXCEPTION'] = False test_app.debug = True return create_app(app=test_app, config=self.app_config) @contextmanager def temp_set_attribute(self, attr_name, value): """Temporarily set an attribute to a certain value. Usage: >>> with ...
cliffano/swaggy-jenkins
clients/python-flask/generated/openapi_server/test/test_remote_access_controller.py
Python
mit
11,876
0.003452
# coding: utf-8 from __future__ import absolute_import import unittest from flask import json from six import BytesIO from openapi_server.models.computer_set import ComputerSet # noqa: E501 from openapi_server.models.free_style_build import FreeStyleBuild # noqa: E501 from openapi_server.models.free_style_project ...
response.data.decode('utf-8')) def test_post_create_item(self): """Test case for post_create_item """ body = 'body_example' query_string = [('name', 'name_example'), ('from', '_from_example')
, ('mode', 'mode_example')] headers = { 'Accept': '*/*', 'Content-Type': 'application/json', 'jenkins_crumb': 'jenkins_crumb_example', 'content_type': 'content_type_example', 'Authorization': 'Basic Zm9vOmJhcg==', } ...
pombredanne/downpour
downpour/PoliteFetcher.py
Python
mit
17,878
0.002349
#! /usr/bin/env python # # Copyright (c) 2011 SEOmoz # # 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, mer...
clear an active PLD.') self.redis.zrem(self.key, packed) class PoliteFetcher(BaseFetcher): # This is the maximum number of parallel requests we can make # to the same key maxParallelR
equests = 5 def __init__(self, poolSize=10, agent=None, stopWhenDone=False, delay=2, allowAll=False, use_lock=None, **kwargs): # First, call the parent constructor BaseFetcher.__init__(self, poolSize, agent, stopWhenDone) # Import DownpourLock only if use_lock specified, because i...
BrainTech/openbci
obci/control/launcher/local_process.py
Python
gpl-3.0
6,101
0.00082
#!/usr/bin/python # -*- coding: utf-8 -*- import time import signal import sys import os from process_io_handler import DEFAULT_TAIL_RQ import process from process import FAILED, FINISHED, TERMINATED, UNKNOWN, NON_RESPONSIVE,\ PING, RETURNCODE, REG_TIMER class LocalProcess(process.Process): def __init__(se...
self._status = FAILED # self._status_detals = self.tail_stdout(15) while not self._stop_monitoring: self.popen_obj.poll() code = self.popen_obj.returncode if code is not None: self.logger.info(self.proc_type + " process " + self.name...
pid " + str(self.pid) + " ended with " + str(code)) with self._status_lock: self.popen_obj.wait() if code == 0: self._status = FINISHED self._status_details = '' elif code < 0: ...
gnhuy91/django-tutorial-docker
apps/polls/models.py
Python
mit
696
0
import datetime from django.db import models from django.utils import timezone class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.Da
teTimeField('date published') def __str__(self): return self.question_text def was_published_recently(self): now = timezone.now() yesterday = now - datetime.timedelta(days=1) return now >= self.pub_date >= yesterday class Choice(models.Model): question = models.ForeignKey...
votes = models.IntegerField(default=0) def __str__(self): return self.choice_text
stephane-martin/salt-debian-packaging
salt-2016.3.3/salt/modules/github.py
Python
apache-2.0
7,694
0
# -*- coding: utf-8 -*- ''' Module for interacting with the GitHub v3 API. .. versionadded:: 2016.3.0. :depends: PyGithub python module Configuration ------------- Configure this module by specifying the name of a configuration profile in the minion config, minion pillar, or master config. The module will use the '...
me The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_user github-handle ''' client = _get_client(profile) organization = client.get_organi...
rofile)) try: github_named_user = client.get_user(name) except UnknownObjectException as e: logging.exception("Resource not found {0}: ".format(str(e))) return False org_team = organization.get_team(_get_dev_team_id(profile)) try: headers, data = org_team._requester.re...
MitMaro/The-Blame-Game
game/service.py
Python
mit
1,086
0.040516
from django.contrib.auth.models import User from game.models import Point, Team def addPoint(blame_username, fixer_username): blame = User.objects.get(username=blame_username) fixer = User.objects.get(username=fixer_username) point = Point() point.blame = blame point.fixer = fixer point.save() return point def...
me]['fixes'][point.blame.username] +
= 1 return rtn
tday55/wineapp
winecat/migrations/0001_initial.py
Python
gpl-2.0
1,137
0.002639
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Tasting', fields=[ ('id', models.AutoField(seri...
, models.CharField(max_length=200)), ('vintage', models.CharField(max_length=10)), ('acquisition_date', models.DateTimeField(verbose_name='date acquired'
)), ], ), migrations.AddField( model_name='tasting', name='wine', field=models.ForeignKey(to='winecat.Wine'), ), ]
ytbau/python2
hello_world_using_interpreter.py
Python
apache-2.0
40
0
#
print "Hello, World!" "Hello, World!"
tensorflow/ngraph-bridge
test/python/test_biasadd.py
Python
apache-2.0
3,990
0.000251
# ============================================================================== # Copyright 2018-2020 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://ww...
ias_var = tf.compat.v1.placeholder(tf.float32, shape=(3)) out = tf.nn.bias_add(input_var, bias_var, 'NHWC') def run_test(sess): return sess.run(
out, feed_dict={ input_var: input_data, bias_var: bias_data }) assert ( self.with_ngraph(run_test) == self.without_ngraph(run_test)).all()
richbrowne/f5-openstack-agent
f5_openstack_agent/utils/debug_bundler.py
Python
apache-2.0
5,426
0
# coding=utf-8 # Copyright 2016-2017 F5 Networks 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...
if not self.no_log_files: self._tar_log_files(tar) self._save_pip_list(tar) if __name__ == "__main__": parser = argparse.ArgumentParser( description='Bundles important info for troubleshooting purposes.' ) parser.add_argument( '--no-config-files', ...
ded by default).' ) parser.add_argument( '--no-log-files', action='store_true', help='Use this option to exclude log files from your bundle' '(they are included by default).' ) parser.add_argument( 'tar_dest', help='Directory of bundle produced by this script...
lpramuk/robottelo
tests/foreman/virtwho/ui/test_esx.py
Python
gpl-3.0
32,035
0.002279
"""Test class for Virtwho Configure UI :Requirement: Virt-whoConfigurePlugin :CaseAutomation: Automated :CaseLevel: Acceptance :CaseComponent: Virt-whoConfigurePlugin :Assignee: kuhuang :TestType: Functional :CaseImportance:
High :Upstream: No """ from datetime import datetime import pytest from airgun.session import Session from fauxfactory import gen_string from robottelo.config import settings from robottelo.datafactory import valid_emails_list from robottelo.virtwho_utils import add_configure_option from robottelo.virtwho_utils imp...
tils import delete_configure_option from robottelo.virtwho_utils import deploy_configure_by_command from robottelo.virtwho_utils import deploy_configure_by_script from robottelo.virtwho_utils import get_configure_command from robottelo.virtwho_utils import get_configure_file from robottelo.virtwho_utils import get_conf...
nickmckay/LiPD-utilities
Python/lipd/lipd_io.py
Python
gpl-2.0
3,743
0.003473
from .zips import unzipper, zipper from .directory import rm_file_if_exists, create_tmp_dir, find_files from .bag import create_bag from .csvs import get_csv_from_metadata, write_csv_to_file, merge_csv_metadata, read_csvs from .jsons import write_json_to_file, idx_num_to_name, idx_name_to_num, rm_empty_fields, read_jso...
t_tsids(D) _csvs = read_csvs() D = merge_csv_metadata(D, _csvs) # Why ? Because we need to align the csv filenames with the table filenames. We don't need the csv output here. D, _csv = get_csv_from_metad
ata(D["dataSetName"], D) os.chdir(dir_original) shutil.rmtree(dir_tmp) except FileNotFoundError: print("Error: lipd_read: LiPD file not found. Please make sure the filename includes the .lpd extension") except Exception as e: logger_lipd.error("lipd_read: {}".format(e)) p...
iohannez/gnuradio
grc/core/utils/epy_block_io.py
Python
gpl-3.0
3,687
0.001085
from __future__ import absolute_import import inspect import collections import six from six.moves import zip TYPE_MAP = { 'complex64': 'complex', 'complex': 'complex', 'float32': 'float', 'float': 'float', 'int32': 'int', 'uint32': 'int', 'int16': 'short', 'uint16': 'short', 'int8': 'byte', 'u...
code, cls): ns = {} try: exec(source_code, ns) except Exception as e: raise ValueError("Can't interpret source code: " + str(e)) for var in six.itervalues(ns): if inspect.isclass(var) an
d issubclass(var, cls): return var raise ValueError('No python block class found in code') def extract(cls): try: from gnuradio import gr import pmt except ImportError: raise EnvironmentError("Can't import GNU Radio") if not inspect.isclass(cls): cls = _fin...
arenadata/ambari
ambari-server/src/main/resources/stacks/ADH/1.6/services/HBASE/package/scripts/setup_ranger_hbase.py
Python
apache-2.0
6,925
0.013574
#!/usr/bin/env python """ 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");...
_ranger_kerberos: api_version='v2' from resource_management.libraries.functions.adh_setup_ranger_plugin_xml import setup_ranger_plugin setup_ranger_plugin('hbase', 'hbase', params.previous_jdbc_jar, params.downloaded_custom_connector, params.driver_curl_source, params.drive...
anger_plugin_properties, params.policy_user, params.policymgr_mgr_url, params.enable_ranger_hbase, conf_dict=params.hbase_conf_dir, component_user=params.hbase_user, component_group=params.user_group, cache_service_list=['hbaseMaster', 'hbase...
rapidpro/ureport-web-participation
webparticipation/apps/utils/tests.py
Python
agpl-3.0
535
0.001869
fro
m django.test import TestCase from views import dashify_user, undashify_user class TestUtils(TestCase): def test_undashify_user(self): user = '4c21a87b-4031-4437-a4c5-afb5ddb42aad' undashified_user = undashify_user(user) self.assertEqual(undashified_user, '4c21a87b40314437a4c5afb5ddb42aad...
b-4031-4437-a4c5-afb5ddb42aad')
josemfc/directorio-iep
directorio/migrations/0012_video.py
Python
apache-2.0
865
0.004624
# -*- coding: utf-8 -*- #
Generated by Django 1.9.2 on 2016-02-26 09:59 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('directorio', '0011_auto_20160225_0957'), ] operations = [ migrations.CreateModel( name='V...
('titulo', models.CharField(blank=True, max_length=100, null=True)), ('descripcion', models.CharField(blank=True, max_length=200, null=True)), ('enlace', models.CharField(max_length=200)), ('asignaturas', models.ManyToManyField(blank=True, null=True, to='directorio.Asi...
Shuailong/Leetcode
solutions/string-to-integer-atoi.py
Python
mit
1,137
0.007036
#!/usr/bin/env python # encoding: utf-8 """ string-to-integer-atoi.py Created by Shuailong on 2016-01-15. https://leetcode.com/problems/string-to-integer-atoi/. """ class Solution(object): def myAtoi(self, str): """ :type str: str :rtype: int """ if len(str) < 1: ...
if len(str_valid) == 1 and (str_valid == '+' or str_valid == '-') or len(str_valid) == 0: retur
n 0 res = int(str_valid) MAX = 2**31-1 if res > MAX: return MAX if res < -MAX-1: return -MAX-1 return res def main(): solution = Solution() print solution.myAtoi("-2147483648") if __name__ == '__main__': main()
mwilliamson/python-mammoth
tests/styles/parser/tokeniser_tests.py
Python
bsd-2-clause
2,864
0.000349
from hamcrest import assert_that, contains, has_properties from mammoth.styles.parser.tokeniser import tokenise def test_unknown_tokens_are_tokenised(): assert_tokens("~", is_token("unknown", "~")) def test_empty_string_is_tokenised_to_end_of_file_token(): assert_tokens("") def test_whitespace_is_tokenis...
er", "Magic"), is_token("whitespace", " "), is_token("identifier", "Position"), ) def assert_tokens(string, *expected): expected = list(expected) expected.append(is_token("end", "")) assert_that( tokenise(string), contains(*expected), ) def is_token(token_type, va...
has_properties( type=token_type, value=value, )
wraithan/funday
anyday/core/migrations/0001_initial.py
Python
mit
1,661
0.007827
# -*- 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): # Adding model 'Funday' db.create_table('core_funday', ( ('id', self.gf('django.db.models.fields...
gth=255)), ('description', self.gf('django.db.models.fields.TextField')()), ('video', self.gf('django.db.models.fields.URLField')(max_length=200)), )) db.send_create_signal('core', ['Funday']) def backwards(self, orm): # Deleting model 'Funday' db.delete_tab...
'Meta': {'object_name': 'Funday'}, 'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'description': ('django.db.models.fields.TextField', [], {}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), ...
yanchen036/tensorflow
tensorflow/contrib/distributions/python/ops/bijectors/power_transform.py
Python
apache-2.0
4,229
0.00402
# 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...
me=name) @property def power(self): """The `c` in: `Y = g(X) = (1 + X * c)**(1 / c)`.""" return self._power def _forward(self, x):
x = self._maybe_assert_valid_x(x) if self.power == 0.: return math_ops.exp(x) # If large x accuracy is an issue, consider using: # (1. + x * self.power)**(1. / self.power) when x >> 1. return math_ops.exp(math_ops.log1p(x * self.power) / self.power) def _inverse(self, y): y = self._may...
ScreamingUdder/mantid
scripts/test/SANS/gui_logic/beam_centre_model_test.py
Python
gpl-3.0
5,587
0.007338
from __future__ import (absolute_import, division, print_function) import unittest import sys from sans.gui_logic.models.beam_centre_model import BeamCentreModel from sans.common.enums import FindDirectionEnum, SANSInstrument if sys.version_info.major == 3: from unittest import mock else: import mock class ...
self.assertEqual(state.convert_to_q.q_min, self.beam_centre_model.q_min) self.assertEqual(state.convert_to_q.q_max, self.beam_centre_
model.q_max) def test_that_find_beam_centre_calls_centre_finder_twice_when_COM_is_TRUE(self): state = mock.MagicMock() self.beam_centre_model.COM = True self.beam_centre_model.find_beam_centre(state) self.assertEqual(self.SANSCentreFinder.return_value.call_count, 2) self....
kianby/sandbox
pyserver/app/models/session.py
Python
apache-2.0
339
0
#!/usr/bin/python # -*- coding: UTF-8 -*- from peewee import Model from peewee import CharField from peewee import DateField from app.services.database import g
et_db class Session(Model): username = CharField() token = CharField() login = DateField() last_used = DateField() class Me
ta: database = get_db()
xlk521/cloudguantou
base/views.py
Python
bsd-3-clause
4,622
0.007572
#coding=utf8 # Create your views here. from django.contrib.auth.decorators import login_required from django.shortcuts import render_to_response from django.http import HttpResponse, HttpResponseRedirect from django.views.decorators.http import require_http_methods from content.models import Work, Portfolio, CategoryMo...
s import UserProfile from django.contrib.auth.models import User from django.contrib.auth import authenticate from django.contrib.auth.views import login from django.contrib.auth.forms import AuthenticationForm from django.template import RequestContext #@login_required @require_http_methods(["GET", "POST"]) def
index(request): if request.method != "POST": portfolios = Portfolio.objects.all().order_by('-datetime')[0:20] request.session['album_latesttime'] = portfolios[0].datetime return render_to_response('homepage/index.html',{'Portfolios':portfolios},context_instance=RequestContext(request)) e...
vitorio/ocropodium
ocradmin/ocrmodels/models.py
Python
apache-2.0
1,928
0.002075
""" Object representing
a helper file for an OCR app. """ import datetime from django.db import models from django.contrib.auth.models import User from tagging.fields import TagField import tagging class OcrModel(models.Model): """ OCR model objects. """ user = mode
ls.ForeignKey(User, related_name="ocrmodels") derived_from = models.ForeignKey("self", null=True, blank=True, related_name="derivees") tags = TagField() name = models.CharField(max_length=100, unique=True) description = models.TextField(blank=True) created_on = models.DateField(editable=False) u...
SmartElect/SmartElect
audit/migrations/0001_initial.py
Python
apache-2.0
4,421
0.006107
# Generated by Django 2.2 on 2019-05-03 14:04 from django.db import migrations, models import django.db.models.deletion import django.utils.timezone import libya_elections.libya_bread class Migration(migrations.Migration): initial = True dependencies = [ ('register', '__first__'), ] operat...
se_name='ID')), ('deleted', models.BooleanField(default=False, verbose_name='deleted')), ('creation_date', models.DateTimeField(default=django.utils.timezone.now, editable=False, verbose_name='creation date')), ('modification_date', models.DateTimeField(default=django.uti...
models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='register.SMS', verbose_name='sms')), ('vumi', models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='audit.VumiLog', verbose_name='vumi log')), ], op...
eevee/cocos2d-mirror
test/test_rich_label.py
Python
bsd-3-clause
1,040
0.028846
# This code is so you can run the samples without installing the package import sys import os sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..')) # testinfo = "s, t 5, s, t 10.1, s, q" tags = "RichLabel" import cocos from cocos.director
import director from cocos.sprite import Sprite from cocos.actions import * from cocos.text import * class TestLayer(cocos.layer.Layer): def __init__(self): super( TestLayer, self ).__init__() x,y = director.get_window_size() self.text = RichLabel( "Hello {color (255, 0, 0, 255)}W...
t.document.set_style(0, 5, dict(bold = True)) self.text.element.document.set_style(6, 11, dict(italic = True)) self.text.do( Rotate( 360, 10 ) ) self.text.do( ScaleTo( 10, 10 ) ) self.add( self.text ) def main(): director.init() test_layer = TestLayer () main_scene = cocos...
openatv/enigma2
lib/python/Components/Converter/Streaming2.py
Python
gpl-2.0
1,029
0.019436
from Components.Converter.Converter import Converter from Components.Element import cached from pprint import pprint # the protocol works as the following: # lines starting with '-' are fatal errors (no recovery possible), # lines starting with '=' are progress notices, # lines starting with '+' are PIDs to record: #...
RVICE\n" streaming = service.stream() s = streaming and streaming.getStreamingData() if s is None or not any(s): err = hasattr(service, 'getError') and service.getError() if err: return "-SERVICE ERROR:%d\n" % err else: return "=NO STR
EAM\n" retval = "+%d:%s" % (s["demux"], ','.join(["%x:%s" % (x[0], x[1]) for x in s["pids"]])) if "default_audio_pid" in s: retval += ",%x:%s" % (s["default_audio_pid"], "default_audio_pid") retval += "\n" return(retval) text = property(getText)
alejo8591/maker
sales/urls.py
Python
mit
7,456
0.010864
# encoding: utf-8 # Copyright 2013 maker # License """ Sales module URLs """ from django.conf.urls.defaults import * urlpatterns = patterns('maker.sales.views', url(r'^(\.(?P<response_format>\w+))?$', 'index', name='sales'), url(r'^index(\.(?P<response_format>\w+))?/?$', 'index', name='sales_index...
uct_view', name='sales_product_view'), url(r'^product/delete/(?P<product_id>\d+)(\.(?P<response_format>\w+))?/?$', 'product_delete', name='sales_product_delete'), # Settings url(r'^settings/view(\.(?P<response_format>\w+))?/?$', 'settings_view', name='sales_settings_view'), ...
edit', name='sales_settings_edit'), # Statuses url(r'^status/add(\.(?P<response_format>\w+))?/?$', 'status_add', name='sales_status_add'), url(r'^status/edit/(?P<status_id>\d+)(\.(?P<response_format>\w+))?/?$', 'status_edit', name='sales_status_edit'), url(r'^s...
RedFantom/GSF-Parser
data/durations.py
Python
gpl-3.0
906
0
""" Author: RedFantom Contributors: Daethyra (Naiii) and Sprigell
ania (Zarainia) License: GNU GPLv3 as in LICENSE Copyright (C) 2016-2018 RedFantom """ """ Dictionary describing the duration of Ao
E effects """ durations = { # (ability: (allied, duration, DoT) "Combat Command": (True, 24, False), "EMP Field": (False, 13, False), "Tensor Field": (True, 24, False), "Repair Probes": (True, 24, False), "EMP Missile": (False, 10, False), "Interdiction Drive": (False, 9, False), "Target...
souzabrizolara/py-home-shell
app.py
Python
apache-2.0
1,714
0.003501
#!venv/bin/python __author__ = 'alisonbento' import flask from flask_cors import CORS from src.resources.appliances import * from src.resources.common import * from src.resources.extras import * from src.resources.groups import * from src.resources.services import * from src.resources.status import * from src.resourc...
ces/<appliance_id>/status/') api.add_resource(StatusResource, '/appliances/<int:appliance_id>/status/<int:status_id>/') # Extras api.add_resource(ListExtrasResource, '/appliances/<int:appliance_id>/extras/') api.add_resource(ExtraResource, '/appliances/<appliance_id>/extras/<extra_key>/') # Schemes api.add_resource(S...
host='0.0.0.0', port=8080, debug=configs.DEBUG_MODE) #app.run(port=8080, debug=configs.DEBUG_MODE)
haamoon/tensorpack
tensorpack/dataflow/imgaug/meta.py
Python
apache-2.0
4,607
0.000651
#!/usr/bin/env python # -*- coding: utf-8 -*- # File: meta.py # Author: Yuxin Wu <ppwwyyxxc@gmail.com> from .base import ImageAugmentor __all__ = ['RandomChooseAug', 'MapImage', 'Identity', 'RandomApplyAug', 'RandomOrderAug'] class Identity(ImageAugmentor): """ A no-op augmentor """ def _augment...
.aug_lists: a.reset_state() def _get_augment_params(self, img): # Note: If augmentors change the shap
e of image, get_augment_param might not work # All augmentors should only rely on the shape of image idxs = self.rng.permutation(len(self.aug_lists)) prms = [self.aug_lists[k]._get_augment_params(img) for k in range(len(self.aug_lists))] return idxs, prms def _augmen...
carolFrohlich/nipype
nipype/interfaces/ants/tests/test_auto_Registration.py
Python
bsd-3-clause
4,113
0.027474
# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT from ....testing import assert_equal from ..registration import Registration def test_Registration_inputs(): input_map = dict(args=dict(argstr='%s', ), collapse_output_transforms=dict(argstr='--collapse-output-transforms %d', usedefault=True, )...
_transform_prefix=dict(argstr='%s', usedefault=True, ), output_warped_image=dict(hash_files=False, ), radius
_bins_item_trait=dict(), radius_bins_stage_trait=dict(), radius_or_number_of_bins=dict(requires=[u'metric_weight'], usedefault=True, ), restore_state=dict(argstr='--restore-state %s', ), sampling_percentage=dict(requires=[u'sampling_strategy'], ), sampling_percentage_item_trait=dict(...
mwrlabs/veripy
contrib/rfc3736/client/client_message_validation.py
Python
gpl-3.0
8,446
0.014208
from contrib.rfc3736.builder import * from contrib.rfc3736.constants import * from contrib.rfc3736.dhcpv6 import DHCPv6Helper from scapy.all import * from veripy.assertions import * class MessageValidationHelper(DHCPv6Helper): def run(self): q = self.restart_and_wait_for_information_request(self.node(1),...
eply message...") self.node(1).send(p) self.node(1).clear_received() self.logger.info("Sending unexpec
ted message...") self.node(1).send(self.packet(p[0])) r1 = self.node(1).iface(0).received(src=(self.target(1).link_local_ip())) assertEqual(0, len(r1), "did not expect to receive any packets") class SolicitMessageTestCase(MessageValidationHelper): """ Solicit Message Verify t...
AsimmHirani/ISpyPi
tensorflow/contrib/tensorflow-master/tensorflow/contrib/tensor_forest/client/random_forest.py
Python
apache-2.0
14,957
0.004747
# 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...
, and training op.""" weights = None keys = None if weights_name and weights_name in features: weights = features.pop(weights_name) if keys_name and keys_name in features: keys = features.pop(keys_name) graph_builder = graph_builder_class(params, device_assigner=device_assigner) inf...
AL or mode == model_fn_lib.ModeKeys.INFER): inference[eval_metrics.INFERENCE_PROB_NAME] = ( graph_builder.inference_graph(features)) if not params.regression: inference[eval_metrics.INFERENCE_PRED_NAME] = math_ops.argmax( inference[eval_metrics.INFERENCE_PROB_NAME], 1)...
abramhindle/UnnaturalCodeFork
python/testdata/launchpad/lib/lp/translations/utilities/tests/test_xpi_import.py
Python
agpl-3.0
15,963
0.000313
# Copyright 2009-2010 Canonical Ltd. This software is licensed under the # GNU Affero General Public License version 3 (see the file LICENSE). """Functional tests for XPI file format""" __metaclass__ = type import re import unittest from zope.component import getUtility from lp.app.interfaces.launchpad import ILau...
ate.getPOTMsgSets()) messages_msgid_list = [] for message in potmsgsets: messages_msgid_list.append(message.msgid_singular.msgid) # Check the common values for all messages. self._assertXpiMessageInvariant(message) if message.msgid_singular.msgid == u'f...
# It's a normal message that lacks any comment. self.assertEquals(message.singular_text, u'FooZilla!') self.assertEquals( message.filereferences, u'jar:chrome/en-US.jar!/test1.dtd(foozilla.name)') self.assertEquals(me...
LeeKamentsky/CellProfiler
BatchProfiler/RunBatch.py
Python
gpl-2.0
28,033
0.005351
""" CellProfiler is distributed under the GNU General Public License. See the accompanying file LICENSE for details. Copyright (c) 2003-2009 Massachusetts Institute of Technology Copyright (c) 2009-2015 Broad Institute All rights reserved. Please see the AUTHORS file for credits. Website: http://www.cellprofiler.org...
batch.timeout = timeout batch.cpcluster = cpcluster batch.project = project batch.memory_limit = memory_limit batch.priority = priority batches.append(batch)
return batches def select(self, batch_id): '''Select a batch from the database''' self.batch_id = batch_id with bpcursor() as cursor: cmd = """ select email, data_dir, queue, batch_size, write_data, time...
lmazuel/azure-sdk-for-python
azure-mgmt-network/azure/mgmt/network/v2018_01_01/models/connectivity_source_py3.py
Python
mit
1,352
0.001479
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
will be initiated. :type resource_id: str :param port: The source port from which a connectivity check will be performed. :type port: int
""" _validation = { 'resource_id': {'required': True}, } _attribute_map = { 'resource_id': {'key': 'resourceId', 'type': 'str'}, 'port': {'key': 'port', 'type': 'int'}, } def __init__(self, *, resource_id: str, port: int=None, **kwargs) -> None: super(Connectivity...
plotly/plotly.py
packages/python/plotly/plotly/validators/choropleth/colorbar/_x.py
Python
mit
472
0.002119
impor
t _plotly_utils.basevalidators class XValidator(_plotly_utils.basevalidators.NumberValidator): def __init__(self, plotly_name="x", parent_name="choropleth.colorbar", **kwargs): super(XValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type...
, -2), **kwargs )
HEG-Arc/marmix
marmix/foobar/admin.py
Python
gpl-3.0
1,025
0.00293
# -*- coding: UTF-8 -*- # admin.py # # Copyright (C) 2014 HES-SO//HEG Arc # # Author(s): Cédric Gaspoz <cedric.gaspoz@he-arc.ch> # # This file is part of MarMix. # # MarMix is free software: you can redistribute
it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version. # # MarMix 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 G...
tendrilinc/marathon-autoscaler
scripts/test_autoscaler.py
Python
apache-2.0
2,665
0.003752
#!/usr/bin/env python """ This script constructs an Marathon application definition for the stress tester container. Be sure to deploy the latest stress tester docker image to the registry before running this. """ import argparse import json import os import sys BASE_PATH = os.path
.dirname(o
s.path.realpath(__file__)) PROJECT_PATH = os.path.dirname(BASE_PATH) sys.path.append(os.path.join(PROJECT_PATH, 'lib/')) from marathon_autoscaler.marathon import Marathon def load_app_definition(): with open(os.path.join(os.getcwd(), "data", "stress_tester_app.json"), 'r') as f: test_app_definition = jso...
cchienhao/data_collector
src/collectors/fitbit/dao.py
Python
apache-2.0
841
0.011891
''' Created on Aug 29, 2015 @author: kevinchien ''' import datetime # from bson import ObjectId from tornado.gen import Task, Return from tornado.gen import coroutine from src.common.logutil import get_logger # f
rom src.core.mongoutil import get_instance # # @coroutine # def update_auth(auth_info): # new_auth_info = auth_info.copy() # new_auth_info['updated_
at'] = datetime.datetime.utcnow() # # criteria = {"user_id": new_auth_info.get('user_id'), # "access_token": new_auth_info.get('access_token'), # "refresh_token": new_auth_info.get('refresh_token')} # # fields = {'$set': new_auth_info} # # result, err...
rcbops/glance-buildpackage
glance/tests/functional/test_s3.py
Python
apache-2.0
9,007
0
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2011 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/...
path = "http://%s:%d/v1/images" % ("0.0.0.0", self.api_port) http = httplib2.Http() response, content = http.request(path, 'POST', headers=headers) self.assertEqual(response.status, 201) # ensure data is refreshed
, previously the size assertion # applied to the metadata returned from the previous GET data = json.loads(content) self.assertEqual(data['image']['size'], FIVE_KB) # checksum is not set for a remote image, as the image data # is not yet retrieved self.assertEqual(data['i...
deepinsight/Deformable-ConvNets
deeplab/function/test_deeplab.py
Python
apache-2.0
3,137
0.003507
# -------------------------------------------------------- # Deformable Convolutional Networks # Copyright (c) 2016 by Contributors # Copyright (c) 2017 Microsoft # Licensed under The Apache-2.0 License [see LICENSE for details] # Modified by Zheng Zhang # -------------------------------------------------------- impor...
m shape data_names = [k[0] for k in test_data.provide_data_single] label_names = ['softmax_label'] max_data_shape = [[('data', (1, 3, max([v[0] for v in config.SCALES]), max([v[1] for v in config.SCALES])))]] # create predictor predictor = Predictor(sym, data_names, label_names, ...
arg_params=arg_params, aux_params=aux_params) # start detection pred_eval(predictor, test_data, imdb, vis=vis, logger=logger)
edmorley/django
docs/_ext/cve_role.py
Python
bsd-3-clause
877
0.002281
""" An interpreted text role to link docs to CVE issues. To use: :cve:`XXXXX` """ from docutils import nodes, utils from docutils.parsers.rst import roles def cve_role(name, rawtext, text, lineno, inliner, options=None, content=None): if options is None: options = {} url_pattern = inliner.document.se...
refuri=url, **options) return [node], [] def setup(app): app.add_config_value('cve_url', None, 'env') app.add_role('cve', cve_role) retur
n {'parallel_read_safe': True}
Azure/azure-sdk-for-python
sdk/core/azure-core/tests/async_tests/test_rest_stream_responses_async.py
Python
mit
9,371
0.003095
# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See LICENSE.txt in the project root for # license information. # ------------------------------------------------------------------------- from azure....
, stream=True) iter = response.iter_raw() data = b"" async for d in iter: data += d assert data == b"test" @pytest.mark.asyncio async def test_iter_read_back_and_forth(client): # thanks to McCoy Patiño for this test! # while this test may look like it's exposing bug...
or # the reason why the code flow is like this, is because the 'iter_x' functions don't # actually read the contents into the response, the output them. Once they're yielded, # the stream is closed, so you have to catch the output when you iterate through it request = HttpRequest("GET", "/basic/string")...
stackforge/compute-hyperv
compute_hyperv/tests/unit/test_coordination.py
Python
apache-2.0
3,659
0
# Copyright 2015 Intel # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except i
n 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, softwa
re # 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 limitations # under the License. import inspect import mock import tooz.coordination impor...