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
sileht/deb-openstack-nova
nova/tests/test_virt_drivers.py
Python
apache-2.0
19,029
0
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright 2010 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 # # http://www.apache.org/licenses/LICENSE-2.0...
nfirmed_resizes(self): self.connection.poll_unconfirmed_resizes(10) @catch_notimplementederror def test_migrate_disk_and_power_off(self): instance_ref, network_info = self._get_running_instanc
e() instance_type_ref = test_utils.get_test_instance_type() self.connection.migrate_disk_and_power_off( self.ctxt, instance_ref, 'dest_host', instance_type_ref, network_info) @catch_notimplementederror def test_pause(self): instance_ref, network_info = self._get_...
smouzakitis/molly
molly/views.py
Python
apache-2.0
711
0.014104
from django.shortcuts import render from django.http import HttpResponse from django.utils import simplejson as json import ner def index(request): params = {'current': 'home'} return render(request, 'index.html', params) def name_entity_recognition(request): if request.method == 'GET': #Get the ...
t_array = request.GET.getlist('text[]') data = {} i=0 for text in input_text_array: #Recognize all strings / texts cont
ained in the array data[i] = ner.recognize(text.strip()) i+=1 return HttpResponse(json.dumps(data), content_type = "application/json")
bnoi/scikit-tracker
sktracker/trajectories/__init__.py
Python
bsd-3-clause
533
0.001876
# -*- coding: utf-8 -*- from __future__ import unicode_literals from __future__ import division from __future__ import absolute_import from __future__ import print_function import logging log = logging.getLogger(__name__) from .trajectories import Trajectories try: # pragma: no cover from . import draw __a...
ortError: # pragm
a: no cover log.warning('''Matplotlib can't be imported,''' '''drawing module won't be available ''') __all__ = ['Trajectories']
cclljj/AnySense_7688
lib/gas_co2_s8.py
Python
gpl-3.0
1,189
0.044575
import mraa import time from multiprocessing import Queue,Process import move_avge CO2_BYTE = 9 NUM_INCOME_BYTE = 13 S8_message = b"\xFE\x04\x00\x00\x00\x04\xE5\xC6" class sensor(Process): def __init__(self, q): Process.__init__(self) self.q = q self.u=mraa.Uart(1) self.u.setBaudRate(9600) self.u.setMod...
YTE]*256 + bytedata[CO2_BYTE+1] self.co2_avg.add(CO2) else: return def checksum
(self, dstr): return True def get_data(self): CO2 = self.co2_avg.get() ret = { 'CO2': CO2 } return ret def run(self): while True: self.u.writeStr(S8_message) self.u.flush() if self.u.dataAvailable(): time.sleep(0.05) getstr = self.u.readStr(NUM_INCOME_BYTE) if len(getstr) == NUM_...
rubendibattista/python-ransac-library
pyransac/features.py
Python
bsd-3-clause
6,919
0.021246
from __future__ import division import abc import numpy as n import scipy.linalg as linalg import scipy.optimize as opt import scipy.spatial.distance as dist class Feature(object): ''' Abstract class that represents a feature to be used with :py:class:`pyransac.ransac.RansacFeature` ''' __metaclass...
rgs: num_points (numpy.ndarray): the number of points to be returned Returns: coords (numpy.ndarray): a num_points x 2 numpy array t
hat contains the points coordinates ''' theta = n.linspace(0,2*n.pi,num_points) x = self.xc + self.radius*n.cos(theta) y = self.yc + self.radius*n.sin(theta) return n.vstack((x,y)) class Exponential (Feature): ''' Feature Class for an...
chrislit/abydos
abydos/distance/_upholt.py
Python
gpl-3.0
4,479
0
# Copyright 2018-2020 by Christopher C. Little. # This file is part of Abydos. # # Abydos 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 versio...
X| + |Y|} +
\sqrt{\Big(\frac{2 \cdot |X \cap Y|}{|X| + |Y|}\Big)^2 + 8\frac{2 \cdot |X \cap Y|}{|X| + |Y|}}\Bigg) In :ref:`2x2 confusion table terms <confusion_table>`, where a+b+c+d=n, this is .. math:: sim_{Upholt}(X, Y) = \frac{1}{2}\Bigg(-\frac{2a}{2a+b+c} + ...
porolakka/motioneye-jp
src/update.py
Python
gpl-3.0
1,486
0.007402
# Copyright (c) 2013 Calin Crisan # This file is part of motionEye. # # motionEye 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. # #...
: version1 = [int(n) for n in version1.split('.')] version2 = [int(n) for n in version2.split('.')] len1 = len(version1) len
2 = len(version2) length = min(len1, len2) for i in xrange(length): p1 = version1[i] p2 = version2[i] if p1 < p2: return -1 elif p1 > p2: return 1 if len1 < len2: return -1 elif len1 > len2: return 1 ...
fstagni/DIRAC
WorkloadManagementSystem/Client/Matcher.py
Python
gpl-3.0
14,961
0.008689
""" Encapsulate here the logic for matching jobs Utilities and classes here are used by MatcherHandler """ __RCSID__ = "$Id" import time from DIRAC import gLogger from DIRAC.FrameworkSystem.Client.MonitoringClient import gMonitor from DIRAC.Core.Utilities.PrettyPrint import printDict from DIRAC.Co
re.Security import Properties from DIRAC.ConfigurationSystem.Client.Helpers import Registry from DIRAC.ConfigurationSystem.Client.Helpers.Operations import Operations from DIRAC.WorkloadManagementSystem.Cli
ent.Limiter import Limiter from DIRAC.WorkloadManagementSystem.DB.TaskQueueDB import TaskQueueDB, singleValueDefFields, multiValueMatchFields from DIRAC.WorkloadManagementSystem.DB.PilotAgentsDB import PilotAgentsDB from DIRAC.WorkloadManagementSystem.DB.JobDB import JobDB from DIRAC.WorkloadManagementSystem.DB.JobLog...
callen/Alky-Reborn
Convertor/setup.py
Python
lgpl-3.0
303
0.033003
#!/usr/bin/env python # encoding: utf-8 """ setup.py Created by Cody Brocious on 2006-12-21. Copyright (c) 2006 Falling Leaf Systems. All rights reserved. """ from dis
tutils.core import setup import py2app setup( app = ['Convert.py'], options
= dict( py2app=dict( argv_emulation=True ) ) )
jfzhang95/lightML
SupervisedLearning/Neural Layers/methods.py
Python
mit
3,801
0.006969
#!usr/bin/env python #-*- coding:utf-8 -*- """ @author: James Zhang @date: """ import numpy as np import theano import theano.tensor as T from theano.ifelse import ifelse from theano.tensor.shared_randomstreams import RandomStreams from collections import OrderedDict import copy import sys sys.setrecursionlimit(10000...
ffle(0, 'x') output 2 dim array # return prob of each label. prob1+...+probn = 1 r
eturn e_x / e_x.sum(axis=1).dimshuffle(0, 'x') # dimshuffle(0, 'x') output 2 dim array def sigmoid(X): return 1 / (1 + T.exp(-X)) def dropout(X, dropout_prob=0.0): retain_prob = 1 - dropout_prob srng = RandomStreams(seed=1234) X *= srng.binomial(X.shape, p=retain_prob, dtype=theano.config.floatX) ...
ojii/readthedocs.org
readthedocs/rtd_tests/tests/test_redirects.py
Python
mit
3,374
0.005039
from django.test import TestCase from builds.models import Version from projects.models import Project class RedirectTests(TestCase): fixtures = ["eric", "test_data"] def setUp(self): self.client.login(username='eric', password='test') r = self.client.post( '/dashboard/import/', ...
{'repo_type': 'git', 'name': 'Pip', 'tags': 'big, fucking, monkey', 'default_branch': '', 'project_url': 'http://pip.rtfd.org', 'repo': 'https://github.com/fail/sauce',
'csrfmiddlewaretoken': '34af7c8a5ba84b84564403a280d9a9be', 'default_version': 'latest', 'privacy_level': 'public', 'version_privacy_level': 'public', 'description': 'wat', 'documentation_type': 'sphinx'}) pip = Project.objects.get(slug='pip') ...
alexAubin/hovercraft
hovercraft/tests/test_data/__init__.py
Python
mit
17,298
0
HTML_OUTPUTS = { 'simple': ( b'<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><body>' b'<div id="impress"><div class="step step-level-1" step="0" ' b'data-rotate-x="0" data-rotate-y="0" data-rotate-z="0" ' b'data-scale="1" data-x="0" data-y="0" data-z="0"><h1 ' b'...
eet" href="css/style.css" media="all"></link><link ' b'rel="stylesheet" href="css/print.css" media="print"></link><link ' b'rel="stylesheet" href="css/impressConsole.css" ' b'media="screen,projection"></link><link rel="stylesheet" ' b'href="extra.css" media="all"></link><script type="tex...
te-x="0" data-rotate-y="0" ' b'data-rotate-z="0" data-scale="1" data-x="0" data-y="0" data-z="0">' b'<h1 id="simple-presentation">Simple Presentation</h1><p>This ' b'presentation has two slides, each with a header and some text.</p>' b'</div><div class="step step-level-1" step="1" data-r...
castlecms/castle.cms
castle/cms/search.py
Python
gpl-2.0
5,355
0.000747
from castle.cms.behaviors.search import ISearch from castle.cms.social import COUNT_ANNOTATION_KEY from collective.elasticsearch import mapping from collective.elasticsearch import query from collective.elasticsearch.interfaces import IAdditionalIndexDataProvider from plone import api from zope.annotation.interfaces im...
f sdata: data['searchterm_pins'] = [ t.lower() for t in sdata.searchterm_pins or []
if t] else: data['searchterm_pins'] = [] try: data['SearchableText'] = u'%s %s' % ( existing_data.get('SearchableText', ''), u' '.join(data['searchterm_pins'])) except UnicodeError: pass try: data['contrib...
Agent007/deepchem
examples/low_data/tox_graph_conv_one_fold.py
Python
mit
2,851
0.009821
""" Train low-data Tox21 models with graph-convolution. Test last fold only. """ from __future__ import print_function from __future__ import division from __future__ import unicode_literals import numpy as np np.random.seed(123) import tensorflow as tf tf.set_random_seed(123) import deepchem as dc from datasets impor...
set support_generator = dc.data.SupportGener
ator(test_dataset, n_pos, n_neg, n_trials) # Compute accuracies task_scores = {task: [] for task in range(len(test_dataset.get_task_names()))} for trial_num, (task, support) in enumerate(support_generator): print("Starting trial %d" % trial_num) # Number of features o...
sje397/p2pool
p2pool/skiplists.py
Python
gpl-3.0
2,559
0.007034
from p2pool.util import forest, math class WeightsSkipList(forest.TrackerSkipList): # share_count, weights, total_weight def get_delta(self, element): from p2pool.bitcoin import data as bitcoin_data share = self.tracker.shares[element] att = bitcoin_data.target_to_average_attempts(...
): return share_count1 + share_count2, math.add_dicts(weights1, weights2), total_weight1 + total_weight2, total_donation_weight1 + total_donation_weight2 def initial_solution(self, start, (max_shares, desired_weight)): assert desired_weight % 65535 == 0, divmod(desired_weight, 65535) re...
def apply_delta(self, (share_count1, weights_list, total_weight1, total_donation_weight1), (share_count2, weights2, total_weight2, total_donation_weight2), (max_shares, desired_weight)): if total_weight1 + total_weight2 > desired_weight and share_count2 == 1: assert (desired_weight - total_weight1) ...
Answeror/torabot
torabot/mods/bilibili/spy/bilibili/spiders/__init__.py
Python
mit
6,671
0.0006
# This package will contain the spiders of your Scrapy project # # Please refer to the documentation for information on how to create and manage # your spiders. import json from urllib import urlencode from scrapy import log from scrapy.http import Request from scrapy.selector import Selector from scrapy.contrib.load...
: yield r names[r['username']] = 1 return list(gen()) def make_recommendation(post): return Recommendation( user_uri=po
st['user_uri'], username=post['upper'], ) def failed(query, message): log.msg('parse failed: %s' % message, level=log.ERROR) return Result(ok=False, query=query, message=message) class SearchResultPostLoader(ItemLoader): default_item_class = SearchResultPost default_input_processor = Id...
xiaonanln/myleetcode-python
src/96. Unique Binary Search Trees.py
Python
apache-2.0
560
0.05
class Solution(object): def numTrees(self, n): """ :type n: int
:rtype: int """ if n <= 1: return 1 nt = [0] * (n+1) nt[0] = 1 nt[1] = 1 for i in xrange(2, n+1): # i numbers total = 0 for k in xrange(i): # let kth number be the root, left has k numbers, right has i-k-1 numbers total += nt[k] * nt[i-k-1] # print n, total nt[i] = total ret...
olution().numTrees(3) # print Solution().numTrees(4)
FutureMind/drf-friendly-errors
runtests.py
Python
mit
2,452
0.001223
#! /usr/bin/env python """ based on https://github.com/tomchristie/django-rest-framework/blob/master/runtests.py """ from __future__ import print_function import pytest import sys import os import subprocess PYTEST_ARGS = { 'default': ['tests'], 'fast': ['tes
ts', '-q'], } FLAKE8_ARGS = ['rest_framework_friendly_errors', 'tests', '--ignore=E501'] sys.path.append(os.path.dirname(__file__)) def exit_on_failure(ret, message=None): if ret: sys.exit(ret) def flake8_main(args): print('Running flake8 code linting') ret = subprocess.call(['flake8'] + args...
def split_class_and_function(string): class_string, function_string = string.split('.', 1) return "%s and %s" % (class_string, function_string) def is_function(string): # `True` if it looks like a test function is included in the string. return string.startswith('test_') or '.test_' in string def i...
e-democracy/edem.content.logo
setup.py
Python
gpl-3.0
1,382
0.014472
# -*- coding=utf-8 -*- import os from setuptools import setup, find_packages from version import get_version version = get_version() setup(name='edem.content.logo', version=version, description="Logos for forums.e-democracy.org", long_description=open("README.txt").read() + "\n" + op...
%3Aaction=list
_classifiers for values classifiers=[ "Development Status :: 5 - Production/Stable", "Environment :: Web Environment", "Framework :: Zope2", "Intended Audience :: Developers", "License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)", "Natural Language :: Engl...
zhongliliu/muse
muse/Calculators/DirectOpt.py
Python
gpl-2.0
2,930
0.021843
""" MUSE -- A Multi-algorithm-collaborative Universal Structure-prediction Environment Copyright (C) 2010-2017 by Zhong-Li Liu 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 version 2 of t...
e nkept <= int(indict['Num_Keep'][0]): if int(indict['IfReOptKept'][0]): with open('../log.muse','a') as logfile: print >>logfile, "Direct reopt. ..." spgnum = Findspg.Findspg(Old_cry[i][1]) if spgnum[0] not in spglist: spglist.append(spgnu...
tr(ng)+'-'+str(nn),direct=True,sort=True,vasp5=True) nk,enth,BigDict = Submit.Submit(BigDict,nu,ng,nn,Old_cry) nn += 1 nkept +=1 else: spgnum = Findspg.Findspg(Old_cry[i][1]) if spgnum[0] not in spglist: ...
dpogue/korman
korman/ui/ui_toolbox.py
Python
gpl-3.0
2,031
0.003447
# This file is part of Korman. # # Korman 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. # # Korman is distributed i...
= col.operator("object.plasma_toggle_all_objects", icon="OBJECT_DATA", text="Enable All") enable_all.
enable = True all_plasma_objects = all((i.plasma_object.enabled for i in bpy.context.selected_objects)) col.operator("object.plasma_toggle_selected_objects", icon="VIEW3D", text="Disable Selection" if all_plasma_objects else "Enable Selection") disable_all = col.operator("object.plasma_toggle_al...
domenicosolazzo/TweetMining
tests/test_tweetMining.py
Python
mit
13,682
0.007528
import unittest from tweetMining import TweetMining, TweetProxy, TestProxy, HttpProxy import nltk class TweetMiningTestCase(unittest.TestCase): def setUp(self): self.tweetMining = TweetMining(proxy='test') self.search = self.tweetMining.search(q="twitter") self.userInfoResponse = self.tweet...
s_exists(self): self.assertTrue(callable(getattr(self.tweetMining, "_getRTSources"))) def test_getRTSources_returnsAList(self): actual = self.tweetMining._getRTSources('RT @user la la la') self.assertIsInstance(actual, list) def test_getRTSources_raisesAnExceptionWithWrongInput(self): ...
) self.assertRaises(Exception, self.tweetMining._getRTSources, []) self.assertRaises(Exception, self.tweetMining._getRTSources, {}) # buildRetweetGraph def test_buildRetweetGraph_exists(self): self.assertTrue(callable(getattr(self.tweetMining, "buildRetweetGraph"))) def test_buildRet...
mgeorgehansen/FIFE_Technomage
demos/shooter/scripts/common/baseobject.py
Python
lgpl-2.1
7,040
0.035938
# -*- coding: utf-8 -*- # #################################################################### # Copyright (C) 2005-2010 by the FIFE team # http://www.fifengine.net # This file is part of FIFE. # # FIFE is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General ...
not, write to the # Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # #################################################################### from fife import fife
from fife.fife import FloatRect as Rect SHTR_DEFAULT = 0 SHTR_PLAYER = 1 SHTR_LASTBOSS = 2 SHTR_PROJECTILE = 3 SHTR_ENEMYSHIP = 4 SHTR_POWERUP = 5 class SpaceObject(object): """ Space Object is the base class for all game objects. """ def __init__(self, scene, name, findInstance=True): """ ...
vpetersson/docker-py
tests/integration/models_services_test.py
Python
apache-2.0
7,604
0
import unittest import docker from .. import helpers from .base import TEST_API_VERSION class ServiceTest(unittest.TestCase): @classmethod def setUpClass(cls): client = docker.from_env(version=TEST_API_VERSION) helpers.force_leave_swarm(client) client.swarm.init('127.0.0.1', listen_a...
ION) service = client.services.create( name=helpers.random_name(), image="alpine", command="sleep 300" ) assert service in client.services.list() service.remove() assert se
rvice not in client.services.list() def test_tasks(self): client = docker.from_env(version=TEST_API_VERSION) service1 = client.services.create( name=helpers.random_name(), image="alpine", command="sleep 300" ) service2 = client.services.create( ...
hone5t/pyquick
basic/string1.py
Python
apache-2.0
3,606
0.013588
#!/usr/bin/python -tt # Copyright 2010 Google Inc. # Licensed under the Apache License, Version 2.0 # http://www.apache.org/licenses/LICENSE-2.0 # Google's Python Class # http://code.google.com/edu/languages/google-python-class/ # Basic string exercises # Fill in the code for the functions below. main() is already se...
the above functions with interesting inputs, # using test() to check if each result is correct or not. def main(): print 'donuts' # Each line c
alls donuts, compares its result to the expected for that call. test(donuts(4), 'Number of donuts: 4') test(donuts(9), 'Number of donuts: 9') test(donuts(10), 'Number of donuts: many') test(donuts(99), 'Number of donuts: many') print print 'both_ends' test(both_ends('spring'), 'spng') test(both_ends('H...
alex/sqlalchemy
test/orm/test_froms.py
Python
mit
95,771
0.010076
from sqlalchemy.testing import eq_, assert_raises, assert_raises_message import operator from sqlalchemy import * from sqlalchemy import exc as sa_exc, util from sqlalchemy.sql import compiler, table, column from sqlalchemy.engine import default from sqlalchemy.orm import * from sqlalchemy.orm import attributes from s...
s.nodes, \ cls.classes.Order, cls.tables.orders, cls.tables.addresses mapper(User, users, properties={ 'addresses':relationship(Address, backref='user', order_by=addresses.c.id), 'orders':relationship(Order, backref='user', order_by=orders.c.id), # o2m, m2o }) ...
s={ 'dingaling':relationship(Dingaling, uselist=False, backref="address") #o2o }) mapper(Dingaling, dingalings) mapper(Order, orders, properties={ 'items':relationship(Item, secondary=order_items, order_by=items.c.id), #m2m 'address':relationship(Address), ...
dwadler/QGIS
python/plugins/processing/algs/saga/SagaAlgorithm.py
Python
gpl-2.0
20,651
0.003099
# -*- coding: utf-8 -*- """ *************************************************************************** SagaAlgorithm.py --------------------- Date : August 2012 Copyright : (C) 2012 by Victor Olaya Email : volayaf at gmail dot com *************************...
else: layer = self.parameterAsRasterLayer(parameters, param.name(), context) exportCommand = self.exportRasterLayer(param.name(), layer) if exportCommand is not None: comma
nds.append(exportCommand) else: if parameters[param.name()].source().lower().endswith('sdat'): self.exportedLayers[param.name()] = parameters[param.name()].source()[:-4] + 'sgrd' if parameters[param.name()].source().lower().endswith('sgrd')...
mdrasmus/spimap
test/all_terms.py
Python
gpl-2.0
4,112
0.009971
import sys, os import pygsl import pygsl.sf while "python" not in os.listdir("."): os.chdir("..") sys.path.append("python") import spidir from rasmus.common import * from rasmus.bio import phylo from test import * if os.system("which xpdf 2>/dev/null") != 0: rplot_set_viewer("display") def exc_default(f...
in treeids: tree_correct = read_tree("test/data/flies.nt/%s/%s.tree" % (treeid, treeid)) align = read_fasta("test/data/flies.nt/%s/%s.align" % (treeid, treeid)) phylo.hash_order_tree(tree_correct)
print >>out, treeid print >>out, "correct" drawTree(tree_correct, out=out) stree = read_tree("test/data/flies.norm.stree") gene2species = phylo.read_gene2species("test/data/flies.smap") params = spidir.read_params("test/data/flies.nt.para...
agharibi/linchpin
linchpin/provision/InventoryFilters/OpenstackInventory.py
Python
gpl-3.0
1,255
0
#!/usr/bin/env python import StringIO from InventoryFilter import InventoryFilter class OpenstackInventory(InventoryFilter): def get_host_ips(self, topo): host_public_ips = [] for group in topo['os_server_res']: grp = group.get('openstack', []) if isinstance(grp, list): ...
for server in grp: host_public_ips.append(str(server['accessIPv4'])) if
isinstance(grp, dict): host_public_ips.append(str(grp['accessIPv4'])) return host_public_ips def get_inventory(self, topo, layout): if len(topo['os_server_res']) == 0: return "" inven_hosts = self.get_host_ips(topo) # adding sections to respective host g...
CarterBain/Medici
ib/client/msg_wrapper.py
Python
bsd-3-clause
6,312
0.003961
__author__ = 'oglebrandon' import logging as logger import types from ib.ext.EWrapper import EWrapper def showmessage(message, mapping): try: del(mapping['self']) except (KeyError, ): pass items = mapping.items() items.sort() print '### %s' % (message, ) for k, v in items: ...
event in events: try: listener(self,event,msg) except (Exception,): self.unregister(listener) errmsg = "Exception in message dispatch: Handler '{0}' " \ "unregistered for event " \ ...
del self.listeners[listener] class ReferenceWrapper(EWrapper,Observable): # contract = None # tickerId # field # price def __init__ (self,subs={}): super(ReferenceWrapper, self).__init__() self.orderID = None self.subscriptions = subs def setSubscriptions (self,sub...
quisas/albus
cli_tools/openpyxl/tests/test_named_range.py
Python
agpl-3.0
6,909
0.002461
# Copyright (c) 2010-2014 openpyxl # # 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, distr...
(DATADIR, 'reader', 'workbook.xml')) try: content = handle.read() named_ranges = read_named_ranges(content, DummyWB()) eq_(["My Sheeet!$D$8"], [str(range) for range in named_ranges]) finally: handle.close() def test_oddly_shaped_named_ranges(): ranges_counts = ((4, 'TEST_RA...
check_ranges(ws, count, range_name): eq_(count, len(ws.range(range_name))) wb = load_workbook(os.path.join(DATADIR, 'genuine', 'merge_range.xlsx'), use_iterators = False) ws = wb.worksheets[0] for count, range_name in ranges_counts: yield check_ranges, ws, count, ...
everAspiring/Sentiment-Analysis
PickleAlgos.py
Python
gpl-3.0
5,592
0.007332
import nltk import random import pickle from nltk.classify.scikitlearn import SklearnClassifier from sklearn.naive_bayes import MultinomialNB, BernoulliNB from sklearn.svm import LinearSVC from sklearn.linear_model import LogisticRegression, SGDClassifier from nltk.classify import ClassifierI from statistics im...
le.dump(BernoulliNB_classifier, save_classifier, protocol=2) save_classifier.close() LinearSVC_classifier = SklearnClassifier(LinearSVC()) LinearSVC_classifier.train(training_set) print("LinearSVC_classifier accuracy percent:", (nltk.classify.accuracy(LinearSVC_classifier, testing_set))*100) save_classif...
se() LogisticRegression_classifier = SklearnClassifier(LogisticRegression()) LogisticRegression_classifier.train(training_set) print("LogisticRegression_classifier accuracy percent:", (nltk.classify.accuracy(LogisticRegression_classifier, testing_set))*100) save_classifier = open...
ScriptingBeyondCS/CS-35
week_0_to_2/tree_analysis/recipe_analysis_examples.py
Python
mit
4,728
0.006768
import os import os.path import random import recipe_generator import subprocess import shutil #Comparing all recipes, which uses the fewest ingredients? ...kinda hacky def fewest_ingredients(path): """ Takes a path and returns the recipe txt file with the fewest ingredients in the tree specified by that p...
fewest_ingredients = i fewest_ingredients_file_path = os.path.join(root, f) return fewest_ingredients_file_path, (fewest_ingredients-7) #Check if a given recip
e is a savory pie def is_savory(recipe): """ Takes a recipe and determines if it is Savory """ r = recipe.read() if "Savory" in r: return True else: return False #Check if a given recipe is a sweet pie def is_sweet(recipe): """ Takes a recipe and determines if it is Sweet ""...
FrodoTheTrue/safeurl
tests/tests.py
Python
mit
1,050
0
from unittest import TestCase from safeurl.core import getRealURL class MainTestCase(TestCase): def test_decodeUrl(self): self.assertEqual(getRealURL('http://bit.ly/1gaiW96'), 'https://www.yandex.ru/') def test_decodeUrlArray(self): self.assertEqual( getRe...
'Failed') def test_errorDecodeUrlArray(self): self.assertEqual( getRealURL( ['http://bit.ly.wrong/wrong', 'http://bit.ly.wrong/wrong']), ['Failed', 'Failed']) def test_errorWithOkDecodeUrlArray(self): self.assertEqual( getRealURL(['http:/...
//bit.ly/1gaiW96', 'http://bit.ly.wrong/wrong']), ['Failed', 'https://www.yandex.ru/', 'Failed'])
Valloric/ycmd
ycmd/identifier_utils.py
Python
gpl-3.0
8,517
0.019493
# Copyright (C) 2014-2020 ycmd contributors # # This file is part of ycmd. # # ycmd 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. # #...
D_STRING_REGEX ) def IdentifierRegexForFiletype( filetype ): return FILETYPE_TO_IDENTIFIER_REGEX.get
( filetype, DEFAULT_IDENTIFIER_REGEX ) def ReplaceWithEmptyLines( regex_match ): return '\n' * ( len( SplitLines( regex_match.group( 0 ) ) ) - 1 ) def RemoveIdentifierFreeText( text, filetype = None ): return CommentAndStringRegexForFiletype( filetype ).sub( ReplaceWithEmptyLines, text ) def ExtractIdenti...
OpenFurry/submitify
submitify/views/test_calls.py
Python
mit
1,704
0
from submitify.tests import ( TestCase, # CallMixin, # GuidelineMixin, # NotificationMixin, # ReviewMixin, # SubmissionMixin, # UserMixin, ) class TestListCalls(TestCase): def test_lists_open_calls(self): self.assertTrue(True) def test_lists_other_calls_if_asked(self): ...
ubmit_if_reader(self): pass class TestCreateCall(TestCase): def test_form_renders(self): pass def test_form_saves(self): pass def test_guidelines_save(self): pass class TestEditCall(TestCase): def test_owner_only(self): pass def test_form_renders(self):...
pass class TestInviteReader(TestCase): def test_reader_invited(self): pass def test_cant_invite_owner(self): pass class TestInviteWriter(TestCase): def test_writer_invited(self): pass def test_cant_invite_owner(self): pass def test_cant_invite_unless_invite_on...
justacec/bokeh
examples/app/timeout.py
Python
bsd-3-clause
1,560
0.001923
''' Present a plot updating according to a set of fixed timeout intervals. Use the ``bokeh serve`` command to run the example by executing: bokeh serve timeout.py at your command prompt. Then navigate to the URL http://localhost:5006/timeout in your browser. ''' import numpy as np from bokeh.palettes im...
e=(0, 100), toolbar_location=None) p.border_fill_color = 'black' p.background_fill_color = 'black' p.outline_line_color = None p.grid.grid_line_color = None p.rect(x=50, y=50, width=80, height=80, line_alpha=0.5, line_color="darkgrey", fill_color=None) r = p.text(x=[], y=[], text=[], text_color=[], ...
plot to document curdoc().add(p) def make_callback(i): ds = r.data_source def func(): if i == N-1: ds.data['x'].append(50) ds.data['y'].append(95) ds.data['text'].append("DONE") ds.data['text_color'].append("white") else: ds.data['x']...
SKA-ScienceDataProcessor/integration-prototype
sip/examples/flask_processing_controller/app/api/scheduling_block_list.py
Python
bsd-3-clause
2,351
0
# -*- coding: utf-8 -*- """Scheduling Block Instance List API resource.""" import logging from http import HTTPStatus from random import choice from flask import Blueprint, request from .utils import add_scheduling_block, get_root_url, missing_db_response from ..db.client import ConfigDb BP = Blueprint("scheduling-...
block_ids = DB.get_sched_block_instance_ids() # Loop over SBIs and add summary of each to the list of SBIs in the # response. for block in DB.get_block_details(block_ids): block_id = block['id'] LOG.debug('Adding SBI %s to list',
block_id) LOG.debug(block) block['num_processing_blocks'] = len(block['processing_block_ids']) temp = ['OK'] * 10 + ['WAITING'] * 4 + ['FAILED'] * 2 block['status'] = choice(temp) try: del block['processing_block_ids'] except KeyError: pass ...
pixies/academic
membro_profile/views.py
Python
gpl-3.0
4,644
0.004741
#-*- encoding: utf-8 -*- from django.contrib.auth import authenticate, login, logout from django.http import HttpResponseRedirect, HttpResponse from django.shortcuts import render_to_response, RequestContext, render from membro_profile.forms import MembroForm, MembroProfileForm, EditProfileForm from django.contrib.aut...
s import Submissao def some_view(request): if not request.user.is_authenticated(): return HttpResponse("You are logged in.") else: return HttpResponse("You are not logged in.") # Create your views here. def register(r
equest): context = RequestContext(request) registered = False if request.method == 'POST': membro_form = MembroForm(data=request.POST) membro_profile_form = MembroProfileForm(data=request.POST) if membro_form.is_valid() and membro_profile_form.is_valid(): membro = membr...
hudvin/brighteye
facenet_experiments/vgg_utils/vgg_downloader.py
Python
apache-2.0
2,983
0.004358
import Image import argparse from StringIO import StringIO from urlparse import urlparse from threading import Thread import httplib, sys from Queue import Queue import numpy as np from scipy import misc import os def doWork(): while True: task_data = q.get() print task_data url = task_dat...
filename = x[0] url = x[1] image_path = os.path.join(args.output_dir, dir_name, filename + '.' + args.output_format) error_path = os.path.join(args.output_dir, dir_name, filename + '.err') q.put({ "ur...
"error_path":error_path }) q.join() except KeyboardInterrupt: sys.exit(1) def parse_arguments(argv): parser = argparse.ArgumentParser() parser.add_argument('dataset_descriptor', type=str, help='Directory containing the text files with the...
blossomica/airmozilla
airmozilla/comments/tests/test_jinja_helpers.py
Python
bsd-3-clause
1,016
0
from nose.tools import eq_, ok_ from django.test import TestCase from airmozilla.comments.templatetags.jinja_helpers import ( gravatar_src, obscure_email, ) class TestHelpers(TestCase): def test_gravatar_src_http(self): email = '[email protected]' result = gravatar_src(email, False) ...
in result) eq_(result.count('?'), 1) def test_gravatar_src_https(self): email = '[email protected]' result = gravatar_src(email, True) ok_(result.startswith('//secure.gravatar.com')) def test_obscure_email(self): email = '[email protected]' result
= obscure_email(email) eq_(result, '[email protected]')
RobotsAndPencils/terrible
tests/test_run.py
Python
bsd-3-clause
3,415
0.000586
#!/usr/bin/env python # -*- coding: utf-8 -*- from preggy import expect import click from click.testing import CliRunner from terrible.run import compile_template from tests.base import TestCase import os class CompileTemplateTestCase(TestCase): def test_compile_template(self): base_dir = os.path.dirnam...
t_code).to_be_greater_than(0) # Give a file instead of a directory for template path result = runner.invoke(compile_template, [ '--template-path', tfstate]) expect(res
ult.exit_code).to_be_greater_than(0) # Give a path instead of an acutal template for --template result = runner.invoke(compile_template, [ '--template-path', template_path, '--template', template_path]) expect(result.exit_code).to_be_greater_than(0) # Give an in...
ar4s/django
tests/timezones/tests.py
Python
bsd-3-clause
58,810
0.002041
import datetime import re import sys from contextlib import contextmanager from unittest import SkipTest, skipIf from xml.dom.minidom import parseString try: import zoneinfo except ImportError: from backports import zoneinfo try: import pytz except ImportError: pytz = None from django.contrib.auth.mo...
try: orig_timezone = connection.settings_dict['TIME_ZONE'] connection.settings_dict['TIME_ZONE'] = timezone # Clear cached prop
erties, after first accessing them to ensure they exist. connection.timezone del connection.timezone connection.timezone_name del connection.timezone_name yield finally: connection.settings_dict['TIME_ZONE'] = orig_timezone # Clear cached properties, after fir...
markovmodel/thermotools
test/test_callback.py
Python
lgpl-3.0
2,723
0.002203
# This file is part of thermotools. # # Copyright 2015, 2016 Computational Molecular Biology Group, Freie Universitaet Berlin (GER) # # thermotools 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...
imate( np.ones(shape=(T, M, M), dtype=np.intc), np.zeros(shape=(T, M), dtype=np.float64), maxiter=10, maxerr=-1.0, save_convergence_info=1, callback=generic_
callback_stop) assert_allclose(therm_energies, 0.0, atol=1.0E-15) assert_allclose(conf_energies, np.log(M), atol=1.0E-15) assert_allclose(log_lagrangian_mult, np.log(M + dtram.get_prior()), atol=1.0E-15) assert_true(increments.shape[0] == 1) assert_true(loglikelihoods.shape[0] == 1)
niallrmurphy/simlir
instrumentation.py
Python
gpl-2.0
8,970
0.014939
#!/usr/bin/env python # encoding: utf-8 """ instrumentation.py This file defines the various 'events' that can happen in the simlir system. Every time an object in the simulation does something significant, it sends a message to a global instrumentation object, which currently has a mild wrapping around them for textu...
print "*** ADD PREFIX EVENT for '%s' with prefix '%s'" % (args[0], args[1]) return args def RemovePrefixEvent(self, args): if self.verbosity > 1: print "*** REMOVE PREFIX EVENT with route '%s', owner '%s' and note '%s'" % \
(args[0], args[1], args[2]) return args def NeedsSpaceEvent(self, args): # TODO(niallm): implement return args def GetsSpaceEvent(self, args): # TODO(niallm): implement return args def TradeSpaceEvent(self, args): # TODO(niallm): implmenet return args def FindUnusedEvent...
detiber/lib_openshift
test/test_v1_project.py
Python
apache-2.0
1,236
0.003236
# coding: utf-8 """ OpenAPI spec version: Generated by: https://github.com/swagger-api/swagger-codegen.git 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 ...
ng, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from __future__ import absolute_import import o...
import sys import unittest import lib_openshift from lib_openshift.rest import ApiException from lib_openshift.models.v1_project import V1Project class TestV1Project(unittest.TestCase): """ V1Project unit test stubs """ def setUp(self): pass def tearDown(self): pass def testV1Proje...
AndreyBalabanov/python_training
test/test_del_contact.py
Python
apache-2.0
633
0.00316
from model.contact import Contact import random def test_delete_some_contact(app
, db, check_ui): if len(db.get_contact_list()) == 0: app.contact.add(Contact(firstname="test")) old_contacts = db.get_contact_list() contact = random.choice(old_contacts) app.contact.delete_contact_by_id(contact.id) assert len(old_contacts) - 1 == app.contact.count() new_contacts = db.ge...
tacts, key=Contact.id_or_max) == sorted(app.contact.get_contact_list(), key=Contact.id_or_max)
HopeFOAM/HopeFOAM
ThirdParty-0.1/ParaView-5.0.1/VTK/Common/Core/Testing/Python/TestOverloads.py
Python
gpl-3.0
2,562
0.005074
"""Test overloaded method resolution in VTK-Python The wrappers should call overloaded C++ methods using similar overload resolution rules as C++. Python itself does not have method overloading. Created on Feb 15, 2015 by David Gobbi """ import sys import vtk from vtk.test import Testing class TestOverloads(Testi...
vtkObject()) self.assertEqual(a.GetValue(0), vtk.vtkVariant(2.5)) self.assertEqual(a.GetValue(1).GetType(), vtk.VTK_OBJECT) # same, but this one is via "const vtkVariant&" argument a = vtk.vtkDenseArray[float]() a.Resize(1) a.SetVariantValue(0, 2.5) self.assertEqu...
Testing.main([(TestOverloads, 'test')])
rbarrois/factory_boy
tests/cyclic/self_ref.py
Python
mit
467
0
# -*- coding: utf-8 -*- # Copyright: See the LICENSE file. """Helper to test
circular factory dependencies.""" import factory class TreeElement(object): def __init__(self, name, parent): self.parent = parent self.name = name class TreeElementFactory(factory.Factory):
class Meta: model = TreeElement name = factory.Sequence(lambda n: "tree%s" % n) parent = factory.SubFactory('tests.cyclic.self_ref.TreeElementFactory')
kamitchell/py2app
py2app/simpleio.py
Python
mit
5,394
0.002225
""" A simple file-system like interface that supports both the regular filesystem and zipfiles """ __all__ = ('FileIO', 'ReadOnlyIO') import os, time, zipfile class FileIO (object): """ A simple interface that makes it possible to write simple filesystem structures using the interface that's exposed b...
nm in zf.namelist(): if nm == rest: raise IOError("%r is not a directory in %r"%(path, _zf)) if nm.startswith(rest): result.add(nm[len(rest):].split('/')[0]) return list(result) def _zippath(self, path, strict=True): """...
either ``(zipfilename, zippath)`` or ``(None, path)`` If ``zipfilename`` is not None is points to a zipfile that may contain the file as ``zippath``. Otherwise the file is definitely not in a zipfile Raises ``IOError`` when the file doesn't exist, but won't check if the file ...
bqbn/addons-server
src/olympia/bandwagon/tasks.py
Python
bsd-3-clause
1,228
0.002443
from datetime import datetime from django.db.models import Count import olympia.core.logger from olympia.amo.celery import task from olympia.amo.decorators import use_primary_db from .models import Collection, CollectionAddon log = olympia.core.logger.getLogger('z.task') @task @use_primary_db def collection_met...
nt == old_count: continue # We want to set addon_count & modified without triggering post_save # as it would cause an infinite loop (this task is called on # post_save). So we update queryset.update() and set modified ourselves # instead of relying on auto_now behaviour. ...
on_id).update( addon_count=addon_count, modified=now )
rskwan/mt
mt/mt/settings/base.py
Python
apache-2.0
2,992
0.003008
import os from unipath import Path from django.core.exceptions import ImproperlyConfigured import dj_database_url def env_var(var_name): """Get the environment variable var_name or return an exception.""" try: return os.environ[var_name] except KeyError: msg = "Please set the environment ...
ORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, {
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] TIME_ZONE = 'America/Los_Angeles' LANGUAGE_CODE = 'en-us' USE_I18N = False USE_L10N = True USE_TZ = True STATIC_URL = '/static/'...
klim-iv/phantomjs-qt5
src/webkit/Tools/Scripts/webkitpy/tool/steps/suggestreviewers_unittest.py
Python
bsd-3-clause
2,415
0.001656
# Copyright (C) 2009 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 list of conditions and the f...
RIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT L...
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import unittest2 as unittest from webkitpy.common.system.outputcapture import OutputCapture from webkitpy.tool.mocktool import MockOptions, MockTool from webkitpy.tool.steps.suggestreviewers import ...
teeple/pns_server
work/install/node-v0.10.25/deps/v8/tools/run-tests.py
Python
gpl-2.0
13,499
0.010371
#!/usr/bin/env python # # Copyright 2012 the V8 project authors. 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 # noti...
VARIANT_FLAGS = [[], ["--stress-opt", "--always-opt"], ["--nocrankshaft"]] MODE_FLAGS = { "debug" : ["--nobreak-on-ab
ort", "--nodead-code-elimination", "--enable-slow-asserts", "--debug-code", "--verify-heap"], "release" : ["--nobreak-on-abort", "--nodead-code-elimination"]} SUPPORTED_ARCHS = ["android_arm", "android_ia32", "arm", "ia32", ...
zhengxinxing/bespeak_meal
__init__.py
Python
mit
120
0.01087
# 主要是为了使用中文显示 app 于 admin 界面 default_app_config = 'bespeak_meal.apps.Be
speak_meal_config'
jiocloudservices/jcsclient
src/jcsclient/compute_api/instance.py
Python
apache-2.0
7,005
0.001713
# Copyright (c) 2016 Jiocloud.com, Inc. or its affiliates. All Rights Reserved # # 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 right...
s, version, args): params = {} params['Action'] = utils.dash_to_camelcase(args[0]) params['Version'] = version args = args[1:] parser = utils.get_argument_parser() parser.add_argument('--instance-ids', nargs='+', required=True)
args = parser.parse_args(args) utils.populate_params_from_cli_args(params, args) return requestify.make_request(url, verb, headers, params) def stop_instances(url, verb, headers, version, args): params = {} params['Action'] = utils.dash_to_camelcase(args[0]) params['Version'] = version args...
IT-SeanWANG/CodeJam
2017_2nd/Q2_Refer2.py
Python
apache-2.0
1,200
0.003333
import copy max_pro = 0 def find(list_foot_pmt, max_pmt): max_pmtn = max_pmt a = list_foot_pmt.pop(0) for i in range(0, len(list_foot_pmt)): max_pmt = max_pmtn list_foot_pmt1 = copy.deepcopy(list_foot_p
mt) b =list_foot_pmt1.pop(i) max_pmt += pro_matrix[a][b] if len(list_foot_p
mt1) > 0: find(list_foot_pmt1, max_pmt) else: global max_pro if max_pmt > max_pro: max_pro = max_pmt return N = int(input()) pro_matrix = [] for j in range(0, N): str_tmp = input() pro_row = str_tmp.split(" ") pro_matrix.a...
juancarlospaco/vagrant
main.py
Python
gpl-3.0
23,005
0.005651
# -*- coding: utf-8 -*- # PEP8:OK, LINT:OK, PY3:OK ############################################################################# ## This file may be used under the terms of the GNU General Public ## License version 2.0 or 3.0 as published by the Free Software Foundation ## and appearing in the file LICENSE.GPL includ...
} end ''' BASE = path.abspath(path.join(path.expanduser("~"), 'vagrant')) ############################################################################### class Main(plugin.Plugin): " Main Class " def initialize(self, *args, **kwargs): " Init Main
Class " super(Main, self).initialize(*args, **kwargs) self.completer, self.dirs = QCompleter(self), QDirModel(self) self.dirs.setFilter(QDir.AllEntries | QDir.NoDotAndDotDot) self.completer.setModel(self.dirs) self.completer.setCaseSensitivity(Qt.CaseInsensitive) self.com...
pankajn17/intern
web/db.py
Python
gpl-3.0
40,670
0.007303
""" Database API (part of web.py) """ __all__ = [ "UnknownParamstyle", "UnknownDB", "TransactionError", "sqllist", "sqlors", "reparam", "sqlquote", "SQLQuery", "SQLParam", "sqlparam", "SQLLiteral", "sqlliteral", "database", 'DB', ] import time try: import datetime except ImportError: datetime = Non...
items.append(')') return SQLQuery(items) def reparam(string_, dictionary): """ Takes a string and a dictionary and interpolates the string using values from the dictionary. Returns an `SQLQuery` for the result. >>> reparam("s = $s", dict(s=True))
<sql: "s = 't'"> >>> rep
intenthq/code-challenges
python/connected_graph/test_connected_graph.py
Python
mit
910
0.002198
import unittest from .connected_graph import Node class TestConnectedGraph(unittest.TestCase): def test_acyclic_graph(self): """Example graph fr
om https://upload.wikimedia.org/wikipedia/commons/0/03/Directed_acyclic_graph_2.svg""" n9 = Node(9) n10 = Node(10) n8 = Node(8, [n9]) n3 = Node(3, [n8, n10]) n2 = Node(2) n11 = Node(11, [n2, n9, n10]) n5 = Node(5, [n11]) self.assertTrue(n3.connected_to(n...
_to(n9)) self.assertTrue(n11.connected_to(n9)) self.assertTrue(n5.connected_to(n9)) self.assertFalse(n9.connected_to(n5)) self.assertFalse(n9.connected_to(n11)) self.assertFalse(n3.connected_to(n11)) def test_connected_to_self(self): n1 = Node(1) self.assertT...
kentya6/swift
utils/benchmark/Graph/generate-data.py
Python
apache-2.0
748
0.002674
import pygraph.algorithms.generators as gen import pygraph.algorithms.accessibility as acc import pygraph.algorithms.minmax as minmax graph =
gen.generate(5000, 10000, weight_range=(50, 2000)) components = acc.connected_components(graph) nodes = [g for g in graph if components[g] == 1] print "GRAPH NODES" for n in graph.nodes(): print n print "GRAPH EDGES" for e in graph.edges(): if components[e[0]] == 1: w = graph.edge_weight(e) pr...
is not None: # print "(%d, %d)" % (k, MST[k]) # else: # print "(%d, %d)" % (k, k)
mmcfarland/model-my-watershed
deployment/cfn/utils/constants.py
Python
apache-2.0
369
0
EC2_
INSTANCE_TYPES = [ 't2.micro', 't2.small', 't2.medium' ] RDS_INSTANCE_TYPES = [ 'db.t2.micro' ] ELASTICACHE_INSTANCE_TYPES = [ 'cache.t2.micro' ] ALLOW_ALL_CIDR = '0.0.0.0/0' VPC_CIDR = '10.0.0.0/16' GRAPHITE = 2003 GRAPHITE_WEB = 8080 HTTP = 80 HTTPS = 443 KIBANA = 5601 POSTGRESQL = 5432 REDIS ...
4 SSH = 22 STATSITE = 8125
tommybobbins/pipoegusca
test2.py
Python
gpl-2.0
347
0.002882
#!/usr/bin/python import time import d
atetime import logging import os import syslog #from os import path, access, R_OK from time import sleep import os import RPi.GPIO as GPIO GPIO.setmode
(GPIO.BCM) # 22 = Relay 1, 27 = Relay 2, 17 = Relay 3 GPIO.setup(27, GPIO.OUT) GPIO.setup(27, False) sleep(2) GPIO.setup(27, True) sleep(2) GPIO.cleanup()
liveaverage/baruwa
src/baruwa/manage.py
Python
gpl-2.0
575
0.006957
#!/usr/bin/env python from django.core.management import execute_manager try: import settings # Assumed to be in the same directory. except ImportError: import sys sys.stderr.write("Error: Can't find the file 'settings.py' in" " the directory
containing %r. It appears you've customized "
"things.\nYou'll have to run django-admin.py, passing it your" " settings module.\n(If the file settings.py does indeed exist," " it's causing an ImportError somehow.)\n" % __file__) sys.exit(1) if __name__ == "__main__": execute_manager(settings)
Masood-M/yalih
mechanize/_mechanize.py
Python
apache-2.0
31,059
0
"""Stateful programmatic WWW navigation, after Perl's WWW::Mechanize. Copyright 2003-2006 John J. Lee <[email protected]> Copyright 2003 Andy Lester (original Perl code) This code is free software; you can redistribute it and/or modify it under the terms of the BSD or ZPL 2.1 licenses (see the file COPYING.txt included w...
t=False, timeout=timeout)
def open(self, url_or_request, data=None, timeout=_sockettimeout._GLOBAL_DEFAULT_TIMEOUT): '''
marguslaak/django-xadmin
xadmin/models.py
Python
bsd-3-clause
4,934
0.001216
import json import django from django.db import models from django.conf import settings from django.contrib.contenttypes.models import ContentType from django.utils.translation import ugettext_lazy as _ from django.core.urlresolvers import reverse from django.core.serializers.json import DjangoJSONEncoder from django.d...
def __unicode__(self):
return "%s %s" % (self.user, self.key) class Meta: verbose_name = _(u'User Setting') verbose_name_plural = _('User Settings') class UserWidget(models.Model): user = models.ForeignKey(AUTH_USER_MODEL, verbose_name=_(u"user")) page_id = models.CharField(_(u"Page"), max_length=256) ...
braubar/braubar-pi
test/testReadTempSocket.py
Python
gpl-3.0
139
0.021583
from helper.readtempsocket import ReadTempSocket class asd:
def __init__(self): r = ReadTempSocket()
r.run() asd()
teeple/pns_server
work/install/Python-2.7.4/Tools/freeze/makeconfig.py
Python
gpl-2.0
1,676
0.002983
import re import sys # Write the config.c file never = ['marshal', '__main__', '__builtin__', 'sys', 'exceptions', '_warnings'] def makeconfig(infp, outfp, modules, with_ifdef=0): m1 = re.compile('-- ADDMODULE MARKER 1 --') m2 = re.compile('-- ADDMODULE MARKER 2 --') while 1: line = infp.readline...
): if not sys.argv[3:]: print 'usage: python makeconfig.py config.c.in outputfile', print 'modulename ...' sys.exit(2) if sys.argv[1] == '-':
infp = sys.stdin else: infp = open(sys.argv[1]) if sys.argv[2] == '-': outfp = sys.stdout else: outfp = open(sys.argv[2], 'w') makeconfig(infp, outfp, sys.argv[3:]) if outfp != sys.stdout: outfp.close() if infp != sys.stdin: infp.close() if __name__ ==...
hiveary/hiveary-agent
setup.py
Python
bsd-3-clause
3,550
0.010986
#!/usr/bin/env python """ Hiveary https://hiveary.com Licensed under Simplified BSD License (see LICENSE) (C) Hiveary, Inc. 2013-2014 all rights reserved """ import platform import sys from hiveary import __version__ as version current_platform = platform.system() FROZEN_NAME = 'hiveary-agent' AUTHOR = "Hiveary"...
NAME, version=version, scripts=[script], options=options, data_files=data_files, ) sys.argv.remove('bdist_esky') sys.argv.app
end('py2exe') # used for the versioninfo resource class Target(object): def __init__(self, **kw): self.__dict__.update(kw) self.version = version self.company_name = 'Hiveary' self.name = "HivearyService" script = Target( description='Hiveary Agent Service Launcher', modu...
saxix/django-concurrency
setup.py
Python
mit
2,485
0.000805
#!/usr/bin/env python import ast import os import re from setuptools import find_packages, setup from setuptools.command.test import test as TestCommand ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__))) init = os.path.join(ROOT, 'src', 'concurrency', '__init__.py') _version_re = re.compile(r'__version...
st.literal_eval(_name_re.search(
content).group(1))) base_url = 'https://github.com/saxix/django-concurrency/' class PyTest(TestCommand): def finalize_options(self): TestCommand.finalize_options(self) self.test_args = ['tests'] self.test_suite = True def run_tests(self): # import here, cause outside the eggs...
Perkville/django-tastypie
tastypie/resources.py
Python
bsd-3-clause
100,856
0.001874
from __future__ import unicode_literals from copy import copy, deepcopy from datetime import datetime import logging import sys from time import mktime import traceback import warnings from wsgiref.handlers import format_date_time import django from django.conf import settings from django.conf.urls import url from dj...
code_keys, is_valid_jsonp_callback_value, string_to_python, trailing_slash, ) from tastypie.utils.mime import determine_format, build_conten
t_type from tastypie.validation import Validation from tastypie.compat import get_module_name, atomic_decorator def sanitize(text): # We put the single quotes back, due to their frequent usage in exception # messages. return escape(text).replace('&#39;', "'").replace('&quot;', '"') class ResourceOptions...
cyllyq/nutsbp-test
test_case/demo.py
Python
gpl-2.0
407
0.004914
# _*_ coding:utf-8 _*_ __author__ = 'Y-ling' __date__ = '2017/9/15 11:11' from selenium import webdriver from selenium.common.exceptions import NoSuchElementException import unittest import os
import time import copy import utils from elements_path import LOGIN_
FORM, TOP_BAR, CENTER, CENTER_PERSONAL, CENTER_RESET_PASSWORD, FIND_WAIT_TIME, MY_BP for x in range(70): print utils.random_chinese(1000)
bSr43/capstone
suite/disasm_mc.py
Python
bsd-3-clause
7,561
0.003835
#!/usr/bin/python # Test tool to disassemble MC files. By Nguyen Anh Quynh, 2017 import array, os.path, sys from capstone import * # convert all hex numbers to decimal numbers in a text def normalize_hex(a): while(True): i = a.find('0x') if i == -1: # no more hex number break h...
cs_output2 = cs_output2.replace('$t3', '$11') cs_output2 = cs_output2.replace('$t4', '$12') cs_output2 = cs_output2.replace('$t5', '$13') cs_output2 = cs_output2.replace('$t6', '$14') cs_output2 = cs_output2.replace('$t7', '$15') cs_output2 = cs_output2.repl...
cs_output2 = cs_output2.replace('$s0', '$16') cs_output2 = cs_output2.replace('$s1', '$17') cs_output2 = cs_output2.replace('$s2', '$18') cs_output2 = cs_output2.replace('$s3', '$19') cs_output2 = cs_output2.replace('$s4', '$20') cs_output2 = cs_outpu...
falanxia/tileset_baker
merge.py
Python
mit
9,760
0.003381
#!/usr/bin/python __author__ = 'Martin Samsula' __email__ = '<[email protected]>' import sys import glob import math import xml.etree.ElementTree import os import os.path try: import simplejson except: import json simplejson = json def ds(data): return simplejson.dumps(data, indent=4, default=str) fro...
_height = 0 self.source = '' self.width = 0 self.height =
0 self.first_gid = 0 self.collision_tile = 0 self._image = None self._cut_tiles = {} def out(self): return {'name': self.name, 'tile_width': self.tile_width, 'tile_height': self.tile_height, 'source': self.source, ...
jeremiahyan/odoo
addons/account_edi/models/ir_actions_report.py
Python
gpl-3.0
1,420
0.002113
# -*- coding: utf-8 -*- import io from odoo import models from odoo.tools.pdf import OdooPdfFileReader, OdooPdfFileWriter class IrActionsReport(models.Model): _inherit = 'ir.actions.report' def _post_pdf(self, save_in_attachment, pdf_content=None, res_ids=None
): # OVERRIDE to embed some EDI documents inside the PDF. if self.model == 'account.move' and res_ids and len(res_ids) == 1 and pdf_content: invoice = self.env['account.move'].browse(res_ids) if invoice.is_sale_document() and invoice.state != 'draft': to_embed = i...
reader = OdooPdfFileReader(reader_buffer, strict=False) writer = OdooPdfFileWriter() writer.cloneReaderDocumentRoot(reader) for edi_document in to_embed: edi_document.edi_format_id._prepare_invoice_report(writer, edi_document) ...
lewixliu/git-repo
subcmds/init.py
Python
apache-2.0
20,047
0.007333
# -*- coding:utf-8 -*- # # Copyright (C) 2008 The Android Open Source Project # # 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 re...
manifest") # Tool g = p.add_option_group('repo Version options') g.add_option('--repo-url', dest='repo_url',
help='repo repository location', metavar='URL') g.add_option('--repo-rev', metavar='REV', help='repo branch or revision') g.add_option('--repo-branch', dest='repo_rev', help=optparse.SUPPRESS_HELP) g.add_option('--no-repo-verify', dest='repo_verify', d...
bdh1011/wau
venv/lib/python2.7/site-packages/twisted/plugins/cred_anonymous.py
Python
mit
968
0.003099
# -*- test-case-name: twisted.test.test_strcred -*- # # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ Cred plugin for anonymous logins. """ from zope.interface import implementer from twisted import plugin from twisted.cred.checkers import AllowAnonymousAccess from twisted.cred.strcred im...
.IPlugin) class AnonymousCheckerFactory(object): """ Generates checkers that will authenticate an anonymous request.
""" authType = 'anonymous' authHelp = anonymousCheckerFactoryHelp argStringFormat = 'No argstring required.' credentialInterfaces = (IAnonymous,) def generateChecker(self, argstring=''): return AllowAnonymousAccess() theAnonymousCheckerFactory = AnonymousCheckerFactory()
Huyuwei/tvm
topi/python/topi/nn/sparse.py
Python
apache-2.0
7,132
0.00028
# 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...
ros], dtype of 'int32' sparse_indptr : tvm.Tensor 1-D with shape [n+1], dtype of 'int32' Returns ------- out_data : tvm.Tensor 1-D with shape [nonzeros], dtype of 'float32' out_indices : tvm.Tensor 1-D with shape [nonzeros], dtype of 'int32' out_indptr : tvm.Tensor ...
'int32' """ assert len(sparse_data.shape) == 1, "error in data dimension" assert len(sparse_indices.shape) == 1, "error in indices dimension" assert len(sparse_indptr.shape) == 1, "error in indptr dimension" nnz = get_const_tuple(sparse_data.shape)[0] n = get_const_tuple(sparse_indptr.shape)[0]...
jasonballensky/django-guardian
example_project/posts/urls.py
Python
bsd-2-clause
222
0.009009
from gua
rdian.compat import url, patterns urlpatterns = patterns('posts.views', url(r'^$', view='post_list', name='posts_post_l
ist'), url(r'^(?P<slug>[-\w]+)/$', view='post_detail', name='posts_post_detail'), )
matteoferla/Geobacillus
geo_mutagenesis.py
Python
gpl-2.0
2,769
0.015529
__author__ = 'Matteo' __doc__='''This could be made into a handy mutagenesis library if I had time.''' from Bio.Seq import Seq,MutableSeq from Bio import SeqIO from Bio.Alphabet import IUPAC from difflib import Differ def Gthg01471(): ori=Seq("ATGAGCATAAGTTTATCGGTTCCAAAATGGTTATTAACAGTTTTATCAATTTTATCTTTAGTCGTAGCAT...
ble() print(x.pop(1748-1)) y=x.toseq().translate(to_stop
=1) print(z) print(y) print(list(Differ().compare(str(z),str(y)))) print(len(z),len(y)) if __name__ == "main": pass
theKono/mobile-push
bin/competing_consumer.py
Python
apache-2.0
1,384
0
#!/usr/bin/env python # standard library imports import signal # third party related imports import boto.sqs import ujson # local library imports from mobile_push.config import setting from mobile_push.logger import logger from mobile_push.message_router import MessageRouter keep_running = True def sigterm_handl...
keep_running logger.warn('Receive SIGTER
M') keep_running = False def get_queue(): conn = boto.sqs.connect_to_region(setting.get('sqs', 'region')) return conn.get_queue(setting.get('sqs', 'queue')) def poll_message(queue): message = queue.read(wait_time_seconds=20) if message is None: return try: body = message....
bzamecnik/ml-playground
ml-playground/boston_dataset_exploration/data_analysis.py
Python
mit
6,084
0.006903
''' This script analyzes the Boston housing dataset available via scikit-learn. It generates a textual report and a set of plot images into the 'report' directory. ''' import logging import matplotlib # non-interactive plotting - just outputs the images and doesn't open the window matplotlib.use('Agg') import matplotl...
_hist(col, plot_real) for col in int_cols: plot_hist(col, plot_int) def pairwise_scatter_matrix(df, img_file='pairwise_scatter_matrix.png'): logging.debug('Plotting pairwise sc
atter matrix') grid = sns.pairplot(df) grid.savefig(img_file) plt.close() def pairwise_joint_plots(df, cols): logging.debug('Plotting pairwise joint distributions') cols = sorted(cols) for colA, colB in [(a,b) for a in cols for b in cols if a < b]: file = 'joint_{}_{}.png'.format(colA, ...
pas256/troposphere
troposphere/s3.py
Python
bsd-2-clause
11,735
0
# Copyright (c) 2013, Bob Van Zant <[email protected]> # All rights reserved. # # See LICENSE file for full license. import warnings from . import AWSHelperFn, AWSObject, AWSProperty, Tags from .validators import boolean, positive_integer, s3_bucket_name from .validators import s3_transfer_acceleration_status try: f...
ease use ' '"Transitions" since the former has been deprecated.') if 'NoncurrentVersionTransition' in self.properties: if 'NoncurrentVersionTransitions' not in self.properties: warnings.warn( 'NoncurrentVersionTransition has been deprecated in...
n format to the new format self.properties['NoncurrentVersionTransitions'] = [ self.properties.pop('NoncurrentVersionTransition')] else: raise ValueError( 'Cannot specify both "NoncurrentVersionTransition" and ' '"No...
rogerwang/chromium
tools/checkdeps/checkdeps.py
Python
bsd-3-clause
17,591
0.008925
#!/usr/bin/env python # Copyright (c) 2011 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. """Makes sure that files include headers from allowed directories. Checks DEPS files in the source tree for rules, and applies tho...
additions or subtractions for their own sub-trees. There is an implicit rule for the current directory (where the DEPS file lives) and all of its subdirectori
es. This prevents you from having to explicitly allow the current directory everywhere. This implicit rule is applied first, so you can modify or remove it using the normal include rules. The rules are processed in order. This means you can explicitly allow a higher directory and then take away permissions from sub-p...
asidev/aybu-manager
tests/test_activity_log.py
Python
apache-2.0
7,363
0.001087
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Copyright 2010-2012 Asidev s.r.l. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required b...
d=True, instance=instance) self.assertFalse
(os.path.exists(target)) al.commit() self.assertTrue(os.path.exists(target)) def test_delete(self): al = ActivityLog() testfile = os.path.join(self.tempdir, 'test.txt') with self.assertRaises(OSError): al.add(rm, testfile) al.add(rm, testfile, error_on...
penny4860/SVHN-deep-digit-detector
tests/cifar_loader.py
Python
mit
487
0.008214
import cP
ickle import numpy as np import cv2 def unpickle(file): fo = open(file, 'rb') dict = cPickle.load(fo) fo.close() return dict files = ['../../datasets/svhn/cifar-10-batches-py/data_batch_1'] dict = unpickle(files[0]) images = dict['data'].reshape(-1, 3, 32, 32) labels = np.array(dict['labels']) image...
v2.imshow("", images[1000]) cv2.waitKey(0) cv2.destroyAllWindows()
danriti/python-traceview
docs/conf.py
Python
mit
8,222
0.006324
# -*- coding: utf-8 -*- # # traceview documentation build configuration file, created by # sphinx-quickstart on Fri May 2 20:12:10 2014. # # 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. # #...
template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template nam
es. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. ...
the5fire/wechat
setup.py
Python
apache-2.0
542
0.009225
# coding: utf-8 #!/usr/bin/env python from setuptools import setup, find_packages readme = open('
README.rst').read() setup( name='wecha', version='${version}', description='', long_description=readme, author='the5fire', author_email='[email protected]', url='http://chat.the5fire.com', packages=['src',], package_data={ 'src':['*.py', 'static/*', 'templates/*'], }...
rn', ], )
arm-hpc/allinea_json_analysis
PR_JSON_Scripts/plot_pr_bar.py
Python
apache-2.0
5,284
0.005678
#!/usr/bin/env python # Copyright 2015-2017 ARM Limited # # 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.or
g/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitation...
fras2560/graph-helper
algorithms/critical.py
Python
apache-2.0
49
0
'''
Created on Oct 20, 2015 @author: Dal
las '''
seakers/daphne_brain
AT/migrations/0016_auto_20200909_1730.py
Python
mit
1,470
0.001361
# Generated by Django 3.0.7 on 2020-09-09 22:30 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('daphne_context', '0007_auto_20191111_1756'), ('AT', '0015_auto_20200909_1334'), ] operations = [ mi...
), migrations.RemoveField( model_name='atcontext', name='next_step_pointer', ), migrations.RemoveField( model_name='a
tcontext', name='previous_step_pointer', ), migrations.CreateModel( name='ATDialogueContext', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('all_steps_from_procedure', model...
botswana-harvard/edc-contact
edc_contact/models/call_log.py
Python
gpl-2.0
1,199
0
from django.db import models from django_crypto_fields.fields import EncryptedTextField from edc_base.model.models import BaseUuidModel try: from edc_sync.mixins import SyncMixin except ImportError: SyncMixin = type('SyncMixin', (object, ), {}) from ..managers import CallLogManager class CallLog (SyncMixin...
fier = models.CharField( verbose_name="
Subject Identifier", max_length=50, blank=True, db_index=True, unique=True, ) locator_information = EncryptedTextField( help_text=('This information has been imported from' 'the previous locator. You may update as required.') ) contact_notes =...
Feduch/pyMessengerBotApi
messengerbot/__init__.py
Python
gpl-3.0
174
0.005747
from .api.api import Api from .api.bot_configuration import BotConfiguration from .version import __version__ __all__ = ['A
pi', 'BotConfi
guration'] __version__ = __version__
philanthropy-u/edx-platform
lms/djangoapps/courseware/field_overrides.py
Python
agpl-3.0
11,496
0.001131
""" This module provides a :class:`~xblock.field_data.FieldData` implementation which wraps an other `FieldData` object and provides overrides based on the user. The use of providers allows for overrides that are arbitrarily extensible. One provider is found in `lms.djangoapps.courseware.student_field_overrides` whic...
_key = ENABLED_OVERRIDE_PROVIDE
RS_KEY.format(course_id=unicode(course.id)) enabled_providers = request_cache.data.get(cache_key, NOTSET) if enabled_providers == NOTSET: enabled_providers = tuple( (provider_class for provider_class in cls.provider_classes if provider_class.enabled_for(course)) )...
f5devcentral/f5-cccl
f5_cccl/resource/ltm/policy/action.py
Python
apache-2.0
5,095
0.000196
"""Provides a class for managing BIG-IP L7 Rule Action resources.""" # coding=utf-8 # # Copyright (c) 2017-2021 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:/...
on', None) self._data['httpReply'] = data.get('httpReply', True) # Is this a setVariable action? elif data.get('setVariable', False): self._data['setV
ariable'] = True # Set the variable name and the value self._data['tmName'] = data.get('tmName', None) self._data['expression'] = data.get('expression', None) self._data['tcl'] = True # Is this a replace URI host action? elif data.get('replace', False) an...
cmshobe/landlab
landlab/components/taylor_nonlinear_hillslope_flux/__init__.py
Python
mit
108
0
from .taylor_nonlinear_hillslope_flux import TaylorNonLinearDiffuser __all
__ = ["TaylorNonLinearDiffu
ser"]
alexin-ivan/zfs-doc
filters/pandoc_fignos.py
Python
mit
11,034
0.002991
#! /usr/bin/env python """pandoc-fignos: a pandoc filter that inserts figure nos. and refs.""" # Copyright 2015, 2016 Thomas J. Duck. # All rights reserved. # # 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 Softwa...
rences and remove curly braces around them.""" flag = False for i in
range(len(value)-1)[1:]: if is_braced_ref(i, value): flag = True # Found reference # Remove the braces value[i-1]['c'] = value[i-1]['c'][:-1] value[i+1]['c'] = value[i+1]['c'][1:] return flag # pylint: disable=unused-argument def preprocess(key, value, fmt, ...
louyihua/edx-platform
lms/djangoapps/django_comment_client/management/commands/assign_role.py
Python
agpl-3.0
1,144
0
from optparse import make_option from django.core.management.base import BaseCommand, CommandError from django_comment_common.models import Role from django.contrib.auth.models import User class Command(BaseCommand): option_list = BaseCommand.option_list + ( make_option('--remove', ac...
s, **options): if len(args) != 3: raise CommandError('Usage is assign_role {0}'.format(self.args)) name_or_email, role, course_id = args role = Role.objects.get(name=role, course_id=course_id) if '@' in name_or_email: user = User.objects.get(email=name_or_email...
er.roles.remove(role) else: user.roles.add(role) print 'Success!'
hmpf/nav
tests/functional/netmap_test.py
Python
gpl-3.0
394
0
"""Selenium tests for ne
tmap""" def test_netmap_index_should_not_have_syntax_errors(selenium, base_url): s
elenium.get("{}/netmap/".format(base_url)) log = selenium.get_log("browser") syntax_errors = [ line for line in log if "syntaxerror" in line.get("message", "").lower() and line.get("source") == "javascript" ] assert not syntax_errors
tquilian/exelearningTest
twisted/pb/promise.py
Python
gpl-2.0
3,532
0.001133
# -*- test-case-name: twisted.pb.test.test_promise -*- from twisted.python import util, failure from twisted.internet import defer id = util.unsignedID EVENTUAL, FULFILLED, BROKEN = range(3) class Promise: """I am a promise of a future result. I am a lot like a Deferred, except that my promised result is us...
d = defer.Deferred() self._watchers.append(d) else: d = defer.succeed(self._resolution) return d def _ready(self, resolution): self._resolution = resolution self._state = FULFILLED self._run_methods() def _broken(self, f): self._re...
_method(self, name, args, kwargs): if isinstance(self._resolution, failure.Failure): return self._resolution method = getattr(self._resolution, name) res = method(*args, **kwargs) return res def _run_methods(self): for (name, args, kwargs, result_deferred...