repo_name
stringlengths
5
100
path
stringlengths
4
231
language
stringclasses
1 value
license
stringclasses
15 values
size
int64
6
947k
score
float64
0
0.34
prefix
stringlengths
0
8.16k
middle
stringlengths
3
512
suffix
stringlengths
0
8.17k
albertoconnor/website
wordpress_importer/tests/test_import_command.py
Python
mit
41,498
0.001663
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals import datetime from collections import namedtuple import mock import six from django.conf import settings from django.test import TestCase from django.utils import timezone from wagtail.wagtailcore.models import Page from articles.mode...
'Bob Smith is a person who does stuff.'), ('[email protected]', 'SHORT_BIO', 'He does stuff.'), ('[email protected]', 'userphoto_image_file', 'testcat.jpg'), ] return data @mock.patch('requests.get', local_get_successful) class TestCommandImportFromWordPressUnicodeSlug...
st_post_data import_from_wordpress.Command.get_post_image_data = self.get_test_post_image_data import_from_wordpress.Command.get_data_for_topics = self.get_test_data_for_topics def tearDown(self): self.delete_images() def testCreatesPageWithAsciiSlug(self): command = import_fro...
socialwifi/jsonapi-requests
jsonapi_requests/orm/api.py
Python
bsd-3-clause
376
0
from jsonapi_re
quests import base from jsonapi_requests.orm import registry class OrmApi: def __init__(self, api): self.type_registry = registry.TypeRegistry() self.api = api @classmethod def config(cls, *args, **kwargs): return cls(base.Api.config(*args, **kwargs)) def endpoint(self, path)...
elf.api.endpoint(path)
pekrau/Publications
tests/utils.py
Python
mit
606
0
"Utility functions for the tests." import json def get_settings(**defaults): "Update
the default settings by the contents of the 'settings.json' file." result = defaults.copy() with open("settings.json", "rb") as infile: data = json.load(infile) for key in result: try: result[key] = data[key]
except KeyError: pass if result.get(key) is None: raise KeyError(f"Missing {key} value in settings.") # Remove any trailing slash in the base URL. result["BASE_URL"] = result["BASE_URL"].rstrip("/") return result
Naeka/vosae-app
www/invoicing/api/resources/payment.py
Python
agpl-3.0
2,892
0
# -*- coding:Utf-8 -*- from tastypie import fields as base_fields from tastypie_mongoengine import fields from core.api.utils import TenantResource from invoicing.models import ( Payment, InvoicePayment, DownPaymentInvoicePayment ) from invoicing.api.doc import HELP_TEXT __all__ = ( 'PaymentResource', ) c...
lp_text=HELP_TEXT['payment']['issuer'] ) currency = fields.ReferenceField( to='invoicing.api.resources.CurrencyResource', attribute='currency', help_text=HELP_TEXT['payment']['currency'] ) class Meta(TenantResource.Met
a): excludes = ('tenant',) list_allowed_methods = ('post') detail_allowed_methods = ('get', 'delete',) class InvoicePaymentResource(PaymentBaseResource): related_to = fields.ReferenceField( to='invoicing.api.resources.InvoiceResource', attribute='related_to', help_t...
rec/DMXIS
Macros/Colours/Greens/Dark Green.py
Python
artistic-2.0
199
0.020101
#=============================================================== # DMXIS Macro (c) 2010 db audioware limited #==================
============================================= RgbColour(0,100,0)
11craft/bilsbrowser
examples/appserver/setup.py
Python
gpl-2.0
720
0.004167
from setuptools import setup, find_packages import sys, os version = '0.1' setup( name='appserver', vers
ion=version, description="Sample application server for bilsbrowser", long_description="""\ """, classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers keywords='', author='ElevenCraft Inc.',
author_email='[email protected]', url='http://github.com/11craft/bilsbrowser/', license='MIT', packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), include_package_data=True, zip_safe=False, install_requires=[ 'Django == 1.0.2-final', ], entry_points=""" ...
abramhindle/UnnaturalCodeFork
python/testdata/launchpad/lib/lp/soyuz/browser/tests/test_package_copying_mixin.py
Python
agpl-3.0
8,305
0
# Copyright 2011-2012 Canonical Ltd. This software is licensed under the # GNU Affero General Public License version 3 (see the file LICENSE). """Tests for `PackageCopyin
gMixin`.""" __metaclass__ = type from zope.component import getUtility from zope.security.proxy import removeSecurityProxy from lp.registry.interfaces.pocket import PackagePublishingPocket from lp.services.propertycache import c
achedproperty from lp.soyuz.browser.archive import ( copy_asynchronously, render_cannotcopy_as_html, ) from lp.soyuz.enums import SourcePackageFormat from lp.soyuz.interfaces.archive import CannotCopy from lp.soyuz.interfaces.packagecopyjob import IPlainPackageCopyJobSource from lp.soyuz.interfaces.sourcepa...
jankoslavic/numpy
numpy/lib/shape_base.py
Python
bsd-3-clause
25,676
0.000818
from __future__ import division, absolute_import, print_function import warnings import numpy.core.numeric as _nx from numpy.core.numeric import ( asarray, zeros, outer, concatenate, isscalar, array, asanyarray ) from numpy.core.fromnumeric import product, reshape from numpy.core import vstack, atleast_3d _...
k = 1 while k < Ntot: # increment the index ind[-1] += 1 n = -1 while (ind[n] >= outshape[n]) and (n > (1-nd)): ind[n-1] += 1 ind[n] = 0 n -= 1 i.put(indlist, ind) res = func1d(arr[tuple(...
outarr[tuple(ind)] = res k += 1 return outarr else: Ntot = product(outshape) holdshape = outshape outshape = list(arr.shape) outshape[axis] = len(res) outarr = zeros(outshape, asarray(res).dtype) outarr[tuple(i.tolist())] = res k = 1 ...
DjangoGirls/djangogirls
story/urls.py
Python
bsd-3-clause
161
0
from django.u
rls import path from story.views import StoryListView app_name = "story" urlpatterns = [ path('', StoryList
View.as_view(), name='stories'), ]
nexedi/dream
dream/simulation/Exit.py
Python
gpl-3.0
9,069
0.012681
# =========================================================================== # Copyright 2013 University of Limerick # # This file is part of DREAM. # # DREAM 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 Founda...
Created on 6 Feb 2013 @author: George ''' ''' models the exit of the mod
el ''' # from SimPy.Simulation import now, Process, Resource, infinity, waituntil, waitevent import simpy import xlwt from CoreObject import CoreObject # =========================================================================== # The exit object # =========================================...
sirmar/tetris
tetris/values/test/test_key.py
Python
mit
330
0.00303
from nose.tools import istest, eq_ from tetr
is.values.key import Key class TestKey(object): @istest def same_key_is_equal(self): eq_(Key(
"key"), Key("key")) @istest def key_is_usable_as_key(self): key_dict = { Key("key"): "Value" } eq_(key_dict[Key("key")], "Value")
2asoft/tdesktop
Telegram/build/release.py
Python
gpl-3.0
7,388
0.0134
import os, sys, requests, pprint, re, json from uritemplate import URITemplate, expand from subprocess import call changelog_file = '../../changelog.txt' token_file = '../../../TelegramPrivate/github-releases-token.txt' version = '' commit = '' for arg in sys.argv: if re.match(r'\d+\.\d+', arg): version = arg ...
r, 201) r = requests.get(url + 'repos/telegramdesktop/tdesktop/releases/tags/v' + version) checkResponseCode(r, 200); release_data = r.json() #pp.pprint(release_data) release_id = release_data['id'] print('Release ID: ' + str(release_id)) r = requests.get(url + 'repos/telegramdesktop/tdesktop/releases/' + str(relea...
et in assets: name = asset['name'] found = 0 for file in files: if file['remote'] == name: print('Already uploaded: ' + name) file['already'] = 1 found = 1 break if found == 0: print('Warning: strange asset: ' + name) for file in files: if 'already' in file: continue fil...
chenbojian/SU2
SU2_PY/SU2/io/config.py
Python
lgpl-2.1
30,110
0.016739
#!/usr/bin/env python ## \file config.py # \brief python package for config # \author T. Lukaczyk, F. Palacios # \version 3.2.9 "eagle" # # SU2 Lead Developers: Dr. Francisco Palacios ([email protected]). # Dr. Thomas D. Economon ([email protected]). # # SU2 Developers: Prof....
ror: from ..util.ordered_dict import OrderedDict inf = 1.0e20 # ---------------------------------------------------------------------- # Configuration Class # ---------------------------------------------------------------------- class Config(or
dered_bunch): """ config = SU2.io.Config(filename="") Starts a config class, an extension of ordered_bunch() use 1: initialize by reading config file config = SU2.io.Config('filename') use 2: initialize from dictionary or bunch config = SU2....
christianmemije/kolibri
kolibri/deployment/default/settings/dev.py
Python
mit
206
0
from __f
uture__ import absolute_import, print_function, unicode_literals from .base import * # noqa isort:skip @UnusedWildImport INSTALLED_APPS += ['rest_framewor
k_swagger'] # noqa REST_SWAGGER = True
andymckay/zamboni
services/verify.py
Python
bsd-3-clause
14,089
0.000213
import calendar import json from datetime import datetime from time import gmtime, time from urlparse import parse_qsl, urlparse from wsgiref.handlers import format_date_time import jwt from browserid.errors import ExpiredSignatureError from django_statsd.clients import statsd from receipts import certs from lib.cef_...
urchase, but require a specific type and install. """ try: self.decoded = self.decode() self.check_type('developer-receipt', 'reviewer-receipt') self.check_url(settings.DOMAIN) exce
pt InvalidReceipt, err: return self.invalid(str(err)) return self.ok_or_expired() def check_without_db(self, status): """ This is what test receipts do, no purchase or install check. In this case the return is custom to the caller. """ assert status in [...
balikasg/SemEval2016-Twitter_Sentiment_Evaluation
src/ark-tweet-nlp-0.3.2/scripts/toconll.py
Python
gpl-3.0
595
0.015126
#!/usr/bin/env python # Take the pretsv format and make it CoNLL-like
("supertsv", having tweet metadata headers) import sys,json from datetime import datetime for line in sys.stdin: parts = line.split('\t') tokens = parts[0].split() tags = parts[1].split() try: d = json.loads(parts[-1]) print "TWEET\t{}\t{}".format(d['id'], datetime.strptime(d['created_...
print "{}\t{}".format(tag,tok) print ""
QuantumElephant/horton
data/examples/hf_dft/rks_water_hybgga.py
Python
gpl-3.0
3,728
0.002682
#!/usr/bin/env python #JSON {"lot": "RKS/6-31G(d)", #JSON "scf": "EDIIS2SCFSolver", #JSON "er": "cholesky", #JSON "difficulty": 5, #JSON "description": "Basic RKS DFT example with hyrbid GGA exhange-correlation functional (B3LYP)"} import numpy as np from horton import * # pylint: disable=wildcard-import,unused-w...
r analysis. Note that the CDIIS_EDIIS algorithm can only really construct # an optimized density m
atrix and no orbitals. mol.title = 'RKS computation on water' mol.energy = ham.cache['energy'] mol.obasis = obasis mol.orb_alpha = orb_alpha mol.dm_alpha = dm_alpha # useful for post-processing (results stored in double precision): mol.to_file('water.h5') # CODE BELOW IS FOR horton-regression-test.py ONLY. IT IS NOT...
ewbankkit/cloud-custodian
tools/c7n_azure/c7n_azure/resources/key_vault.py
Python
apache-2.0
10,984
0.001092
# Copyright 2018 Capital One Services, 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 # # Unless required by applicable law or agreed to in...
.compare_permissions(p['permissions'], self.permissions): re
turn False return True @staticmethod def compare_permissions(user_permissions, permissions): for v in user_permissions.keys(): if user_permissions[v]: if v not in permissions.keys(): # If user_permissions is not empty, but allowed permissions is e...
aendinalt/pymodoro
pomodoro.py
Python
gpl-2.0
4,117
0.000972
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'aen' import pygame import sys from pygame.locals import USEREVENT, QUIT, MOUSEBUTTONDOWN def pomodoro(): pygame.mixer.pre_init(frequency=44100, size=-16, channels=1, buffer=512) pygame.init() # set up the window font = pygame.font.Font('fr...
top_icon_x + 64) \ and (stop_icon_y <= click_y <= stop_icon_y + 64): return True else: return False def pomodoro_run(pomodoro_time): pomo_start_sound.play() timeleft = pomodoro_time pygame.time.set_
timer(USEREVENT + 1, 1000 * 60) pygame.time.set_timer(USEREVENT + 2, 867) return timeleft def pomodoro_stop(): pygame.time.set_timer(USEREVENT + 1, 0) pygame.time.set_timer(USEREVENT + 2, 0) def pomodoro_end(): pomo_end_sound.play() pomodoro_stop() if __name__ == '__main__': pomodoro()
google/iree
integrations/tensorflow/test/python/iree_tf_tests/uncategorized/linspace_test.py
Python
apache-2.0
1,322
0.009077
# Copyright 2020 The IREE Authors # # Licensed under the Apache License v2.0 with LLVM Exceptions. # See https://llvm.org/LICENSE.txt for license information. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception from absl import app from iree.tf.support import tf_test_utils import
numpy as np import tensorflow.compat.v2 as tf class LinspaceModule(tf.Module): def __init__(self): pass @tf.function(input_signature=[ tf.TensorSpec([], tf.float32), tf.TensorSpec([], tf.float32) ]) def linspace(self, start, stop): # 'num' is const because XLA's iota operation does not s...
edModuleTestCase): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._modules = tf_test_utils.compile_tf_module(LinspaceModule) def test_linspace(self): def linspace(module): start = np.array(10., dtype=np.float32) stop = np.array(12., dtype=np.float32) mod...
dymkowsk/mantid
scripts/Interface/ui/reflectometer/refl_gui.py
Python
gpl-3.0
64,194
0.002648
# pylint: disable = too-many-lines, invalid-name, line-too-long, too-many-instance-attributes, # pylint: disable = too-many-branches,too-many-locals, too-many-nested-blocks from __future__ import (absolute_import, division, print_function) try: from mantidplot import * except ImportError: canMantidPlot = False...
Data" self.__search_settings = "Mantid/ISISReflGui/Search" self.__column_settings = "Mantid/ISISReflGui/Columns" self.__icat_download_ke
y = "icat_download" self.__ads_use_key = "AlgUse" self.__alg_migration_key = "AlgUseReset" self.__live_data_frequency_key = "frequency" self.__live_data_method_key = "method" self.__group_tof_workspaces_key = "group_tof_workspaces" self.__stitch_right_key = "stitch_right"...
s20121035/rk3288_android5.1_repo
external/chromium_org/chrome/common/extensions/docs/server2/document_renderer_test.py
Python
gpl-3.0
5,797
0.002588
#!/usr/bin/env python # Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import unittest from document_renderer import DocumentRenderer from server_instance import ServerInstance from test_file_system import...
itute(self): document = 'hello world' text, warnings = self._Render(document) self.assertEqual(document, text) self.assertEqual([], warnings)
text, warnings = self._Render(document, render_title=True) self.assertEqual(document, text) self.assertEqual(['Expected a title'], warnings) def testTitles(self): document = '<h1>title</h1> then $(title) then another $(title)' text, warnings = self._Render(document) self.assertEqual(document...
garyjyao1/ansible
lib/ansible/modules/extras/cloud/cloudstack/cs_securitygroup_rule.py
Python
gpl-3.0
14,213
0.005841
#!/usr/bin/python # -*- coding: utf-8 -*- # # (c) 2015, René Moser <[email protected]> # # This file is part of Ansible # # Ansible 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 Lice...
ty_group is defined type: string sample: default protocol: description: protocol of the rule. returned: success type: string sample: tcp start_
port: description: start port of the rule. returned: success type: int sample: 80 end_port: description: end port of the rule. returned: success type: int sample: 80 ''' try: from cs import CloudStack, CloudStackException, read_config has_lib_cs = True except ImportError: has_lib_cs = False...
AnsgarSchmidt/sensomatic
server/Tank.py
Python
apache-2.0
9,629
0.007685
import os import time import json import datetime import requests import threading import ConfigParser import paho.mqtt.client as mqtt from InformationFetcher import InformationFetcher from Template import TemplateMatcher from requests.auth import HTTPBasicAuth SECOND = 1 MINUTE = 60 * SE...
nOffset"))) moonPhase = self._info.getMoonPhase(self
._config.get("TANK", "Location")) moonElevation, _ = self._info.getMoonPosition() if (dawn < now < sunrise): duration = sunrise - dawn done = now - dawn self._daystate = Tank.DAWN self._sunpercentage = int((done.total_seconds() / dura...
facelessuser/SublimeRandomCrap
sublime_info.py
Python
mit
2,894
0.00311
""" SublimeInfo Sublime Plugin. Show info about the system and the current Sublime Text instance. ``` ////////////////////////////////// // Info Commands ////////////////////////////////// { "caption": "Sublime Info", "command": "sublime_info" }, ``` Licensed under MIT Copyright (...
ware is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO TH
E WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER ...
sciCloud/OLiMS
lims/controlpanel/bika_labcontacts.py
Python
agpl-3.0
4,479
0.004465
from dependencies.dependency import ClassSecurityInfo from dependencies.dependency import schemata from dependencies import atapi from dependencies.dependency import registerType from dependencies.dependency import permissions from dependencies.dependency import getToolByName from lims.browser.bika_listing import BikaL...
obj.getFullname() items[x]['Department'] = obj.getDepartmentTitle() items[x]['BusinessPhone'] = obj.getBusinessPhone()
items[x]['Fax'] = obj.getBusinessFax() items[x]['MobilePhone'] = obj.getMobilePhone() items[x]['EmailAddress'] = obj.getEmailAddress() items[x]['replace']['Fullname'] = "<a href='%s'>%s</a>" % \ (items[x]['url'], items[x]['Fullname']) return items sche...
5monkeys/python-email-reply-parser
email_reply_parser/parser.py
Python
mit
7,227
0.000415
""" Ported from https://github.com/github/email_reply_parser EmailReplyParser is a small library to parse plain text email content. The goal is to identify which fragments are quoted, part of a signature, or original body content. We want to support both top and bottom posters, so no simple "REPLY ABOVE HERE" conten...
> blah blah > blah blah ... and signatures: this is some text -- Bob http://homepage.com/~bob Each of these are parsed into Fragment objects. EmailReplyParser also attempts to figure out which of these blocks s
hould be hidden from users. """ import re class Fragment(object): """ Represents a group of paragraphs in the email sharing common attributes. Paragraphs should get their own fragment if they are a quoted area or a signature. """ def __init__(self, quoted, first_line): self.signature =...
Jokeren/neon
loader/test/raw_to_wav.py
Python
apache-2.0
136
0
import nump
y as np from scipy.io.wavfile import write a = np.fromfile('/tmp/file.raw', dtype='int16') write('/tmp/file.wav', 16000, a)
wadobo/socializa
backend/game/models.py
Python
agpl-3.0
3,494
0.004293
import re from django.contrib.auth.models import User from django.db import models from common.models import ExtraBase CHALLENGES_TYPE = ( ('p', 'playable player'), ('np', 'not playable player'), ) class Challenge(models.Model, ExtraBase): name = models.CharField(max_length=200, blank=True, null=True)...
ge, related_name="games") author = models.ForeignKey(User, related_name="games", blank=True, null=True) auto_assign_clue = models.BooleanField(default=True) visible_players = models.BooleanField(default=True) extra = models.TextField(max_length=1024, blank=True, null=T
rue) # options in extra: # {"options": # [ # {"type": "text", "question": "who is the killer?"}, # {"type": "option", "question": "with which weapon?", # "answers": ["knife", "rope", "gun", "bare hands", "venom"]}, # ... # ] # } def get_desc_html(self): # sea...
heineman/algorithms-nutshell-2ed
PythonCode/adk/knapsack.py
Python
mit
4,073
0.009084
""" Unbounded knapsack: *(http://www.mathcs.emory.edu/~cheung/Courses/323/Syllabus/DynProg/knapsack2.html """ class Item: def __init__(self, value, weight): """Create item with given value and weight. """ self.value = value self.weight = weight def __str__(self): r...
weight total += numAdd * item.value return (total, selections) def knapsack_unbounded (items, W): """ Compute unbounded knapsack solution (any number of each item is available) for set of items with corresponding weights and values. Return total weight and sele
ction of items. """ n = len(items) progress = [0] * (W+1) progress[0] = -1 m = [0] * (W + 1) for j in range(1, W+1): progress[j] = progress[j-1] best = m[j-1] for i in range(n): remaining = j - items[i].weight if remaining >= 0 and m[rem...
breandan/java-algebra-system
examples/sicora.py
Python
gpl-2.0
382
0.04712
# # jython examples for jas. # $Id$ # import sys; from jas import Ring, Ideal fr
om jas import startLog, terminate # sicora, e-gb example r =
Ring( "Z(t) L" ); print "Ring: " + str(r); print; ps = """ ( ( 2 t + 1 ), ( t**2 + 1 ) ) """; f = r.ideal( ps ); print "Ideal: " + str(f); print; #startLog(); g = f.eGB(); print "seq e-GB:", g; print "is e-GB:", g.iseGB(); print;
thoreg/raus-mit-den-kids
rmdk/location/forms.py
Python
mit
275
0
# -*- coding: utf-8 -*- from django import forms from location.models import Address class Address
AdminForm(forms.ModelForm): class Meta: model = Address widgets = { 'description':
forms.Textarea(attrs={'cols': 80, 'rows': 20}), }
scorpiontahir02/easysub
src/easysub/subscene.py
Python
mit
2,817
0.035144
import os import urlparse import zipfile import requests from bs4 import BeautifulSoup from downloader import Downloader from common import Subtitles, User class Subscene(object): def __init__(self): super(Subscene, self).__init__() self._base_url = u'http://subscene.com/' self._search_url = self._get_full_ur...
n subs def search(self, query): if not query: return list() data = { u'q': query, u'l': None } r = requests.get(self._search_url, params=data, cookies=self._cookies, timeout=self._timeout) if r.status_code == 200: return self._parse_search_results_source(r.text) def _extract_sub_zip(self, ...
z: with z.open(z.namelist()[0]) as sz, open(sub_path, u'wb') as so: so.write(sz.read()) return True except Exception, e: pass return False def download(self, sub, path): r = requests.get(sub.page_url) if r.status_code == 200: soup = self._get_soup(r.text) sub.url = self._get_full_...
lfalvarez/nouabook
elections/tests/photo_loader_tests.py
Python
gpl-3.0
1,842
0.005429
# coding=utf-8 from elections.tests import VotaInteligenteTestCase as TestCase from elections.models import Election from django.core.urlresolvers import reverse from candideitorg.models import Candidate from django.core.management import call_command class PhotoLoaderCase(TestCase): def setUp(self): supe...
elf.assertEquals(otro.photo, 'http://www.2eso.info/sinonimos/wp-content/uploads/2013/02/feo1.jpg') def test_if_the_candidate_does_not_exist_it_does_it_for_the_rest(self): call_command('photo_loader', 'elections/tests/fixtures/candidate_photo_url.csv', verbosity=0) jano = Can
didate.objects.get(name=u"Alejandro Guillier") otro = Candidate.objects.get(name=u"Manuel Rojas") self.assertEquals(jano.photo, 'http://upload.wikimedia.org/wikipedia/commons/7/76/Alejandro_Guillier.jpg') self.assertEquals(otro.photo, 'http://www.2eso.info/sinonimos/wp-content/uploads/2013/02/f...
ifduyue/sentry
src/sentry/identity/pipeline.py
Python
bsd-3-clause
2,192
0.001825
from __future__ import absolute_import, print_function import logging from django.contrib import messages from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect from django.utils import timezone from django.utils.translation import ugettext_lazy as _ from sentry.pipeline import Pip...
external_id=identity['id'], defaults=defaults, ) if not created: identity.update(**defaults) messages.add_message(self.request, messages.SUCCESS, IDENTITY_LINKED.format( identity_provider=self.provider.nam
e, )) self.state.clear() # TODO(epurkhiser): When we have more identities and have built out an # identity management page that supports these new identities (not # social-auth ones), redirect to the identities page. return HttpResponseRedirect(reverse('sentry-account-s...
prasannav7/ggrc-core
src/ggrc/models/section.py
Python
apache-2.0
3,107
0.003862
# Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file> # Licensed under ht
tp://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # Created By: [email protected] # Maintained By: [email protected]
from ggrc import db from ggrc.models.directive import Directive from ggrc.models.mixins import CustomAttributable from ggrc.models.mixins import Described from ggrc.models.mixins import Hierarchical from ggrc.models.mixins import Hyperlinked from ggrc.models.mixins import Noted from ggrc.models.mixins import Slugged ...
sillvan/hyperspy
doc/conf.py
Python
gpl-3.0
7,719
0.005312
# -*- coding: utf-8 -*- # # HyperSpy documentation build configuration file, created by # sphinx-quickstart on Mon Oct 18 11:10:55 2010. # # 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. # # Al...
[howto/manual]). latex_documents = [ ('index', 'HyperSpy.tex', u'HyperSpy Documentation', u'The Hyp
erSpy Developers', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal lin...
Svjard/flightpath
config/urls.py
Python
mit
508
0.001969
from django.conf.urls import include, patterns, url from django.contrib import admin urlpatterns = patterns( '', url(r'', include('main.urls')), url(r'^api/v1/', include('authentication.urls')), url(r'^a
pi/v1/', include('posts.urls')), url(r'^admin/', include(admin.site.urls)) ) urlpatterns += [ url(r'^api-auth/', include('rest_fra
mework.urls', namespace='rest_framework')) ] # Redirect to webapp URL # TODO Server-side rendering urlpatterns += [ url(r'^.*$', include('main.urls')), ]
clouserw/zamboni
mkt/site/management/commands/clean_redis.py
Python
bsd-3-clause
3,336
0
import logging import os import socket import subprocess import sys import tempfile import time from django.core.management.base import BaseCommand import redisutils import redis as redislib log = logging.getLogger('z.redis') # We process the keys in chunks of size CHUNK. CHUNK = 3000 # Remove any sets with less th...
e(delete=False) for ks in keys(): tmp.write('\n'.join(ks)) tmp.close() # It's hard to get Python to clean up the memory from slave.keys(), so # we'll let the OS do it. You have to pass sys.executable both as the # thing to run and so argv[0] is set properly. os.execl(sys.executable, sys...
, filename], stdout=subprocess.PIPE) total[0] = int(p.communicate()[0].strip().split()[0]) def file_keys(): while 1: buffer = [] for _ in xrange(CHUNK): line = tmp.readline() if line: buffer.append(line.strip()) ...
CCI-MOC/GUI-Backend
allocation/models/__init__.py
Python
apache-2.0
866
0.004619
from allocation.models.inputs import TimeUnit, Provider, Machine, Size, Instance, InstanceHistory, Al
locationIncrease, AllocationUnlimited, AllocationRecharge, Allocation from allocation.models.results import InstanceHis
toryResult, InstanceResult, TimePeriodResult, AllocationResult from allocation.models.rules import Rule, GlobalRule, InstanceRule, CarryForwardTime, FilterOutRule, InstanceCountingRule, InstanceMultiplierRule, IgnoreStatusRule, IgnoreMachineRule, IgnoreProviderRule, MultiplyBurnTime, MultiplySizeCPU, MultiplySizeDisk, ...
victorpoluceno/shortener_frontend
rest_api/api.py
Python
bsd-2-clause
1,486
0.002692
from django.db import models from tastypie.resources import ModelResource from tastypie.authentication import ApiKeyAuthentication from tastypie.authorization import DjangoAuthorization from tastypie.throttle import CacheThrottle from tastypie.validation import FormValidation from gateway_backend.tasks import url_sho...
lThrottle(throttle_at=100) allowed_methods = ['get', 'post'] validation = FormValidation(form_class=UrlForm) def url_post_save(sender, **kwargs): instance = kwargs.get('instance
') if kwargs.get('created') == True: url_short.delay(instance.id) models.signals.post_save.connect(url_post_save, sender=Url, dispatch_uid='url_create')
bit-jmm/ttarm
nmf/_mm_performance.py
Python
gpl-2.0
1,942
0
# -*- coding: utf-8 -*- # 大規模疎行列 x 密行列演算の実行速度検証 # @nashibao # 使い方: # python mm_performance.py l1 l2 l3 alpha # l1, l2: 疎行列サイズ # l2, l3: 密行列サイズ # alpha: 疎行列充填率 # sp_matrix(l1, l2, alpha) x dense_vec(l2, l3) # 結果: # 2013/01/22 # python mm_performance.py 100000 10000 10 0.005 # prepare.. # 0.437 sec # compute.. # ...
((float)(A.data.nbytes) / 1000000) return A def tests_sparse
_matmul(A, vec): """ compare speed of matrix product """ print "compute.." t1 = time() A * vec t2 = time() print "%8.3f sec" % (t2 - t1) if __name__ == "__main__": l1 = int(argv[1]) l2 = int(argv[2]) l3 = int(argv[3]) alpha = float(argv[4]) A = prepare_matrices(l1, ...
sorenh/cc
vendor/Twisted-10.0.0/twisted/conch/test/test_recvline.py
Python
apache-2.0
21,585
0.002363
# -*- test-case-name: twisted.conch.test.test_recvline -*- # Copyright (c) 2001-2008 Twisted
Matrix Laboratories. # See LICENSE for details. """ Tests for L{twisted.conch.recvline} and fixtures for testing related functionality. """ import sys, os from twisted.conch.insults import insults from twisted.conch import recvline from twisted.python import reflect, components from twisted.internet import defer, e...
sted.cred import portal from twisted.test.proto_helpers import StringTransport class Arrows(unittest.TestCase): def setUp(self): self.underlyingTransport = StringTransport() self.pt = insults.ServerProtocol() self.p = recvline.HistoricRecvLine() self.pt.protocolFactory = lambda: sel...
abacuspix/NFV_project
Instant_Flask_Web_Development/sched/forms.py
Python
mit
1,083
0
"""Forms to render HTML input & validate request data.""" from wtforms import Form, BooleanField, DateTimeField, PasswordField from wtforms import TextAreaFi
eld, TextField from wtforms.validators import Length, required class AppointmentForm(Form): """Render HTML input for Appointment model & validate submissions. This matches the models.Appointment class very closely. Where models.Appointment represents the domain and its persistence, this class represe...
end = DateTimeField('End') allday = BooleanField('All Day') location = TextField('Location', [Length(max=255)]) description = TextAreaField('Description') class LoginForm(Form): """Render HTML input for user login form. Authentication (i.e. password verification) happens in the view function. ...
pyspace/test
pySPACE/tests/__init__.py
Python
gpl-3.0
191
0.010471
""" Collection of
pySPACE system and unit tests .. note:: The section with :mod:`~pySPACE.tests` is not really complete, but there is a script to
run all unittests automatically. """
eahneahn/free
bootstrap/gen.py
Python
agpl-3.0
1,091
0.001833
# coding: utf-8 """ Only use this if you want to update a bootstrapV.M
.py file to a newer virtualenv! Usage: /path/to/specific/version/of/python gen.py """ import sys import virtualenv EXTENSION = """ # coding: utf-8 import os from os.path import abspath, basename, dirname, join, pardir import subprocess # get current dir def adjust_options(options, args): BOOTSTRAP_PATH = absp...
virtualenv's dir args.append(join(BOOTSTRAP_PATH, pardir)) # override default options def extend_parser(parser): parser.set_defaults(unzip_setuptools=True, use_distribute=True) # delegate the final hooks to an external script so we don't need to change this. def after_install(options,...
pmoravec/sos
tests/sos_tests.py
Python
gpl-2.0
37,144
0.001023
# This file is part of the sos project: https://github.com/sosreport/sos # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # version 2 of the GNU General Public License. # # See the LICENSE file in the source distribution ...
LOG_UI.error('ERROR:\n' + msg[:8196]) # don't flood w/ super verbose logs if err.result.interrupted: raise Exception("Timeout exceeded, see output above") else:
raise Exception("Command failed, see output above: '%s'" % err.command.split('bin/')[1]) with open(os.path.join(self.tmpdir, 'output'), 'wb') as pfile: pickle.dump(self.cmd_output, pfile) self.cmd_output.stdout = self.cmd_output.stdout.decode() se...
subena-io/subena
package/alerts/main.py
Python
apache-2.0
391
0.015345
#!/usr/local/bin/python2.7 # -*-coding:UTF-8-sig -*- """ Module for getting alerts according to learning program Learning Algorithm - 2015 - Subena """ import package.learning.parameter as lear
ningParameter def execute(): #calculate alerts according to the last values #learningParameter.getProbaForLastMeasures(10) learningParameter.getAlertsFro
mStats()
akarol/cfme_tests
cfme/scripting/link_config.py
Python
gpl-2.0
2,905
0.001721
from __future__ import print_function import errno import os import click from pathlib2 import Path def _is_yaml_file(path): return path.suffix in ('.yaml', '.eyaml') def _warn_on_unknown_encryption(path): if path.suffix == '.eyaml' and not Path('.yaml_key').is_file(): print( "...
) except OSError as e: if e.errno == e
rrno.EEXIST: backup_target = Path(dest.joinpath(element.name + "_bak")) print("Replacing", target.name, "and saving backup as", backup_target.name) # Would use 'backup_target.replace()' here but that's only supported in py3 if backup_target...
mcgid/morenines
morenines/exceptions.py
Python
mit
697
0.005739
class MoreninesError(Exception): """The base class for unrecoverable errors during morenines execution.""" class PathError(MoreninesError): """Errors involving user-supplied path arguments.""" def __init__(self, message, path, *args): self.path = path super(PathError, self).__init__(messa...
class RepositoryError(MoreninesError): """Errors in reading from or writing to a repository.""" class MoreninesWarning(Exception): """The base class for unexpected but recoverable situations during morenines execution.""" class NoEffectWarning(MoreninesWarning): """Situations where sp
ecific user input has yielded no change in repository state."""
stsewd/hellopy
hellopy/config.py
Python
mit
201
0
""" Global configurations """ import datetime USER = 'user' WIT_AI
_KEY = 'your wit key' BIRTH = datetime.datetime(2016, 6, 22, 12, 0, 0) LANGUAGE_UNICODE = 'es' LANGUAGE =
'Es-es' RECORD_DURATION = 0
YangLuGitHub/Euler
src/scripts/Problem12.py
Python
mit
4,196
0.00286
# Highly divisible triangular number # Problem 12 # The sequence of triangle numbers is generated by adding the natural numbers. # So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be: # # 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... # # Let us list the factors of the first seven...
exponent_count if factor_1 == 1: break
if prime * prime > factor_1: # Factor is now prime factor_count *= 2 break for prime in sieve: exponent_count = 1 while factor_2 % prime == 0: exponent_count += 1 factor_2 //= prime facto...
karanisverma/feature_langpop
librarian/menu/apps.py
Python
gpl-3.0
422
0
""" apps.
py: apps menu item Copyright 2014-2015, Outernet Inc. Some rights reserved. This software is free software licensed under the terms of GPLv3. See COPYING file that comes with the source code, or http://www.gnu.org/licenses/gpl.txt. """ from . import MenuItem from bottle_utils.i18n import lazy_gettext as _ class A...
'apps' route = 'apps:list'
Donkyhotay/MoonPy
twisted/internet/threads.py
Python
gpl-3.0
3,490
0.000573
# Copyright (c) 2001-2007 Twisted Matrix Laboratories. # See LICENSE for details. """ Extended thread dispatching support. For basic support see reactor threading API docs. Maintainer: Itamar Shtull-Trauring """ import Queue from twisted.python import failure from twisted.internet import defer def deferToThreadP...
xception. """ d = defer.Deferred() def onResult(success, result): if success: reactor.callFromThread(d.callback, result) else: reactor.callFromThread(d.errback, result) threadpool.callInThreadWithCallback(onResult, f, *args, **kwargs) return d def deferTo...
esult as a Deferred. @param f: The function to call. @param *args: positional arguments to pass to f. @param **kwargs: keyword arguments to pass to f. @return: A Deferred which fires a callback with the result of f, or an errback with a L{twisted.python.failure.Failure} if f throws an exceptio...
jtraver/dev
python/subprocess/write2.py
Python
mit
1,052
0.005703
#!/usr/bin/python import subprocess import os import shutil import pty master, slave = pty.openpty() args = ('stdin1.py') # popen = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd='.
') # http://st
ackoverflow.com/questions/5411780/python-run-a-daemon-sub-process-read-stdout/5413588#5413588 # not working popen = subprocess.Popen(args, shell=True, stdin=subprocess.PIPE, stdout=slave, stderr=slave, close_fds=True, cwd='.') stdout = os.fdopen(master) # set the O_NONBLOCK flag of p.stdout file descriptor: # flags = ...
Akelio-zhang/sxk-microblog
app/models.py
Python
bsd-3-clause
3,738
0.002675
from app import db from app import app from config import WHOOSH_ENABLED import requests, json, re import sys if sys.version_info >= (3, 0): enable_search = False else: enable_search = WHOOSH_ENABLED if enable_search: import flask.ext.whooshalchemy as whooshalchemy followers = db.Table('followers'...
condary=followers, primaryjoin=(followers.c.follower_id == id), secondaryjoin=(followers.c.followed_id == id), backref=db.backref('followers', lazy='dynamic'), lazy='dynamic') def is_authenti...
rn unicode(self.id) # python 2 except NameError: return str(self.id) # python 3 def avatar(self, size='s'): # my own steam info if self.steam_id: url = 'http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=090B8FBA169177A04FFB10777A0C2F41&steamids='...
albertz/music-player
mac/pyobjc-core/Lib/objc/_framework.py
Python
bsd-2-clause
632
0.003165
""" Generic framework path manipulation """ __all__ = ['infoForFramework'] # This regexp should find: # \1 - framework location # \2 - framework name # \3 - framework version (optional) # FRAMEWORK_RE_STR = r"""(^.*)(?:
^|/)(\w+).fram
ework(?:/(?:Versions/([^/]+)/)?\2)?$""" FRAMEWORK_RE = None def infoForFramework(filename): """returns (location, name, version) or None""" global FRAMEWORK_RE if FRAMEWORK_RE is None: import re FRAMEWORK_RE = re.compile(FRAMEWORK_RE_STR) is_framework = FRAMEWORK_RE.findall(filename) ...
luogangyi/bcec-nova
nova/tests/api/openstack/compute/contrib/test_server_external_events.py
Python
apache-2.0
6,660
0
# Copyright 2014 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
self.assertEqual([], expected_events) return result, code def test_create(self): req = self._create_req(self.default_body) result, code = self._assert_call(req,
self.default_body, fake_instance_uuids[:2], ['network-vif-plugged', 'network-changed']) self.assertEqual(self.default_resp_body, result) self.assertEqual(200, code) def test_c...
grongor/school_rfid
lib/nmap-6.40/zenmap/zenmapGUI/DiffCompare.py
Python
gpl-2.0
22,849
0.002495
#!/usr/bin/env python # -*- coding: utf-8 -*- # ***********************IMPORTANT NMAP LICENSE TERMS************************ # * * # * The Nmap Security Scanner is (C) 1996-2013 Insecure.Com LLC. Nmap is * # * also a registered trademark of Inse...
the * # * OpenSSL library which is distributed under a license identical to that * # * listed in the included docs/licenses/OpenSSL.txt file, and distribute * # * linked combinations including the two.
* # * * # * Any redistribution of Covered Software, including any derived works, * # * must obey and carry forward all of the terms of this license, including * # * obeying all GPL rules and restrictions. For exam...
ctrlspc/PyPrinterMonitor
pyPrinterMonitor/test.py
Python
gpl-3.0
507
0.005917
''' Created on Jan 11, 2012 @author: jjm20 ''' import pika connection = pika.BlockingConnection(pika.Connectio
nParameters( host='localhost')) channel = connection.channel() channel.queue_declare(queue='RT_Events_q') print ' [*] Waiting for messages. To exit press CTRL+C' def callback(ch, method, properties, body): print " [x] Received %r" % (body,) channel.basic_consume(callback, queue='RT...
_consuming()
gautsi/pmareport
pmareport/predictors.py
Python
bsd-3-clause
6,290
0.000159
# -*- coding: utf-8 -*- ''' The model used to predict appointment duration is a decision tree. The model is evaluated by the precentage of predicted times that are within a threshold (5 minutes by default) of the actual duration. The class `DurationPredictor` splits the data into testing and training, builds the model...
pred, thresh=5) score_list.append(score) return np.mean(score_list) def fit(self, thresh=5): ''' Fit the model on the training set and evaluate it on the test set. The metric is the percent of predictions within `thresh` of the true value. :param float t...
threshold for considering a prediction close to the true value :returns: the score of the model on the test set :rtype: float ''' self.model.fit(self.Xtrain, self.ytrain) predictions = self.model.predict(self.Xtest) score = percent_within( y_true=self.ytest, ...
dolph/python-keystoneclient
keystoneclient/v2_0/tokens.py
Python
apache-2.0
1,387
0
from keystoneclient import base class Token(base.Resource): def __repr__(self): return "<Token %s>" % self._info @property def id(se
lf): return self._info['token']['id'] @property def expires(self): return self._info['token']['expires'] @property def tenant(self): return self._info['token'].get('tenant', None) class TokenManager(base.ManagerWithFind): resource_class = Token def authenticate(self,...
password=None, token=None, return_raw=False): if token: params = {"auth": {"token": {"id": token}}} elif username and password: params = {"auth": {"passwordCredentials": {"username": username, "password": passw...
lucventurini/mikado
Mikado/subprograms/pick.py
Python
lgpl-3.0
23,916
0.005812
#!/usr/bin/env python3 # coding: utf-8 """Launcher of the Mikado pick step.""" import argparse import re import sys import os from typing import Union, Dict from ._utils import check_log_settings_and_create_logger, _set_pick_mode import marshmallow from ..configuration import DaijinConfiguration, MikadoConfiguration ...
onf.pick.alternative_splicing.keep_cds_disrupted_by_ri = True if args.keep_disrupted_cds is True \ else conf.pick.alternative_splicing.keep_cds_disrupted_by_ri conf.pick.alternative_splicing.keep_retained_introns = False if args.exclud
e_retained_introns is True else \ conf.pick.alternative_splicing.keep_retained_introns return conf def _set_conf_values_from_args(conf: Union[DaijinConfiguration, MikadoConfiguration], args, logger=create_null_logger()) -> Union[DaijinConfiguration, MikadoConfiguration]: ...
serzans/wagtail
wagtail/wagtailsearch/tests/test_elasticsearch_backend.py
Python
bsd-3-clause
38,709
0.003126
# -*- coding: utf-8 -*- from __future__ import unicode_literals import os import unittest import datetime import json import mock from elasticsearch.serializer import JSONSerializer from django.test import TestCase from django.db.models import Q from wagtail.wagtailsearch.backends import get_search_backend from wag...
TestElasticSearchQuery(TestCase): def assertDictEqual(self, a, b): default = JSONSerializer().default self.assertEqual(json.dumps(a, sort_key
s=True, default=default), json.dumps(b, sort_keys=True, default=default)) def test_simple(self): # Create a query query = ElasticSearchQuery(models.SearchTest.objects.all(), "Hello") # Check it expected_result = {'filtered': {'filter': {'prefix': {'content_type': 'searchtests_searc...
MOOCworkbench/MOOCworkbench
pylint_manager/tests.py
Python
mit
2,789
0.003586
import os from unittest.mock import patch from django.contrib.auth.models import User from django.core.management import call_command from django.test import TestCase from experiments_manager.models import ChosenExperimentSteps, Experiment from git_manager.models import GitRepository from user_manager.models import W...
github_url='https://github.com/jlmdegoede/Workbench-Acceptance-Experiment.git') self.experiment = Experiment.objects.create(title='Experiment', description='test', owner=s...
rkbench_user, git_repo=self.git_repo, language_id=1, template_id=2) self.chosen_experiment_step = ChosenExperimentSteps.objects.create(step_id=1, ...
xtao/code
tests/webtests/api/test_follow.py
Python
bsd-3-clause
2,864
0
# encoding: utf-8 from .base import APITestCase from vilya.models.user import User class FollowTest(APITestCase): def setUp(self): super(FollowTest, self).setUp() user_name1 = 'zhangchi' email = '%[email protected]' % user_name1 self.zhangchi = User(user_name1, email) user_name2...
(self.lijunpeng.username), headers=dict( Authorization="Bearer %s" % self.api_token_zhangchi.token), status=204 ) self.app.delete( "/api/user/following/%s/" % (self.lijunpeng.username), headers=dict( Authorization="Bearer %...
=204 ) self.app.get( "/api/user/following/%s/" % (self.lijunpeng.username), headers=dict( Authorization="Bearer %s" % self.api_token_zhangchi.token), status=404 )
genialis/resolwe-bio
resolwe_bio/filters.py
Python
apache-2.0
4,334
0.002769
""".. Ignore pydocstyle D400. =================== Resolwe Bio Filters =================== """ import django_filters as filters from rest_framework import exceptions from resolwe.flow.filters import CollectionFilter, DataFilter, EntityFilter from resolwe_bio.models import Sample class BioCollectionFilter(Collectio...
sample = filters.ModelChoiceFilter( field_name="entity", queryset=Sample.objects.all() ) class BioEntityFilter(EntityFilter): """Filter the entity e
ndpoint. Enable filtering collections by the entity. .. IMPORTANT:: :class:`EntityViewSet` must be patched before using it in urls to enable this feature: .. code:: python EntityViewSet.filter_class = BioEntityFilter """ descriptor__subject_information_...
rlbabyuk/integration_tests
cfme/tests/configure/test_rest_access_control.py
Python
gpl-2.0
16,442
0.001095
# -*- coding: utf-8 -*- import fauxfactory import py
test from cfme import test_requirements from cfme.base.credential import Credential from cfme.configure.access_control import User from cfme.login impor
t login, login_admin from cfme.rest.gen_data import groups as _groups from cfme.rest.gen_data import roles as _roles from cfme.rest.gen_data import tenants as _tenants from cfme.rest.gen_data import users as _users from utils import error from utils.wait import wait_for pytestmark = [ test_requirements.auth ] cl...
UmSenhorQualquer/d-track
dolphintracker/singlecam_tracker/pool_camera.py
Python
mit
3,437
0.045388
import cv2, numpy as np from dolphintracker.singlecam_tracker.camera_filter.FindDolphin import SearchBlobs from dolphintracker.singlecam_tracker.camera_filter.BackGroundDetector import BackGroundDetector import datetime class PoolCamera(object): def __init__(self, videofile, name, scene, maskObjectsNames, filters, f...
self.frame_index = firstFrame result = [] for i, colorFilter in enumerate(self.filters): filterResult = colorFilter.filter(self.frame, self._backgrounds[i]) blobs =
self._searchblobs.process(filterResult) res = blobs[0] if len(blobs)>=1 else None result.append(res) return result def create_empty_mask(self): return np.zeros( (self.img_height, self.img_width), np.uint8 ) def points_projection(self, points): cam = self.scene_camera; return [cam.calcPixel(*p) fo...
flowersteam/explauto
explauto/models/motor_primitive.py
Python
gpl-3.0
2,072
0.000965
from numpy import linspace, array, arange, tile, dot, zeros from .gaussian import
Gaussian f
rom ..utils import rk4 class BasisFunctions(object): def __init__(self, n_basis, duration, dt, sigma): self.n_basis = n_basis means = linspace(0, duration, n_basis) # FIXME: variances = duration / (sigma * n_basis)**2 gaussians = [Gaussian(array([means[k]]), array([[varian...
tjhunter/phd-thesis-tjhunter
python/myscript.py
Python
apache-2.0
164
0.012195
from build import save_name f = open(save_name
("myfile.txt"),'w') f.write("XXXXX") f.close() f = open(save_name("dir/myfile2.txt"),'w') f.write("XXXXX") f.close()
Xeralux/tensorflow
tensorflow/contrib/py2tf/utils/py_func.py
Python
apache-2.0
4,890
0.007771
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
ific language governing permissions and # limitations under the License. # ============================================================================== """Pyfunc creation utilities.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from collections impor...
ork import tensor_util from tensorflow.python.ops import script_ops class MatchDType(namedtuple('MatchDType', ('arg_number',))): """Allows matching the dtype of an argument. Used in conjunction with function calls. For example, MatchDType(0) will match the DType of the first argument. """ pass def wrap_...
wogsland/QSTK
build/lib.linux-x86_64-2.7/Bin/Data_CSV.py
Python
bsd-3-clause
3,301
0.014541
#File to read the data from mysql and push into CSV. # Python imports import datetime as dt import csv import copy import os import pickle # 3rd party imports import numpy as np import matplotlib.pyplot as plt import pandas as pd # QSTK imports from QSTK.qstkutil import qsdateutil as du import QSTK.qstkutil.DataEvol...
m = df_sym.join(df_temp, how= 'outer') symfilename = sym.split('-')[0] sym_file = open(s_directory + symfilename + '.csv', 'w') sym_file.write("Date,Open,High,Low,Close,Volume,Adj Close \n") ldt_timestamps = li
st(df_sym.index) ldt_timestamps.reverse() for date in ldt_timestamps: date_to_csv = '{:%Y-%m-%d}'.format(date) string_to_csv = date_to_csv for key in ls_keys: string_to_csv = string_to_csv + ',' + str(df_sym[key][date]) string_to_csv = string_to_csv + '\n' ...
mthh/cartogram_geopandas
cartogram_geopandas.py
Python
gpl-2.0
1,738
0
# -*- coding: utf-8 -*- """ cartogram_geopandas v0.0.0c: Easy construction of continuous cartogram on a Polygon/MultiPolygon GeoDataFrame (modify the geometry in place or create a new GeoDataFrame). Code adapted to fit the geopandas.GeoDataFrame datastructure from Carson Farmer's code (https://github...
e of the field (Series) containing the value to use. :param integer iterations: The number of iterations to make. [default=5] :param bool inplace: Append in place if True i
s set. Otherwhise return a new GeoDataFrame with transformed geometry. [default=False] """ if inplace: crtgm = Cartogram(geodf, field_name, iterations) crtgm.make() else: crtgm = Cartogram(geodf.copy(), field_name, iterations) return crtgm.make()
spottradingllc/zoom
test/predicate/health_test.py
Python
gpl-2.0
1,195
0.005021
import mox import time import unittest from zoom.agent.predicate.health import PredicateHealth from zoom.common.types import PlatformType class PredicateHealthTest(unittest.TestCase): def setUp(self): self.mox = mox.Mox() self.interval = 0.1 def tearDown(self): self.mox.UnsetStubs() ...
pred.start()
time.sleep(0.25) # give other thread time to check pred.stop() pred.stop() pred.stop() self.mox.VerifyAll()
drmelectronic/Despacho
usb/backend/libusb0.py
Python
bsd-3-clause
20,780
0.001396
# Copyright (C) 2009-2013 Wander Lairson Costa # # The following terms apply to all files associated # with the software unless explicitly disclaimed in individual files. # # The authors hereby grant permission to use, copy, modify, distribute, # and license this software and its documentation for any purpose, provided...
es(lib): # usb_dev_handle *usb_open(struct usb_device *dev); lib.usb_open.argtypes = [POINTER(_usb_device)] lib.usb_open.restype = _usb_dev_handle # int usb_close(usb_dev_handle *dev); lib.usb_close.argtypes = [_usb_dev_handle] # int usb_get_string(usb_dev_handle *dev, # ...
int langid, #
RPGOne/Skynet
scikit-learn-0.18.1/examples/model_selection/grid_search_digits.py
Python
bsd-3-clause
2,764
0
""" ============================================================ Parameter estimation using grid search with cross-validation ============================================================ This examples shows how a classifier is optimized by cross-validation, which is done using the :class:`sklearn.model_selection.GridS...
ages.reshape((n_samples, -1)) y = digits.target # Split the dataset in two equal parts X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.5, random_state=0) # Set the parameters by cross-validation tuned_parameters = [{'kernel': ['rbf'], 'gamma': [1e-3, 1e-4], 'C': [1, 10,...
%s" % score) print() clf = GridSearchCV(SVC(C=1), tuned_parameters, cv=5, scoring='%s_macro' % score) clf.fit(X_train, y_train) print("Best parameters set found on development set:") print() print(clf.best_params_) print() print("Grid scores on development set:")...
guardiaocl/guardiaocl-servers
guardiancl/guardianService.py
Python
apache-2.0
10,091
0.00327
import getpass import json import os import platform from datetime import datetime import urllib3 import psutil from apscheduler.schedulers.blocking import BlockingScheduler import console from utils import Utils from account import Account from device import Device utils = Utils() system_config = utils.get_system_c...
g['ROUTES'].get('devices') if account is not None: try: response = http.request('GET', url, None, {'user-key': account.user_key}) except Exception, e: console.error("Check your connection", exc_info=True) if response.status == 200: devices = [] ...
n json.loads(response.data): devices.append(Device(dev['serial'], dev['description'])) return devices else: data = json.loads(response.data) console.error(data['status']) return None def generate_config_file(account, device): if account is not...
sparkslabs/kamaelia_
Tests/Python/Axon/test_Ipc.py
Python
apache-2.0
8,217
0.023853
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1) # # (1) Kamaelia Contributors are listed in the AUTHORS file and at # http://www.kamaelia.org/AUTHORS - please extend this file, # not this notice. # # Licensed under the Apache License...
hecks object is instance of ipc." s=status("Status message.") self.failUnless(isinstance(s, ipc), "status should be derived from ipc.") self.failUnless(s.status() == "Status message.", "Status message not stored properly.") def test_status(self): "status.status - Returns the status message st...
to __init__ test." s=status("Status message.") self.failUnless(s.status() == "Status message.", "Status message not stored properly.") class wouldblock_Test(unittest.TestCase): def test_SmokeTest_NoArguments(self): "wouldblock.__init__ - Called without arguments fails." self.failUnlessRaise...
wikimedia/pywikibot-wikibase
tests/test_itempage.py
Python
mit
1,946
0
import unittest import json import os from pywikibase import ItemPage, Claim try:
unicode = unicode except NameError: basestring = (str, bytes) class TestItemPage(unittest.TestCase): def setUp(self): with open(os.path.join(os.path.split(__file__)[0], 'data', 'Q7251.wd')) as f: self._content = json.load(f)['entities']['Q7251'] self...
rtRaises(RuntimeError, ItemPage, title='Null') self.assertRaises(RuntimeError, ItemPage, title='P15') def test_sitelinks(self): self.assertEqual(len(self.item_page.sitelinks), 134) self.assertIn('fawiki', self.item_page.sitelinks) self.assertNotIn('fa', self.item_page.sitelinks) ...
p-montero/py-ans
class9/exercise2/mytest/__init__.py
Python
apache-2.0
97
0
f
rom mytes
t.simple import func1 from mytest.whatever import func2 from mytest.world import func3
wuqize/FluentPython
chapter8/_weakref.py
Python
lgpl-3.0
277
0.025271
# -*- coding: utf-8 -*- """ Created
on Wed May 10 23:08:27 2017 """ import time import weakref s1 = {1, 2, 3} s2 = s1 def bye(): print('Gone with the wind...') ender = weakref.finalize(s1, bye) print ender.alive def s1 print ender.aliv
e s2 = 'spam' print ender.alive
MuckRock/muckrock
muckrock/organization/views.py
Python
agpl-3.0
4,827
0.000829
""" Views for the organization application """ # Django from django.conf import settings from django.contrib import messages from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from django.core.cache import cache from django.db.models.query import Prefetch from django.h...
context_data(self, **kwargs): """Add extra context data""" context = super(OrganizationDetailView, self).get_context_data(**kwargs) organization = context["organization"] user = self.request.user context["is_staff"] = user.is_staff if user.is_authentic
ated: context["is_admin"] = organization.has_admin(user) context["is_member"] = organization.has_member(user) else: context["is_owner"] = False context["is_member"] = False requests = FOIARequest.objects.organization(organization).get_viewable(user) ...
pitunti/alfaPitunti
plugin.video.alfa/servers/zippyshare.py
Python
gpl-3.0
1,478
0.006089
# -*- coding: utf-8 -*- import re from core import httptools from core import scrapertools from platformcode import logger def test_video_exists(page_url): result = False message = '' try: error_message_file_not_exists = 'File does not exist on this server' error_message_file_deleted = '...
st anymore on this server' data = httptools.downloadpage(page_url).data if error_message_file_not_exists in data: message = 'File does not exist.' elif error_message_file_deleted in data: message = 'File deleted.' else: result = True except Excep...
url, premium=False, user="", password="", video_password=""): logger.info("(page_url='%s')" % page_url) video_urls = [] data = httptools.downloadpage(page_url).data match = re.search('(.+)/v/(\w+)/file.html', page_url) domain = match.group(1) patron = 'getElementById\(\'dlbutton\'\).href\s*=\s...
davygeek/vitess
test/backup_only.py
Python
apache-2.0
14,271
0.008689
#!/usr/bin/env python # Copyright 2017 The Vitess Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applic...
w') as fd: fd.write(init_db) fd.write(mysql_flavor().change_passwords(password_col)) logging.debug("initilizing mysql %s",str(datetime.datetime.now())) # start mysql instance external to the test setup_procs = [ tablet_master.init_mysql(init_db=new_init_db, ...
extra_args=['-db-credentials-file', db_credentials_file]), tablet_replica2.init_mysql(init_db=new_init_db, extra_args=['-db-credentials-file', db_credentials_fi...
benagricola/exabgp
lib/exabgp/reactor/daemon.py
Python
bsd-3-clause
4,987
0.039503
# encoding: utf-8 """ daemon.py Created by Thomas Mangin on 2011-05-02. Copyright (c) 2009-2015 Exa Networks. All rights reserved. """ import os import sys import pwd import errno import socket from exabgp.configuration.environment import environment from exabgp.logger import Logger MAXFD = 2048 class Daemon (ob...
cuid = os.getuid() ceid = os.geteuid() cgid = os.getgid() if cuid < 0: cuid += (1 << 32) if cgid < 0: cgid += (1 << 32) if ceid < 0: ceid += (1 << 32) if nuid != cuid or nuid != ceid or ngid != cgid: return False except OSError: return False return True def _is_socket (
self, fd): try: s = socket.fromfd(fd, socket.AF_INET, socket.SOCK_RAW) except ValueError: # The file descriptor is closed return False try: s.getsockopt(socket.SOL_SOCKET, socket.SO_TYPE) except socket.error,exc: # It is look like one but it is not a socket ... if exc.args[0] == errno.ENOTSOCK...
317070/ppbe-finance
finance/tests.py
Python
unlicense
725
0.008276
from django.test import TestCase from finance.models import Banking_Account class IBANTestCase(TestCase): def setUp(self): pass def test_iban_converter(self): """BBAN to IBAN conversion""" self.assertEqual(Banking_Account.convertBBANToIBAN("091-0002777-90"), 'BE3409100
0277790') self.assertEqual(Banking_Account.convertBBANToIBAN("679-2005502-27"), 'BE48679200550227') self.assertEqual(Banking_Account.isBBAN("679-2005502-27"), True) self.assertEqual(Banking_Account.isBBAN('BE48679200550227'), False)
self.assertEqual(Banking_Account.isIBAN("679-2005502-27"), False) self.assertEqual(Banking_Account.isIBAN('BE48679200550227'), True)
takearest118/coconut
handlers/v1/invitation.py
Python
gpl-3.0
2,604
0.00192
# -*- coding: utf-8 -* from tornado.web import HTTPError from common.decorators import parse_argument, app_auth_async from handlers.base import JsonHandler, WSHandler from models.invitation import InvitationModel from models.admin import AdminModel from models.notification import NotificationModel class SubmitHand...
ecoded_body.get('desk_number', None) if not isinstance(desk_number, int): raise HTTPError(400, 'invalid desk_number') mobile_number = self.json_decoded_body.get('mobile_number', None) if not mobile_number or len(mobile_number) == 0: raise HTTPError(400, 'invalid mobile_nu...
raise HTTPError(400, 'not exist desk number') query = { 'mobile_number': mobile_number } invitation = await InvitationModel.find_one(query) if not invitation: raise HTTPError(400, 'not exist mobile number') # save notification notification = Notificat...
heidtn/quadquad
quadquad_hardware/scripts/servo_interface.py
Python
gpl-3.0
2,668
0.037856
#!/usr/bin/env python import rospy from std_msgs.msg import Header from quadquad_hardware.msg import QuadServos import serial from serial.tools import list_ports import sys ser = None servomap = { 'BLHip': [0,-1], 'BRHip': [2, 1], 'FLHip': [5,-1], 'FRHip': [6, 1], 'BLLeg': [1, 1], 'BRLeg': [3,-1], 'FLLeg': [...
], servoMsg.BLHip, servomap['BLHip'][1]) set_pos(servomap['BRHip'][0], servoMsg.BRHip, servomap['BRHip'][1]) set_pos(servomap['FLHip'][0], servoMsg.FLHip, servomap['FLHip'][1]) set_pos(servomap['FRHip'][0], servoMsg.FRHip, servomap['FRHip'][1]) set_pos(servomap['BLLeg'][0], ser
voMsg.BLLeg, servomap['BLLeg'][1]) set_pos(servomap['BRLeg'][0], servoMsg.BRLeg, servomap['BRLeg'][1]) set_pos(servomap['FLLeg'][0], servoMsg.FLLeg, servomap['FLLeg'][1]) set_pos(servomap['FRLeg'][0], servoMsg.FRLeg, servomap['FRLeg'][1]) def create_listener_node(): rospy.init_node('quad_servo_controller') rospy....
pqtoan/mathics
mathics/builtin/natlang.py
Python
gpl-3.0
48,237
0.002218
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Natural language functions """ # PYTHON MODULES USED IN HERE # spacy: everything related to parsing natural language # nltk: functions using WordNet # pattern: finding inflections (Pluralize[] and WordData[]) # langid, pycountry: LanguageIdentify[] # pyenchant: Spell...
else: return 1 + t.idx, t.idx + len(t.text) def _fragments(doc, sep): start = 0 for i, to
ken in enumerate(doc): if sep.match(token.text): yield Span(doc, start, i) start = i + 1 end = len(doc) if start < end: yield Span(doc, start, end) class _SpacyBuiltin(Builtin): requires = ( 'spacy', ) options = { 'Language': '"English"', ...
hustlzp/Flask-Boost
flask_boost/project/application/controllers/account.py
Python
mit
1,215
0
# coding: utf-8 from flask import render_template, Blueprint, redirect, request, url_for from ..forms import SigninForm, SignupForm from ..utils.account import signin_user, signout_user from ..utils.permissions import VisitorPermission, UserPermission from ..models import db, User bp = Blueprint('account', __name
__) @bp.route('/signin', methods=['GET', 'POST']) @VisitorPermission() def signin(): """Signin""" form = SigninForm() if form.valid
ate_on_submit(): signin_user(form.user) return redirect(url_for('site.index')) return render_template('account/signin/signin.html', form=form) @bp.route('/signup', methods=['GET', 'POST']) @VisitorPermission() def signup(): """Signup""" form = SignupForm() if form.validate_on_submit():...
Azure/azure-sdk-for-python
sdk/containerregistry/azure-mgmt-containerregistry/azure/mgmt/containerregistry/v2021_06_01_preview/aio/operations/_scope_maps_operations.py
Python
mit
24,899
0.004659
# 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 may ...
ls.ScopeMap"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) request = build_get_request( subscription_id=self._config.subscription_id, resour...
registry_name=registry_name, scope_map_name=scope_map_name, template_url=self.get.metadata['url'], ) request = _convert_request(request) request.url = self._client.format_url(request.url) pipeline_response = await self._client._pipeline.run(request, stream=F...
openstack/designate
api-ref/source/conf.py
Python
apache-2.0
6,722
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 the...
language governing permissions and limitations # under the License. # # ironic documentation build configuration file, created by # sphinx-quickstart on Sat May 1 15:17:47 2010. # # This file is execfile()d with the current directory set to # its containing dir. # # Note that not all possible configuration values are...
t # serve to show the default. import os import sys html_theme = 'openstackdocs' html_theme_options = { "sidebar_mode": "toc", "sidebar_dropdown": "api_ref", } extensions = [ 'os_api_ref', 'openstackdocstheme' ] # If extensions (or modules to document with autodoc) are in another directory, # add th...
telefonicaid/fiware-sinfonier
sinfonier-backend-api/config/config.py
Python
apache-2.0
525
0
import os import sys from utils.SinfonierConstants import Environment as EnvConst SINFONIER_API_NAME = os.environ[EnvConst.SINFONIER_ENV_KEY] if SINFONIER_API_NAME == EnvConst.DEVELOP_ENVIRONMENT: from environmentConfig.
Develop import * elif SINFONIER_API_NAME == Env
Const.PROD_ENVIRONMENT: from environmentConfig.Production import * elif SINFONIER_API_NAME == EnvConst.DOCKER_ENVIRONMENT: from environmentConfig.Docker import * else: sys.exit('ERROR: Environment not found: ' + EnvConst.SINFONIER_ENV_KEY)
Som-Energia/somenergia-tomatic
tomatic/scheduling_test.py
Python
gpl-3.0
24,860
0.010666
#!/usr/bin/env python # -*- coding: utf8 -*- import unittest from datetime import datetime, timedelta from yamlns.dateutils import Date from yamlns import namespace as ns from .scheduling import ( weekday, weekstart, nextweek, choosers, Scheduling, ) class Scheduling_Test(unittest.TestCase): ...
schedule.properName('perico'), u'Perico') def test_properName_noNamesAtAll(self): schedule = Scheduling("""\ otherkey: """) self.assertEqual( schedule.properName('perico'), u'Perico') # Scheduling.intervals def test_interv...
""") self.assertEqual( schedule.intervals(), [ ]) def test_intervals_withTwoDates(self): schedule = Scheduling("""\ hours: - '09:00' - '10:15' """) self.assertEqual( schedule.intervals(), [ '09:0...
shepdelacreme/ansible
test/units/module_utils/test_distribution_version.py
Python
gpl-3.0
39,710
0.002518
# -*- coding: utf-8 -*- # Copyright: (c) 2017 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type from itertools import product import pytest # the module we are actually te...
e" """, "/etc/SuSE-release": """ openSUSE 42.1 (x86_64) VERSION = 42.1 CODENAME = Malachite # /etc/SuSE-release is deprecated and will be removed in the future, use /etc/os-release instead """ }, "platform.dist": ['SuSE', '42.1', 'x86_64'], "result": { "distribution": "op...
", "distribution_release": "1", "os_family": "Suse", "distribution_version": "42.1", } }, { 'name': 'openSUSE 13.2', 'input': { '/etc/SuSE-release': """openSUSE 13.2 (x86_64) VERSION = 13.2 CODENAME = Harlequin # /etc/SuSE-release is deprec...
vagabondize/MyDemo
python/Multiplication.py
Python
mit
300
0.01
print(' Multiplication Table') print(" ", end = '') for j in range(1, 10): print(" ", j, end="") print() print('---------------------------------------') for i in range(1, 10): print(i,
"|", end="")
for j in range(1, 10): print(format(i * j, "3d"), end="") print()
ThinkboxSoftware/Deadline
Custom/events/PriorityClamp/PriorityClamp.py
Python
apache-2.0
2,103
0.001427
############################################################### # Imports ############################################################### from System.Diagnostics import * from System.IO import * from System import TimeSpan from Deadline.Events import * from Deadline.Scripting import * import re import sys...
def __init__(self
): self.OnJobSubmittedCallback += self.OnJobSubmitted def Cleanup(self): del self.OnJobSubmittedCallback # This is called when a job is submitted. def OnJobSubmitted(self, job): user = job.JobUserName priority = 0 priority_map = self.GetConfigEntry('Prio...
myuuuuun/ThinkStats2-Notebook
chap3ex.py
Python
gpl-2.0
4,243
0.006178
#!/usr/bin/python #-*- encoding: utf-8 -*- """ Sample Codes for ThinkStats2 - Chapter2 Copyright 2015 @myuuuuun URL: https://github.com/myuuuuun/ThinkStats2-Notebook License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html """ from __future__ import division, print_function import sys sys.path.append('./code') sys.path...
th.fabs(speed - average)) new_pmf.Normalize() return new_pmf def ex4(): pmf = relay.pmf() observed = ObservedPmf(pmf, 7.5) thinkplot.PrePlot(2) thinkplot.Pmfs([pmf, observed]) thinkplot.Sho
w(title='PMF of running speed', xlabel='speed (mph)', ylabel='probability') #ex4()
rkarlberg/opencog
tests/cython/test_agent_finder.py
Python
agpl-3.0
400
0.0125
from unittest import TestCase from agent_finder import find_subclasses i
mport opencog.cogserver import test_agent
class HelperTest(TestCase): def setUp(self): pass def tearDown(self): pass def test_find_agents(self): x=find_subclasses(test_agent,opencog.cogserver.MindAgent) self.assertEqual(len(x),1) self.assertEqual(x[0][0], 'TestAgent')