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
deepmind/acme
acme/utils/loggers/base.py
Python
apache-2.0
1,965
0.006616
# Copyright 2018 DeepMind Technologies Limited. 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 ...
lose(self): pass def tensor_to_numpy(value: Any): if hasattr(value, 'numpy'): return value.numpy() # tf.Tensor (TF2). if hasattr(value, 'device_buffer'): return np.asarray(value) # jnp.De
viceArray. return value def to_numpy(values: Any): """Converts tensors in a nested structure to numpy. Converts tensors from TensorFlow to Numpy if needed without importing TF dependency. Args: values: nested structure with numpy and / or TF tensors. Returns: Same nested structure as values, bu...
StackOps/python-automationclient
automationclient/tests/test_shell.py
Python
apache-2.0
2,750
0.000727
# Copyright 2011 OpenStack LLC. # Copyright 2012-2013 STACKOPS TECHNOLOGIES S.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 re...
AUTH_URL': 'http://no.where', } # Patch os.environ to avoid required auth info. def setUp(self): super(ShellTest, self).setUp() for var in self.FAKE_ENV: self.useFixture(fixtures.EnvironmentVariable(var,
self.FAKE_ENV[var])) def shell(self, argstr): orig = sys.stdout try: sys.stdout = moves.StringIO() _shell = automationclient.shell.StackopsAutomationShell() _shell.main(argstr.split()) except SystemExit: ...
Garrett-R/scikit-learn
sklearn/tests/test_grid_search.py
Python
bsd-3-clause
26,766
0.000224
""" Testing for grid search module (sklearn.grid_search) """ from collections import Iterable, Sized from sklearn.externals.six.moves import cStringIO as StringIO from sklearn.externals.six.moves import xrange from itertools import chain, product import pickle import sys import warnings import numpy as np import sci...
= ParameterGrid({}) assert_equal(len(empty), 1) assert_equal(list(empty), [{}]) has_empty = ParameterGrid([{'C': [1, 10]}, {}]) assert_equal(len(has_empty), 3) assert_equal(list(has_empty), [
{'C': 1}, {'C': 10}, {}]) def test_grid_search(): """Test that the best estimator contains the right value for foo_param""" clf = MockClassifier() grid_search = GridSearchCV(clf, {'foo_param': [1, 2, 3]}, verbose=3) # make sure it selects the smallest parameter in case of ties old_stdout = sys.std...
rpedigoni/fbads
tests/test_creative.py
Python
apache-2.0
1,345
0.002974
# coding: utf-8 from fbads import FBAds from tests import BaseTestCase class FBAdsCreativeTestCase(BaseTestCase): def test_add_creative(self): with self.replay(): fbads = FBAds(account_id='1378857852381224', access_token='a_valid_token') creative_id = fbads.creative.add( ...
n(creatives), 1) creative = creatives.pop() self.assertEqual(creati
ve.id, '6014479876682') self.assertEqual(creative.title, 'Luizalabs.com') def test_delete_creative(self): with self.replay(): fbads = FBAds(account_id='1378857852381224', access_token='a_valid_token') deleted = fbads.creative.delete('6015403647082') self.ass...
s-pearce/glider-utilities
glider_utils/parsers/dbd_parsers.py
Python
gpl-2.0
6,823
0.001905
#!/usr/bin/env python """ @package glider_utils @file glider_utils.py @author Stuart Pearce & Chris Wingard @brief Module containing glider utiliities """ __author__ = 'Stuart Pearce & Chris Wingard' __license__ = 'Apache 2.0' import numpy as np import warnings #import pdb import re #import pygsw.vectors as gsw class...
file. """ # There are usually 14 header lines, start with 14, # and check the 'num_ascii_tags' line. num_hdr_lines = 14 header_pattern = r'(
.*): (.*)$' header_re = re.compile(header_pattern) #pdb.set_trace() hdr_line = 1 while hdr_line <= num_hdr_lines: line = self._fid.readline() match = header_re.match(line) if match: key = match.group(1) value = match.gro...
plotly/plotly.py
packages/python/plotly/plotly/validators/choroplethmapbox/legendgrouptitle/_text.py
Python
mit
452
0
i
mport _plotly_utils.basevalidators class TextValidator(_plotly_utils.basevalidators.StringValidator): def __init__( self, plotly_name="text", parent_name="choroplethmapbox.legendgrouptitle", **kwargs ): super(TextValidator, self).__init__( plotly_name=plotly...
)
anchore/anchore-engine
tests/integration/services/policy_engine/test_cve_updates.py
Python
apache-2.0
7,228
0.000415
""" This is an integration-level test for checking CVE updates at fine granularity. """ import sqlalchemy.exc from anchore_engine.db import ( FixedArtifact, Image, ImagePackage, Vulnerability, VulnerableArtifact, ) from anchore_engine.db import get_thread_scoped_session as get_session from anchore_...
id=test_cve.id) test_vulnin.name = "testpackage" test_vulnin.version = "0.9" test_vulnin.epochless_version = "0.9" test_vulnin.namespace_name = "centos:7" test_vulnin.version_format = "rpm
" test_vulnin.include_previous_versions = False test_vulnin.parent = test_cve test_cve.vulnerable_in = [test_vulnin] db = get_session() try: db.add(test_image) db.add(test_package) db.commit() except sqlalchemy.exc.IntegrityError: db.rollback() except Excepti...
spr/OggifyOSX
mutagen/tests/test_mp4.py
Python
gpl-2.0
19,301
0.001917
import os import shutil import struct from cStringIO import StringIO from tempfile import mkstemp from tests import TestCase, add from mutagen.mp4 import MP4, Atom, Atoms, MP4Tags, MP4Info, \ delete, MP4Cover, MP4MetadataError from mutagen._util import cdata try: from os.path import devnull except ImportError: de...
\x00" * 4 + ilst) data = Atom.render("moov", Atom.render("udta", meta)) fileobj = StringIO(data) return MP4Tags(Atoms(fileobj), fileobj)
def test_genre(self): data = Atom.render("data", "\x00" * 8 + "\x00\x01") genre = Atom.render("gnre", data) tags = self.wrap_ilst(genre) self.failIf("gnre" in tags) self.failUnlessEqual(tags["\xa9gen"], ["Blues"]) def test_empty_cpil(self): cpil = Atom.render("cpil...
user01/love-letter
loveletter/env.py
Python
mit
7,457
0.000805
from operator import itemgetter import gym from gym import spaces from gym.utils import seeding from .game import Game from .card import Card from .player import PlayerAction, PlayerTools from .agents.random import AgentRandom class LoveLetterEnv(gym.Env): """Love Letter Game Environment The goal of
hotter colder is to guess closer to a randomly selected number After each step the agent receives an observation of: 0 - No guess yet submitted (only after reset) 1 - Guess is lower than the target 2 - Guess is equal to the target
3 - Guess is higher than the target The rewards is calculated as: (min(action, self.number) + self.range) / (max(action, self.number) + self.range) Ideally an agent will be able to recognize the 'scent' of a higher reward and increase the rate in which is guesses in that direction until the rewar...
UTSA-ICS/python-keystoneclient-SID
keystoneclient/tests/v2_0/test_access.py
Python
apache-2.0
5,660
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 # d...
th_ref.auth_token, '3e2813b7ba0b4006840c3825860b86ed') self.assertEqual(auth_ref.username, 'exampleuser') self.assertEqual(auth_ref.user_id, 'c4da488862bd435c9e6c0275a0d0e49a') self.assertEqual(auth_ref.role_names, []) self.assertIsNone(auth_ref.tenant_name) ...
rtIsNone(auth_ref.tenant_id) self.assertIsNone(auth_ref.auth_url) self.assertIsNone(auth_ref.management_url) self.assertFalse(auth_ref.scoped) self.assertFalse(auth_ref.domain_scoped) self.assertFalse(auth_ref.project_scoped) self.assertFalse(auth_ref.trust_scoped) ...
chrisswk/reddit_comment_scraper
setup.py
Python
mit
1,062
0.000942
import os, sys from setuptools import setup setup( name='reddit_comment_scraper', version='2.0.5', description='A simple Reddit-scrapin
g script', url='https:
//github.com/jfarmer/reddit_comment_scraper', author='Jesse Farmer', author_email='jesse@20bits.com', license='MIT', packages=['reddit_comment_scraper'], install_requires=[ 'unicodecsv==0.9.4', 'praw==2.1.19' ], entry_points={ 'console_scripts': [ 'scra...
pinax/pinax-referrals
pinax/referrals/apps.py
Python
mit
211
0
from django.apps import AppCo
nfig as BaseAppConfig from django.utils.translation import ugettext_lazy as _ class A
ppConfig(BaseAppConfig): name = "pinax.referrals" verbose_name = _("Pinax Referrals")
yeongseon/django_beautifulseodang
home/forms.py
Python
mit
899
0.003654
from allauth.account.forms import * class MyLoginForm(LoginForm): def __init__(self, *args, **kwargs): super(MyLoginForm, self).__init__(*args, **kwargs) self.fields['login'].label = "이메일" se
lf.fields['password'].label = "비밀번호" self.fields['remember'].label = "로그인 상태 유지" #self.fields['submit'].label = "로그인 상태 유지" # You don't want the `remember` field? # if 'remember' in self.fields.keys(): # del self.fields['remember'] class MySignupForm(SignupForm): def __i...
" self.fields['email'].label = "이메일" self.fields['password1'].label = "비밀번호" self.fields['password2'].label = "비밀번호확인"
ElectroCode/lurklib
lurklib/connection.py
Python
gpl-3.0
13,948
0.001506
# This file is part of Lurklib. # Copyright (C) 2011 LK- # # Lurklib 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....
proxy_type, proxy_server, proxy_port, \ proxy_username, proxy_password) else: if not port: port = 6667 self._connect(server, port, tls, tls_verify, proxy, \ proxy_type, proxy_server, proxy...
a = self.recv() if data[0] == 'NOTICE': self.server = data[1][0] self.con_msg.append(data) self._register(nick, user, real_name, password) while self.readable(timeout=4): rdata = self.recv() if rdata[0] == '...
zqqf16/Peanut
peanut/template.py
Python
mit
1,770
0.000565
#!/usr/bin/env python # -*- coding: utf-8 -*- """Template""" from os import path import jinja2 from jinja2 import FileSystemLoader, ChoiceLoader from jinja2.exceptions import TemplateNotFound import peanut from peanut.utils import get_resource class SmartLoader(FileSystemLoader): """A smart template loader"""...
in SmartLoader.available_extension: try: filename = template + extension return super(SmartLoader, self).get_source(environment, filename) except TemplateNotFound: pass
raise TemplateNotFound(template) class Template(object): """Template""" def __init__(self, path, filters=None, **kwargs): loader = ChoiceLoader([ SmartLoader(path), SmartLoader(get_resource('themes/default')), ]) self.env = jinja2.Environment( load...
deshi-basara/coovie2
coovie2/scan.py
Python
mit
1,799
0.000556
import os import re class Scan(object): def __init__(self, endings, size_limit): self.movie_endings = endings self.movie_size_limit = size_limit def is_movie(self, file_name): ''' Checks weather a handed file is a movie-file by validating its ending. ''' if fi...
ize = file_stat.st_size # convert predefined-settings to bytes and compare """compare_str = '{size} >= {limit}'.format( size=file_size, limit=movie_size_limit ) print(compare_str) """ if file_size >= self.movie_size_limit: return True ...
''' Extract a movie name and year from folder or file ''' # shall we use folder-name or file-name (-4 characters for file- # extension) base_name = folder if len(base_name) < (len(file) - 4): base_name = file # find first digit and use it for e...
genonfire/portality
giza/forms.py
Python
mit
412
0
# -*- coding: utf-8 -*- from
django import forms from giza.models import Giza class GizaEditForm(f
orms.ModelForm): """Giza edit form""" class Meta: """Meta for GizaEditForm""" model = Giza exclude = ('user',) def __init__(self, *args, **kwargs): """Init""" self.user = kwargs.pop('user', None) super(GizaEditForm, self).__init__(*args, **kwargs)
LynxyssCZ/Flexget
flexget/plugins/output/utorrent.py
Python
mit
6,154
0.00195
from __future__ import unicode_literals, division, absolute_import from builtins import * # noqa pylint: disable=unused-import, redefined-builtin import os from logging import getLogger from flexget import plugin from flexget.event import event from flexget.utils import requests from flexget.utils.soup import get_so...
).json() download_dirs = dict((os.path.normcase(dir['path']), i) for i, dir in en
umerate(result['download-dirs'])) for entry in task.accepted: # bunch of urls now going to check folder = 0 path = entry.get('path', config.get('path', '')) try: path = os.path.expanduser(entry.render(path)) except RenderError as e: ...
pgermain/pbda
pbda_classify.py
Python
bsd-2-clause
2,793
0.006087
#!/usr/bin/env python #-*- coding:utf-8 -*- ''' PAC-BAYESIAN DOMAIN ADAPTATION (aka PBDA) Executable script to use the classifier (to be used after the learning process). @author: Pascal Germain -- http://researchers.lille.inria.fr/pgermain/ ''' import common from pbda import * from dataset import * from kernel import...
###### predictions = classifier.predict(test_data.X) try: predictions.tofile(args.prediction_file, '\n') print('File "' + args.prediction_file + '" created.') except: print('ERROR
: Unable to write prediction file "' + args.prediction_file + '".') risk = classifier.calc_risk(test_data.Y, predictions=predictions) print('Test risk = ' + str(risk))
thomas-schmid-ubnt/avocado
avocado/core/dispatcher.py
Python
gpl-2.0
8,715
0.000688
# This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # bu...
.extension.Extension` """ return "%s.%s" % (self.plugin_type(), extension.entry_point.name) def settings_section(self): """ Returns the config section name for the plugin type handled by itself """ return "plugins.%s" % self.plugin_type() def enabled(self, exten...
ames(self): """ Returns the names of the discovered extensions This differs from :func:`stevedore.extension.ExtensionManager.names` in that it returns names in a predictable order, by using standard :func:`sorted`. """ return sorted(super(Dispatcher, self).names(...
rogerscristo/BotFWD
env/lib/python3.6/site-packages/pytests/test_inlinequeryresultgame.py
Python
mit
3,198
0.001251
#!/usr/bin/env python # # A library that provides a Python interface to the Telegram Bot API # Copyright (C) 2015-2017 # Leandro Toledo de Souza <devs@python-telegram-bot.org> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as publis...
dict, dict) assert inline_query_result_game_dict['type'] == inline_query_result_game.type assert inline_query_result_game_dict['id'] == inline_query_result_game.id assert inline_query_result_game_dict['game_short_name'] == \ inline_query_result_game.game_short_name as...
ultGame(self.id, self.game_short_name) b = InlineQueryResultGame(self.id, self.game_short_name) c = InlineQueryResultGame(self.id, "") d = InlineQueryResultGame("", self.game_short_name) e = InlineQueryResultVoice(self.id, "", "") assert a == b assert hash(a) == h...
RedhawkSDR/integration-gnuhawk
components/tagged_file_sink_f/tests/test_tagged_file_sink_f.py
Python
gpl-3.0
4,079
0.006864
#!/usr/bin/env python # # This file is protected by Copyright. Please refer to the COPYRIGHT file # distributed with this source distribution. # # This file is part of GNUHAWK. # # GNUHAWK is free software: you can redistribute it and/or modify is under the # terms of the GNU General Public License as published by ...
If not, see http://www.gnu.org/licenses/. # import unittest import ossie.utils.testing import os from omniORB import any class ComponentTests(ossie.utils.testing.ScaComponentTestCase): """Test for all component implementations in tagged_file_sink_f""" def testScaBasicBehavior(self): ###############...
unch the component with the default execparams execparams = self.getPropertySet(kinds=("execparam",), modes=("readwrite", "writeonly"), includeNil=False) execparams = dict([(x.id, any.from_any(x.value)) for x in execparams]) self.launch(execparams) ##############################...
percyfal/luigi
test/dynamic_import_test.py
Python
apache-2.0
1,810
0.001657
# -*- coding: utf-8 -*- # # Copyright 2012-2015 Spotify AB # # 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...
ExtraArgs(luigi.Task): blah = luigi.Parameter(default=444) class CmdlineTest(LuigiTestCase): def test_dynamic_loading(self): interface = luigi.interface.DynamicArgParseInterface() with tempfile.NamedTe
mporaryFile(dir='test/', prefix="_foo_module", suffix='.py') as temp_module_file: temp_module_file.file.write(b''' import luigi class FooTask(luigi.Task): x = luigi.IntParameter() ''') temp_module_file.file.flush() temp_module_path = temp_module_file.name temp_module...
ksmit799/Toontown-Source
toontown/safezone/DistributedFishingSpot.py
Python
mit
42,911
0.002377
from pandac.PandaModules import * from direct.interval.IntervalGlobal import * from direct.gui.DirectGui import * from pandac.PandaModules import * from direct.directtools.DirectGeometry import LineNodePath from direct.distributed import DistributedObject from direct.directnotify import DirectNotifyGlobal from toontown...
om toontown.hood import ZoneUtil from toontown.toontowngui import TeaserPanel class DistributedFishingSpot(DistributedObject.DistributedObject): notify = DirectNotifyGlobal.directNotify.newCategory('DistributedFishingSpot') vZ
eroMax = 25.0 angleMax = 30.0 def __init__(self, cr): DistributedObject.DistributedObject.__init__(self, cr) self.lastAvId = 0 self.lastFrame = 0 self.avId = 0 self.av = None self.placedAvatar = 0 self.localToonFishing = 0 self.nodePath = None ...
klahnakoski/Bugzilla-ETL
vendor/pyLibrary/env/emailer.py
Python
mpl-2.0
4,306
0.002555
# encoding: utf-8 # # # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this file, # You can obtain one at http://mozilla.org/MPL/2.0/. # # Author: Kyle Lahnakoski (kyle@lahnakoski.com) # from __future__ import unicode_literals from _...
ml')) msg['Subject'] = coalesce(subject, settings.subject) msg['From'] = from_address msg['To'] = ', '.join(to_address) if self.server: # CALL AS PAR
T OF A SMTP SESSION self.server.sendmail(from_address, to_address, msg.as_string()) else: # CALL AS STAND-ALONE with self: self.server.sendmail(from_address, to_address, msg.as_string()) if sys.hexversion < 0x020603f0: # versions earlier than 2.6.3 have...
supertask/ChainX
server/websocket/recorded_operations/combiner.py
Python
mit
1,425
0.00432
#!/usr/bin/env python # -*- coding:utf-8 -*- import sys import os import json SPLIT_CHAR = '#' MSG_SPLIT_CHAR = '@' MIN_BETWEEN_BEFORE_AFTER = 1 if len(sys.argv) < 3: print "引数が足りない(<infile1> <infile2>)" sys.exit(1) in_file_1 = sys.argv[1] in_file_2 = sys.argv[2] out_file = "combined_file.txt" wf = open(out...
RE_AFTER秒(x * 10^7 * 100ナノ秒)の間隔をあける currentTs = 0 exCurrentTs = 0 newCurrentTs = last_ts + MIN_BETWEEN_BEFORE_AFTER * (10 ** 7) firstOperation = True for line in rf: line = line.replace('\n', '') if line == '': continue #print line op_name,param = line.split(MSG_SPLIT_CHAR) if op_name == "OPERATION...
dict = json.loads(param) ts_str = op_dict["ts"] currentTs = long(op_dict["ts"]) diffTs = currentTs - exCurrentTs if firstOperation: diffTs = 0 firstOperation = False newCurrentTs += diffTs line = line.replace(ts_str, str(newCurrentTs)) wf....
eduNEXT/edx-platform
lms/djangoapps/course_api/blocks/transformers/tests/test_video_urls.py
Python
agpl-3.0
5,797
0.002933
""" Tests for VideoBlockURLTransformer. """ from unittest import mock from openedx.core.djangoapps.content.block_structure.factory import BlockStructureFactory from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase # lint-amnesty, pylint: disable=wrong-import-order from xmodule.modulestore.tests.fac...
1234abcd.mp4', 'file_size': 0 } }, 'only_on_web': False } video_block_key = self.course_key.make_usage_key('video', 'sample_video') pre_transform_data = self.get_pre_transform_data(video_block_key)
pre_transform_data = self.change_encoded_videos_presentation(pre_transform_data['encoded_videos']) self.collect_and_transform() post_transform_data = self.get_post_transform_data(video_block_key) post_transform_data = self.change_encoded_videos_presentation(post_transform_data['encoded_videos'...
51reboot/homework-arch-4
2/chenkun/proc_pachong.py
Python
apache-2.0
1,151
0.02172
#!/usr/bin/python #coding=utf-8 import re,time,urllib,urllib2,cookielib,multiprocessing img_path="/opt/imgs/" def down_imgs(): url_login = 'http://www.douban.com/accounts/login' values = {'form_email':'chenkun0226@163.com','form_password':'abc12345678'} data = urllib.urlencode(values) ...
j = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) response = opener.open(req) the_page = response.read().decode("utf-8").encode("gbk") url_list = re.findall('"http://.*.jpg" alt',the_page) for url_u in url_list: img_url = url...
_name) print "%s saved!" %img_name if __name__ == "__main__": pool = multiprocessing.Pool(processes=120) pool.apply_async(down_imgs,()) time.sleep(0.2) pool.close() pool.join()
qtumproject/qtum
test/functional/tool_wallet.py
Python
mit
9,551
0.003036
#!/usr/bin/env python3 # Copyright (c) 2018-2019 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test bitcoin-wallet.""" import hashlib import os import stat import subprocess import textwrap from t...
process?', '-wallet=wallet.dat', 'info') self.assert_raises_tool_error('Error: no wallet file at nonexistent.dat', '-wallet=nonexistent.dat', 'info') def test_tool_wallet_info(self): # Stop the node to close the wallet to call the info command. self.stop_node(0) self.log.info('Call...
testing output') # # TODO: Wallet tool info should work with wallet file permissions set to # read-only without raising: # "Error loading wallet.dat. Is wallet being used by another process?" # The following lines should be uncommented and the tests still succeed: # ...
jandom/rdkit
rdkit/Chem/Pharm2D/UnitTestGobbi.py
Python
bsd-3-clause
5,595
0.008758
# $Id$ # # Copyright (C) 2002-2006 greg Landrum and Rational Discovery LLC # # @@ All Rights Reserved @@ # This file is part of the RDKit. # The contents are covered by the terms of the BSD license # which is included in the file license.txt, found at the root # of the RDKit source tree. # """unit testing code f...
(0, None), 'X': (0, None), 'BG': (0, None), 'AG': (0, None), }), ('CC1CCC1', { 'HA': (0, None), 'HD': (0, None), 'LH': (1, ((1, ), (3, ))),
'AR': (0, None), 'RR': (1, ((1, ), )), 'X': (0, None), 'BG': (0, None), 'AG': (0, None), }), ('[SiH3]C1CCC1', { 'HA': (0, None), 'HD': (0, None), 'LH': (1, ((1, ), )), 'AR': (0, None), 'RR': (1, ((1, ), )), 'X': (1, ((0, ), )), ...
ZachOhara/Project-Euler
python/p001_p010/problem001.py
Python
gpl-3.0
196
0.061224
def main(): print(sumMultiplesOf(3, 5, 1000)) def sumMultiplesOf(a, b, cap): s = 0 for i in range(cap): if i % a == 0 or i % b == 0: s += i return s
if _
_name__ == "__main__": main()
lfalvarez/votai
proposal_subscriptions/views.py
Python
gpl-3.0
3,370
0.000891
# coding=utf-8 from django.views.generic.edit import CreateView, DeleteView from proposal_subscriptions.models import SearchSubscription from django.contrib.auth.mixins import LoginRequiredMixin from pytimeparse.timeparse import timeparse from django.forms import ModelForm from django.http import JsonResponse from djan...
elf.filter_class = kwargs.pop('filter_class') self.search_params = kwargs.pop('search_params') super(SubscriptionCreateForm, self).__init__(*args, **kwargs) def save(self): subscription = super(SubscriptionCreateForm, self).save(commit=False) subscription.user = self.user su...
subscription.save() return subscription class Meta: model = SearchSubscription fields = ['oftenity', ] class SearchSubscriptionCreateView(LoginRequiredMixin, CreateView): form_class = SubscriptionCreateForm template_name = 'proposal_subscriptions/subscribe_to_search.html' ...
Sistemas-Multimedia/Icecast-tracker
Django/Savins/Icecast_tracker/manage.py
Python
gpl-2.0
258
0
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Icecast_tra
cker.se
ttings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
syncloud/lib
syncloudlib/application/paths.py
Python
gpl-3.0
223
0
from syncloudlib.application.connection import api_get def get_app_dir(app): return api_get('/app/install_path?name={0}'.format(app)) def get_data_dir(app): return
api_get('/app/data_path?name={0}'.format(app))
inspirehep/invenio
modules/bibindex/lib/bibindex_engine.py
Python
gpl-2.0
105,731
0.002913
# -*- coding: utf-8 -*- ## ## This file is part of Invenio. ## Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, ## 2010, 2011, 2012, 2013, 2014, 2015, 2016 CERN. ## ## Invenio is free software; you can redistribute it and/or ## modify it under the terms of the GNU General Public License as ## published b...
unicode_520 from invenio.bibindex_termcollectors import \ TermCollector, \ NonmarcTermCollector from invenio.memoiseutils
import Memoise if sys.hexversion < 0x2040000: # pylint: disable=W0622 from sets import Set as set # pylint: enable=W0622 ## precompile some often-used regexp for speed reasons: re_subfields = re.compile('\$\$\w') re_datetime_shift = re.compile("([-\+]{0,1})([\d]+)([dhms])") re_prefix = re.compile('__[a-...
rye761/fDict
fdict.py
Python
mit
7,906
0.007336
from flask import Flask, request, redirect, url_for, render_templ
ate, flash, abort, Response, jsonify from flask.ext.pymongo import PyMongo from flask.ext.login import LoginManager, UserMixin, login_user, logout_user, login_required, current_user from flask.ext.bcrypt import Bcrypt from bson import ObjectId from flask_jsglue import JSGlue #Config DEBUG = True SECRET_KEY = '5eb51592...
6bfaf5b064844' #This should be changed if this is ever run in production, though it is unlikely it will ever need to be, seeing as this is a test project. app = Flask(__name__) app.config.from_object(__name__) mongo = PyMongo(app) login_manager = LoginManager() login_manager.init_app(app) bcrypt = Bcrypt(app) jsglue =...
SamoFMF/stiri_v_vrsto
alphabeta.py
Python
mit
17,907
0.007014
from logika import IGRALEC_R, IGRALEC_Y, PRAZNO, NEODLOCENO, NI_KONEC, MAKSIMALNO_STEVILO_POTEZ, nasprotnik from five_logika import Five_logika from powerup_logika import Powerup_logika, POWER_STOLPEC, POWER_ZETON, POWER_2X_NW, POWER_2X_W from pop10_logika import Pop10_logika from pop_logika import Pop_logika import ra...
ni_red, 3) for i in range(1,3): dodajamo = [4-i,4+i] # Poteze, ki jih želimo dodati dodajamo = random.sample(dodajamo, 2)
for j in dodajamo: zeljen_vrstni_red.append(j) elif isinstance(self.igra, Powerup_logika): # Imamo Power Up igro # Dodajmo dvojne poteze brez možnosti zmage # Najprej dodamo te, ker če bi takšne z možnostjo zmage, # bi jih (la...
twisted/quotient
xquotient/stressmtp.py
Python
mit
3,190
0.006897
import os import sys import time from StringIO import StringIO from os.path import join as opj from twisted.python import log from twisted.internet import defer from twisted.mail import smtp from twisted.internet import reactor def sendmail(smtphost, port, from_addr, to_addrs, msg): msg = StringIO(str(msg)) d...
ation def send(self, nConns=1, bps=None): d = []
pb = self.messages.append for c in range(nConns): d.append(MessageSender(self.host, self.port, self.recip, self.next, bps, pb ).sendMessages( ).addCallback(self._cbSenderFinished )) return defer.DeferredList(d ).addCallback...
gpldecha/gym-square
setup.py
Python
mit
407
0.004914
from setupto
ols import setup from setuptools import find_packages setup(name='gym_square', version='0.0.1', author='Guillaume de Chambrier', author_email='chambrierg@gmail.com', description='A simple square world environment for openai/gym', packages=find_packages(), url='https://github.com/gpl...
install_requires=['gym'] )
Bysmyyr/chromium-crosswalk
tools/telemetry/telemetry/web_perf/metrics/timeline_based_metric.py
Python
bsd-3-clause
3,168
0.005051
# Copyright 2014 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. class TimelineBasedMetricException(Exception): """Exception that can be thrown from metrics that implements TimelineBasedMetric to indicate a problem...
actionRecord. Returns: True if |event|'s start & end time is in any of the |interaction_records|'s time range. """ return any(ir.start <= event.start and ir.end >= event.end for ir in interaction_records) class TimelineBasedMetric(object): def __init__(self): """Computes metrics fro...
putes and adds metrics for the interaction_records' time ranges. The override of this method should compute results on the data **only** within the interaction_records' start and end time ranges. Args: model: An instance of telemetry.timeline.model.TimelineModel. interaction_records: A list of...
agoose77/hivesystem
manual/movingpanda/panda-15c.py
Python
bsd-2-clause
3,125
0.00192
from pandalib import myhive, myscene, pandalogichive, pandalogicframe, load_hive, camerabind import bee, dragonfly from bee import connect import Spyder camerahive = "camera.web" pandadict = {} # global variable... # First panda class a = Spyder.AxisSystem() a *= 0.005 data = "models/panda-model", "egg", [("walk", ...
yderframe): mode, data, box, image, hivemap = panda model, modelformat, animations, a = data if mode == "actor": obj = Spyder.ActorClass3D(model, modelformat, animations, a, actorclassname=name) elif mode == "model": model = Spyder.Model3D(model, modelformat, a) ...
obj = Spyder.EntityClass3D(name, [model]) else: raise ValueError(mode) im, transp = image icon = Spyder.Icon(im, name, box, transparency=transp) del model, modelformat, animations, a del mode, data, box, image, hivemap del im, transp return pandascene...
Azure/azure-sdk-for-python
sdk/appservice/azure-mgmt-web/azure/mgmt/web/v2021_03_01/operations/_certificates_operations.py
Python
mit
26,217
0.004272
# 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 ...
.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.rest import HttpR
equest from azure.core.tracing.decorator import distributed_trace from azure.mgmt.core.exceptions import ARMErrorFormat from msrest import Serializer from .. import models as _models from .._vendor import _convert_request, _format_url_section T = TypeVar('T') JSONType = Any ClsType = Optional[Callable[[PipelineRespons...
the-zebulan/CodeWars
katas/beta/lets_flat_them_out.py
Python
mit
396
0
from collections import MutableMapping d
ef flatten(d, parent_key='', sep='/'): result = [] for k, v in d.iteritems(): new_key = parent_key + sep + k if parent_key else k if isinstance(v, MutableMapping): result.extend(flatten(v, new_key, sep=sep).iteritems()) else: result.append((new_key, v)) return...
}
elifesciences/elife-tools
tests/test_parse_jats.py
Python
mit
132,828
0.001197
# coding=utf-8 import json import os import unittest from collections import OrderedDict from bs4 import BeautifulSoup from ddt import ddt, data, unpack from elifetools import parseJATS as parser from elifetools import rawJATS as raw_parser from elifetools.utils import date_struct from tests.file_utils import ( sa...
("elife07586.xml", []), ) def test_keywords_json(self, filename, expected): keywords_json = parser.keywords_json(self.soup(filename)) self.assertEqual(expected, keywords_json) @unpack @data( ('<root xmlns
:xlink="http://www.w3.org/1999/xlink"/>', []), ( '<root xmlns:xlink="http://www.w3.org/1999/xlink"><kwd-group kwd-group-type="research-organism"><title>Research organism</title><kwd><italic>A. thaliana</italic></kwd><kwd>Other</kwd></kwd-group></root>', ["<i>A. thaliana</i>"], ),...
Melon-PieldeSapo/IoTFramework
src/tests/test_ground.py
Python
gpl-3.0
1,704
0.019953
test = "#{0}:{1};" import re regex = re.compile(test,re.IGNORECASE) pattern = r'[{]\d[}]' regex = re.compile(pattern,re.IGNORECASE) print regex parsed = [] for idx,match in enumerate(regex.finditer(test)): parsed.append({'start':match.start(),'end':match.end()}) print "%s: %s-%s: %s" % (str(idx),match.start...
n array para valor donde se guarda el preceding string y el postceding string. (en caso de no
haber al principio o al final se guarda un -1 #Para procesar el payload se va extrallendo el substring de forma que lo que va quedando al principio siempre debe estar el preceding string. payload = "#2:643.0605;" payload_group = [] for group in parsed: start= payload.find(group['prec'])+len(group['prec']) ...
blueyed/pytest_django
tests/compat.py
Python
bsd-3-clause
270
0
try: from django.utils.encoding import force_text # noqa exc
ept ImportError: from django.utils.encoding import force_unicode as force_text # noqa try: from urllib2 import urlopen # noqa except ImportError: from urlli
b.request import urlopen # noqa
michaelforney/libblit
amdgpu/makeregheader.py
Python
isc
16,007
0.003061
from __future__ import absolute_import, division, print_function, unicode_literals COPYRIGHT = ''' /* * Copyright 2015-2019 Advanced Micro Devices, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to dea...
self.register_lines else None if prev and prev.address == line.address and prev.name == line.name:
prev.chips.update(line.chips) prev.type_refs.update(line.type_refs) continue self.register_lines.append(line) # Merge field lines lines = self.field_lines lines.sort(key=lambda line: (line.address, line.name)) self.field_lines ...
webcomics/dosage
dosagelib/plugins/comicfury.py
Python
mit
56,565
0.000177
# SPDX-License-Identifier: MIT # Copyright (C) 2004-2008 Tristan Seligmann and Jonathan Jacobs # Copyright (C) 2012-2014 Bastian Kleineidam # Copyright (C) 2015-2021 Tobias Gruetzmacher # Copyright (C) 2019-2020 Daniel Ring import os from ..scraper import _ParserScraper from ..helpers import bounceStarter XPATH_LINK ...
'amara'), cls('Ampre', 'ampere'), cls('AmyOok', 'amyook'), cls('AndroidFiles', 'androidfiles'), cls('AngelGuardianEnEspanol', 'angelguardianespano
l', 'es'), cls('AngelsOfIblis', 'angelsofiblis'), cls('AngryFaerie', 'angryfaerie'), cls('AnimalInstinct', 'fur-realanimalinstinct'), cls('Animangitis', 'animangitis'), cls('AnK', 'ank'), cls('Anne', 'anne'), cls('AntarcticBroadcasting'...
qedsoftware/commcare-hq
corehq/ex-submodules/pillowtop/tests/test_bulk.py
Python
bsd-3-clause
1,267
0.001591
# coding=utf-8 import json from django.test import SimpleTestCase from corehq.util.test_utils import generate_cases from pillowtop.utils import prepare_bulk_payloads class BulkTest(SimpleTestCase): def test_
prepare_bulk_payloads_unicode(self): unicode_domain = u'हिंदी' bulk_changes = [ {'id': 'doc1'}, {'id': 'doc2', 'domain': unicode_domain}, ] payloads = prepare_bulk_payloads(bulk_changes, max_size=10, chunk_si
ze=1) self.assertEqual(2, len(payloads)) self.assertEqual(unicode_domain, json.loads(payloads[1])['domain']) @generate_cases([ (100, 1, 3), (100, 10, 1), (1, 1, 10), (1, 2, 5), ], BulkTest) def test_prepare_bulk_payloads2(self, max_size, chunk_size, expected_payloads): bulk_changes...
RCOSDP/waterbutler
tests/providers/azureblobstorage/test_provider.py
Python
apache-2.0
18,530
0.001943
import pytest import math import io import time import base64 import hashlib from http import client from unittest import mock import aiohttpretty from waterbutler.core import streams from waterbutler.core import metadata from waterbutler.core import exceptions from waterbutler.core.path import WaterButlerPath from...
<Content-Language /> <Content-MD5 /> <Cache-Control /> <Content-Disposition /> <BlobType>BlockBlob</BlobT
ype> <LeaseStatus>unlocked</LeaseStatus> <LeaseState>available</LeaseState> </Properties> </Blob> <Blob> <Name>top.txt</Name> <Properties> <Last-Modified>Thu, 10 Nov 2016 11:04:45 GMT</Last-Modified> <Etag>0x8D40959613D32F6</Etag> <Content-Length>0</Cont...
makinacorpus/mapnik2
scons/scons-local-1.2.0/SCons/cpp.py
Python
lgpl-2.1
19,982
0.003853
# # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008 The SCons Foundation # # 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...
lists # of preprocessor directives map. cpp_lines_dict = { # Fetch the rest of a #if/#elif/#ifdef/#ifndef as one argument, # separated from the keyword by white space. ('if', 'elif', 'ifdef', 'ifndef',) : '\s+(.+)', # Fetch the rest of a #import/#include/#include_next line as on...
\s*(.+)', # We don't care what comes after a #else or #endif line. ('else', 'endif',) : '', # Fetch three arguments from a #define line: # 1) The #defined keyword. # 2) The optional parentheses and arguments (if it's a function-like # macro, '' if it's not). # 3) The expansion ...
Orange-OpenSource/cf-php-build-pack
extensions/appdynamics/extension.py
Python
apache-2.0
11,666
0.004543
# 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 use ...
abled = AppDynamicsInstaller._appdynamics_credentials.get("ssl-enabled") except Exception: print("Error populating AppDynamics controller binding credentials") else: print("AppDynamics credentials empty") def _load_app_details(self): """ Configure App...
AppDynamicsInstaller._app_name = self._application.get("space_name") + ":" + self._application.get("application_name") print("AppDymamics default application-name = " + AppDynamicsInstaller._app_name) AppDynamicsInstaller._tier_name = self._application.get("application_name") ...
cmccabe/redfish
deploy/st_chunk_io.py
Python
apache-2.0
1,287
0.00777
#!/usr/bin/python from optparse import OptionParser import filecmp import json import of_daemon import of_node import of_util import os import subprocess import sys import tempfile import time of_util.check_python_version() parser = OptionParser() (opts, args, node_list) = of_util.pa
rse_deploy_opts(parser) if opts.bld_dir == None: sys.stder
r.write("you must give a Redfish build directory\n") sys.exit(1) # get a chunk ID that we think will be unique cid = int(time.clock()) cid = cid + (os.getpid() << 32) # create input file input_file = opts.bld_dir + "/hello.in" f = open(input_file, "w") try: print >>f, "hello, world!" finally: f.close() ...
jsbueno/towertower
towertower/__init__.py
Python
gpl-3.0
14,154
0.00106
# coding: utf-8 from __future__ import division import random from random import randint import pygame from pygame.locals import * SIZE = 800, 600 FLAGS = 0 # actually, delay in ms: FRAMERATE = 30 WAVE_ENEMIES = [1, 5, 1] Group = pygame.sprite.OrderedUpdates class GameOver(Exception): pass class NoEnemyI...
rgy_bar(self): if hasattr(self, "energy"): total, remaining = energy = self.energy if getattr(self, "_last_energy", None) == energy: return self._reset_image() self._last_energy = energy width = int(self.size * 0.7) y = int(...
.draw.line(self.image, (0, 0, 0), (x, y), (x + width, y), 3) color = (0, 255, 0) if remaining > total / 2 else (255, 255, 0) if remaining > total / 4 else (255, 0, 0) pygame.draw.line(self.image, color, (x, y), (x + int(width * remaining / total), y), 3) class Targetting(BaseTowerObject): ...
Statoil/libecl
python/tests/util_tests/test_thread_pool.py
Python
gpl-3.0
2,274
0.003078
import time from ecl.util.util import ThreadPool from ecl.util.util.thread_pool import Task from tests import EclTest class ThreadPoolTest(EclTest): def sleepTask(self, *args, **kwargs): time.sleep(args[0]) def numberer(self, index, result): result[index] = True def test_pool_creation(...
result = {} for index in range(10): pool.addTask(self.numberer, index, result=result) pool.nonBlockingStart() pool.join() for index in range(10): self.assertTrue(index in result) self.assertTrue(result[in
dex]) self.assertFalse(pool.hasFailedTasks()) def test_pool_unbound_fail(self): pool = ThreadPool(4) self.assertEqual(4, pool.poolSize()) pool.addTask(ThreadPoolTest.numberer, 0, {}) pool.nonBlockingStart() pool.join() self.assertTrue(pool.hasFailedTask...
jrbl/invenio
modules/websearch/lib/search_engine.py
Python
gpl-2.0
270,395
0.006746
# -*- coding: utf-8 -*- ## This file is part of Invenio. ## Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 CERN. ## ## Invenio 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 Softwar
e Foundation; either version 2 of the ## License, or (at your option) any later version. ## ## Invenio is distributed in the hope that it will be useful, but ## WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ## General Public License for m...
received a copy of the GNU General Public License ## along with Invenio; if not, write to the Free Software Foundation, Inc., ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. # pylint: disable=C0301 """Invenio Search Engine in mod_python.""" __lastupdated__ = """$Date$""" __revision__ = "$Id$" ## import ...
alejob/mdanalysis
package/MDAnalysis/migration/fixes/fix_agmethods2.py
Python
gpl-2.0
1,114
0.004488
''' run with: python ten2eleven.py -f agmethods2 test_dummy_old_MDA_code.py Author: Tyler Reddy ''' from lib2to3.fixer_base import BaseFix from lib2to3.fixer_util import Name, Call, LParen, RParen, ArgList, Dot from lib2to3 import pytree class FixAgmethods2(BaseFix): PATTERN = """ power< head =any+ ...
hod'][0] tail = results['tail'] syms = self.syms method_name = method.value if method_name == 'torsion': method_name = 'dihedral' head = [n.clone() for n in head]
tail = [n.clone() for n in tail] args = head + [pytree.Node(syms.trailer, [Dot(), Name(method_name, prefix = method.prefix), Dot(), Name('value'), LParen(), RParen()])] new = pytree.Node(syms.power, args) return new
beetbox/beets
test/test_dbcore.py
Python
mit
23,723
0.000042
# This file is part of beets. # Copyright 2016, Adrian Sampson. # # 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, ...
vision) # revision changed, so the model should be re-loaded model.load() self.assertEqual(model._revision, self.db.revision) # revision did not change, so no reload mod2_old_rev = model2._revision model2.load() self.assertEqual(model2._revision, mod2_old_rev) ...
id(self): model = ModelFixture1() model.add(self.db)
apache/incubator-superset
superset/dashboards/commands/importers/v1/__init__.py
Python
apache-2.0
6,297
0.000794
# 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...
lsCommand from superset.dashboards.commands.exceptions import DashboardImportError from superset.dashboards.commands.importers.v1.utils import ( find_chart_uuids, find_native_filter_datasets, import_dashboard, update_id_refs, ) from superset.dashboar
ds.dao import DashboardDAO from superset.dashboards.schemas import ImportV1DashboardSchema from superset.databases.commands.importers.v1.utils import import_database from superset.databases.schemas import ImportV1DatabaseSchema from superset.datasets.commands.importers.v1.utils import import_dataset from superset.datas...
hzlf/discogs-proxy
website/apps/dgsproxy/stats.py
Python
mit
2,133
0.004219
# -*- coding: utf-8 -*- from decimal import Decimal import logging from django.core.cache import cache from django.db.models import Sum log = logging.getLogger(__name__) CACHE_PREFIX = 'dgsproxy_stats_' class ProxyStats(object): def __init__(self): self.hits_proxied = 0 self.hits_cached = 0 ...
(remain, limit)) # Writ
e values to cache cache.set('%s_rate_limt' % CACHE_PREFIX, int(limit)) cache.set('%s_rate_limt_remain' % CACHE_PREFIX, int(remain)) pass def set_hit(target): if target in ('cache', 'backend'): log.debug('Add %s hit' % target) key = '%s_hits_%s' % (CACHE_PREFIX, target) if c...
windelbouwman/ppci-mirror
ppci/utils/binary_txt.py
Python
bsd-2-clause
892
0
""" Small helper to convert binary data into text and vice-versa. """ import binascii from .chunk import chunks def bin2asc(data: bytes): """ Encode binary data as ascii. If it is a large data set, then use a list of hex characters. """ if len(data) > 30: res = [] for part in chunk...
return binascii.hexlify(data).decode("ascii") def asc2bin(data) -> bytes: """ Decode ascii into binary """
if isinstance(data, str): return bytes(binascii.unhexlify(data.encode("ascii"))) elif isinstance(data, list): res = bytearray() for part in data: res.extend(binascii.unhexlify(part.encode("ascii"))) return bytes(res) else: # pragma: no cover raise NotImple...
skycucumber/Messaging-Gateway
webapp/venv/lib/python2.7/site-packages/twisted/trial/test/test_pyunitcompat.py
Python
gpl-2.0
8,688
0.001957
# Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. from __future__ import division, absolute_import import sys import traceback from zope.interface import implementer from twisted.python.compat import _PY3 from twisted.python.failure import Failure from twisted.trial.unittest import Synchronous...
) def test_skip26(self): """ On Python 2.6, pyunit doesn't support skipping, so it gets added as a failure to the L{pyunit.TestResult}. """ class SkipTest(SynchronousTestCase): def
test_skip(self): 1/0 test_skip.skip = "Let's skip!" test = SkipTest('test_skip') result = pyunit.TestR
gencer/sentry
src/sentry/quotas/base.py
Python
bsd-3-clause
4,175
0.001198
""" sentry.quotas.base ~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from __future__ import absolute_import import six from django.conf import settings from sentry import options from sentry.utils.services import Servi...
hould # be allowed to consume the entire quota. if settings.SENTRY_SINGLE_ORGANIZATION: if system_limit < account_limit: return (system_limit, 60) return (account_limit, 3600) # an account limit
is enforced, which is set as a fixed value and cannot # utilize percentage based limits elif account_limit: return (account_limit, 3600) return ( self.translate_quota( settings.SENTRY_DEFAULT_MAX_EVENTS_PER_MINUTE, system_limit, ...
serge-cohen/Lima
common/python/Debug.py
Python
gpl-3.0
2,593
0.004242
############################################################################ # This file is part of LImA, a Library for Image Acquisition # # Copyright (C) : 2009-2011 # European Synchrotron Radiation Facility # BP 220, Grenoble 38043 # FRANCE # # This is free software; you can redistribute it and/or modify # it under ...
ilename) lineno = frame.f_lineno @functools.wraps(fn) def real_fn(*arg, **kw): sys.exc_clear() fn_globals = dict(fn.func_globals) deb_obj = DebObj(deb_params, fn.func_name, '', filename, lineno) fn_globals['deb'] = deb_obj if deb_container is not None: deb...
unctionType(fn.func_code, fn_globals, fn.func_name, fn.func_defaults) return new_fn(*arg, **kw) return real_fn def DEB_GLOBAL(deb_mod): DEB_PARAMS(deb_mod, '', True, 2) def DEB_CLASS(deb_mod, class_name): DEB_PARAMS(deb_mod, class_name, False, 2) de...
LibreSoftTeam/R-SNA
GraphDataCreator.py
Python
gpl-2.0
32,520
0.001907
#!/usr/bin/python # -*- coding: iso-8859-15 -*- """ GraphDataCreator Shell(bash)-to-Pyhton translation from Christian Ramiro code Miguel Angel Fernandez Sanchez """ #TODO Implement -s option (program lauched from a super-script, no questions) import os import sys from time import strftime, gmtime import subprocess i...
self.conf_opt = {} self.conf_opt['v'] = True # Verbose option (-v) self.conf_opt['f'] = '1971-1-1' # Starting date of study option (-f) self.conf_opt['t'] = self.date_now # Ending date opt. (-t) self.conf_opt['r'] = "" # Repository URL option (-r) self.conf_opt['h'] = False...
self.fichtag = open('fichtag.log', 'a') def create_data_files(self): os.mkdir(self.DATA_PATH) os.mkdir(self.CHECKOUT_PATH) os.mkdir(self.OUT_PATH) for out_file in self.out_names.keys(): dir_to_open = self.DATA_PATH + '/' + self.out_names[out_...
zwelchWI/BoostEM
source/runTests.py
Python
mit
1,237
0.028294
import sys import subprocess seeds = [1,2,3,4,5,6,7,8,9,10] seeds = [1,2,3,4] for seed in seeds: boostem='python EM.py --input=../data/wdbc.arff --learner=dt --tboost=20 --labelFrac=0.2 --dtM=100 --seed='+str(seed) print boostem subprocess.call(boostem, shell=True) fullBoost='python EM.py --input=../d...
rue) justEM='python EM.py --input=../data/wdbc.arff --learner=dt --tboost=1 --labelFrac=0.2 --dtM=100 --seed='+str(seed) #print justEM #subprocess.call(justEM, shell=True) FullOne='python EM.py --input=../data/wdbc.arff --learner=dt --tboost=1 --labelFrac=1.0 --dtM=100 --see
d='+str(seed) # print FullOne # subprocess.call(FullOne, shell=True) justOne='python EM.py --input=../data/wdbc.arff --learner=dt --tboost=1 --labelFrac=0.2 --dtM=100 --loseUnlabeled --seed='+str(seed) #print justOne #subprocess.call(justOne, shell=True)
wasiqmukhtar/tcp-eval.wasiq
src/buildings/bindings/modulegen__gcc_LP64.py
Python
gpl-2.0
309,810
0.015
from pybindgen import Module, FileCodeSink, param, retval, cppclass, typehandlers import pybindgen.settings import warnings class ErrorHandler(pybindgen.settings.ErrorHandler): def handle_error(self, wrapper, exception, traceback_): warnings.warn("exception %r in wrapper %s" % (exception, wrapper)) ...
odule 'core'): ns3::TypeId::AttributeFla
g [enumeration] module.add_enum('AttributeFlag', ['ATTR_GET', 'ATTR_SET', 'ATTR_CONSTRUCT', 'ATTR_SGC'], outer_class=root_module['ns3::TypeId'], import_from_module='ns.core') ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation [struct] module.add_class('AttributeInformation', import_from_module=...
biomodels/MODEL1310110036
MODEL1310110036/model.py
Python
cc0-1.0
427
0.009368
import os path = o
s.path.dirname(os.path.realpath(__file__)) sbmlFilePath = os.path.join(path, 'MODEL1310110036.xml') with open(sbmlFilePath,'r') as f: sbmlString = f.read() def module_exists(module_name): try: __import__(module_name) except ImportError:
return False else: return True if module_exists('libsbml'): import libsbml sbml = libsbml.readSBMLFromString(sbmlString)
lncwwn/js-partner
js_partner/views.py
Python
mit
1,205
0.00249
from django.shortcuts import render_to_response from django.template import RequestContext from django.http import HttpResponseRedirect from django.contrib.auth.models import User def index(request): return render_to_response('index.html', None) def run(request): pass def save(request): pass # user s...
= 'POST': name = request.POST['name'] password = request.PO
ST['password'] password_confirm = request.POST['password_confirm'] email = request.POST['email'] if password == password_confirm: user = User.objects.create_user(name, password, email) user.save() return HttpResponseRedirect('/') return render_to_respons...
evandrix/Splat
code/demo/pyutilib.math-3.3/setup.py
Python
mit
1,569
0.013384
# _________________________________________________________________________ # # PyUtilib: A Python utility library. # Copyright (c) 2008 Sandia Corporation. # This software is distributed under the BSD License. # Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, # the U.S. Government retains ...
open(os.path.join(os.path.dirname(__file__), *rnames)).read() setup(name="pyutilib.math", version='3.3', maintainer='William E. Hart', maintainer_email='wehart@sandia.gov', url = 'https://software.sandia.gov/svn/public/pyutilib/pyutilib.math', license = 'BSD', platforms = ["any"], de
scription = 'PyUtilib math utilities.', long_description = read('README.txt'), classifiers = [ 'Development Status :: 4 - Beta', 'Intended Audience :: End Users/Desktop', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', 'Operating System :: Microso...
GuillaumeDerval/INGInious
tests/tasks/edx/HelloWorld/insert_input.py
Python
agpl-3.0
891
0.015713
# -*- coding: utf8 -*- # Author: Adrien Bibal # Date: 2014 # Insert the student answer in the correction framework file. import sys import codecs input_file = sys.stdin # input = file containing the student answer. oz_file = codecs.open("/task/task.oz", "r", "utf8") # Open the "correction framework file". new_file =...
pen("new_file.oz", "w","utf8") # Open the fina
l file. for line in oz_file: # "@@q1@@" is the arbitrary marker used to say "insert the student answer here". if "@@q1@@" in line : for input_line in input_file : if '\0' in input_line : input_line = input_line.strip('\0') new_file.write(input_line) # Copy each l...
daxm/fmcapi
unit_tests/port_object_group.py
Python
bsd-3-clause
1,589
0
import logging import fmcapi import time def test__port_object_group(fmc): logging.info("Testing PortObjectGroup class.") starttime = str(int(time.time())) namer = f"_fmcapi_test_{starttime}" obj10 = fmcapi.ProtocolPortObjects( fmc=fmc, name="_porttcp1", port="8443", protocol="TCP" ) ...
s(action="remove", name=obj10.name) obj1.named_ports(action="clear") obj1.named_ports(action="add", name=obj11.name) obj1.named_ports(action="add", name=obj12.name) obj1.named_ports(action="remove", name=obj11.name) obj1.post() time.sleep(1) del obj1 obj1 = fmcapi.PortObjectGroups(fmc=f...
c, name=namer) obj1.get() obj1.named_ports(action="add", name="HTTP") obj1.named_ports(action="clear") obj1.named_ports(action="add", name="HTTP") obj1.named_ports(action="remove", name="HTTP") obj1.named_ports(action="add", name="HTTP") obj1.named_ports(action="add", name="HTTPS") obj1....
priestc/MultiExplorer
multiexplorer/pricetick/migrations/0001_initial.py
Python
mit
872
0.001147
# -*- coding: utf-8 -*- # Generated by Django 1.10.4 on 2017-02-26 03:49 from __future__ import unicode_literals from django.db import migrations, models
class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='PriceTick', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ...
', models.CharField(max_length=8)), ('date', models.DateTimeField(db_index=True)), ('price', models.FloatField()), ], options={ 'get_latest_by': 'date', }, ), ]
davidsminor/gaffer
python/GafferImageTest/ImagePlugTest.py
Python
bsd-3-clause
5,013
0.055057
########################################################################## # # Copyright (c) 2012, John Haddon. All rights reserved. # Copyright (c) 2013, Image Engine Design Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided t...
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR # CONTRIBUTORS 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 LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY ...
OctavianLee/Barrage
tests/cores/test_danmaku_process.py
Python
mit
4,281
0.001407
# -*- coding: utf-8 -*- from unittest import TestCase from nose.tools import eq_ from mock import Mock from datetime import datetime from tests.constants import STRING, NUMBER, DATE from tests.asserters import eq_obj from danmaku.cores.danmaku_process import generate_danmaku from danmaku.cores.danmaku_process import ...
pe=danmaku_type, is_admin=is_admin, is_vip=is_vip ) test_danmaku = generate_danmaku(msg) eq_obj(expect_danmaku, test_danmaku) msg = { u'roomid': NUMBER, u'cmd': u'WELCOME', u'data': { u'uname': u'xxxxxr', u'isadmin': 0,
u'uid': NUMBER } } danmaku_type = WELCOME publisher = msg['data']['uname'].encode('utf-8') is_vip = True content = None is_admin = msg['data']['isadmin'] == 1 expect_danmaku = DanmakuModel( publisher=publisher, content=content, recieved_t...
jkyeung/XlsxWriter
xlsxwriter/test/comparison/test_hyperlink15.py
Python
bsd-2-clause
1,235
0.00081
############################################################################### # # Tests for XlsxWriter. # # Copyright (c), 2013-2016, John McNamara, jmcnamara@cpan.org # from ..excel_comparsion_test import ExcelComparisonTest from ...workbook import Workbook class TestCompareXLSXFiles(ExcelComparisonTest): """...
yperlinks.This example doesn't have any link formatting and tests the relationshiplinkage code.""" workbook = W
orkbook(self.got_filename) # Turn off default URL format for testing. workbook.default_url_format = None worksheet = workbook.add_worksheet() worksheet.write_url('B2', 'external:subdir/blank.xlsx') workbook.close() self.assertExcelEqual()
alveyworld-dev/calculator
team6.py
Python
apache-2.0
738
0.020325
def add(a, b): """ This function adds two numbers """ return a + b def sub(a,b): """ This function subtracts two numbers """ return a - b # print "The first number you want to subtract?" # a = int(raw_input("First no: ")) # print "What's the second
number you want to subtract" # b = int(raw_input("Second no: ")) # """ # This function subtracts two numbers # """ # result = sub(a,b) # """ # this prints the results # """ # print "The result is: %r." % result def opp(a): return a * -1 # print "Number you want to change" # a = int(raw_input("Number to change: ")...
kamcpp/tensorflow
tensorflow/python/lib/io/file_io.py
Python
apache-2.0
13,774
0.006607
# Copyright 2015 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...
self._preread_check() with errors.raise_exception_on_not_ok_status() as status: ret_status = self._read_buf.Seek(position) pywrap_tensorflow.Set_TF_Status_from_Status(status, ret_status) def readline(self): r"""Reads the next line from the
file. Leaves the '\n' at the end.""" self._preread_check() return compat.as_str_any(self._read_buf.ReadLineAsString()) def readlines(self): """Returns all lines from the file in a list.""" self._preread_check() lines = [] while True: s = self.readline() if not s: break ...
caterinaurban/Lyra
src/lyra/unittests/numerical/interval/backward/summarization/subscriptions1b.py
Python
mpl-2.0
350
0.005714
x: int = int(input()) # STATE
: L -> [-inf, inf]; len(L) -> [0, inf]; x -> [-inf, inf]; z -> [-inf, inf] L: List[List[int]] = [[0], [1], [x]] # STATE: L -> [-inf, inf]; len(L) -> [3, inf]; x -> [-inf, inf]; z -> [-inf, inf] z: int = L[2][0] # STATE: L -> [-inf, inf]; len(L) -> [0, inf]; x -> [
-inf, inf]; z -> [2, 2] if z != 2: raise ValueError
ProfessorX/Config
.PyCharm30/system/python_stubs/-1247972723/_codecs_tw.py
Python
gpl-2.0
377
0.013263
# encoding: utf-8 # module _codecs_tw # from /usr/lib/python2.7/
lib-dynload/_codecs_tw.x86_64-linux-gnu.so # by generator 1.135 # no doc # no imports # functions def getcodec(*args, **kwargs): # real signature unknown """ """ pass # no classes # variables with complex values __map_big5 = None # (!) real value is '' __map_cp950ext = None # (!) real value i
s ''
mbikyaw/wordpress-mbinfo
utils.py
Python
mit
1,016
0
__author__ = 'mbikyaw' class AttributeDict(dict): """ Dictionary subclass enabling attribute lookup/assignment of keys/values. For example:: >>> m = AttributeDict({'foo': 'bar'}) >>> m.foo 'bar' >>> m.foo = 'not bar' >>> m['foo'] 'not bar' ``Attribute...
wrong', 'incorrect', 'foo', 'biz') 'bar' """ def __getattr__(self, key): try: return self[key] except KeyError: # to conform with __getattr__ spec raise AttributeError(key) def __setattr__(self, key, value): self[key] = value def fir...
if value: return value
soslan/passgen
setup.py
Python
mit
1,122
0
#!/usr/bin/env python try: from setuptools import setup except ImportError: from distutils.core i
mport setup with open('README.rst') as file: long_description = file.read() setup(name='passgen', version='1.1.1', description='Random password generator', long_description=long_description, url='https://github.com/soslan/passgen', author='Soslan Khubulov', author_email='soslan...
@gmail.com', license='MIT', package_dir={'': 'src'}, entry_points={ 'console_scripts': [ 'passgen = passgen:main', ], }, py_modules=['passgen'], classifiers=[ 'Development Status :: 5 - Production/Stable', 'Programming Language ::...
Azure/azure-sdk-for-python
sdk/operationsmanagement/azure-mgmt-operationsmanagement/azure/mgmt/operationsmanagement/aio/_configuration.py
Python
mit
4,167
0.00336
# 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 ...
onsManagementClientConfiguration(Configuration): """Configuration for OperationsManagementClient. Note that all parameters used to create this instance are saved as instance attributes. :param credential: Credential needed for the client to connect to Azure. :type credential: ~azure.co
re.credentials_async.AsyncTokenCredential :param subscription_id: Gets subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. :type subscription_id: str :param provider_name: Provider name for the parent resource. ...
dalembertian/fabmanager
fabmanager/decorators.py
Python
bsd-3-clause
3,353
0.006263
# encoding: utf-8 # Useful decorators from functools import wraps from fabric.api import * # These variables must be defined in the actual fabfile.py for the proxy decorators: # env.proxy_server = 'proxy.com.br' Address of the proxy server intermediating the executation # env.proxy_home = '/home/me/fabric' Lo...
ncluded # env.proxy_role = 'somerole' in the fab command executed at the proxy server def _is_running_on_proxy(): """ Returns True if this fabfile is being run on the proxy server. """ return env.real_fabfile.find(env.proxy_home) < 0 def _run_on_proxy(role=None, host=None): """ Dec...
@hosts(env.proxy_server) @_run_on_proxy([host='somehost'|role='somerole']) def mytask(): Each task must be surrounded by a @hosts decorator specifying the proxy server, so the task will be initially run at the proxy. Then the @_run_on_proxy decorator can be used with or without specify...
hep-gc/glint-service
glint-service/glint_git_setup.py
Python
apache-2.0
12,100
0.025289
#!/usr/bin/python glint_lib_directory='/var/lib/glint' horizon_git_repo='https://github.com/rd37/horizon.git' glint_git_repo='https://github.com/hep-gc/glint.git' glint_inst_type='default' horizon_inst_type='default' glint_server='django' glint_horizon_server='django' cfg_dir = '/etc/glint' pkg_dir = 'glint-service' ...
te_command(['cp','%s/gl
int-horizon'%pkg_dir,'/usr/bin/.'],None) [out,err] = execute_command(['chmod','755','/usr/bin/glint-horizon'],None) print "Setup /etc/init.d/glint-horizon as a service" [out,err] = execute_command(['cp','%s/openstack-glint-horizon'%pkg_dir,'/etc/init.d/.'],None) [out,err] = execute_comma...
johnwheeler/flask-ask
tests/test_audio.py
Python
apache-2.0
2,585
0.003095
import unittest from mock import patch, MagicMock from flask import Flask from flask_ask import Ask, audio from flask_ask.models import _Field class AudioUnitTests(unittest.TestCase): def setUp(self): self.ask_patcher = patch('flask_ask.core.find_ask', return_value=Ask()) self.ask_patcher.start()...
(audio_item['stream']['token'])) self.assertEqual(123, audio_item['stream']['offsetInMilliseconds']) def test_custom_token(self): """ Check to see t
hat the provided opaque token remains constant""" token = "hello_world" audio_item = audio()._audio_item(stream_url='https://fakestream', offset=10, opaque_token=token) self.assertEqual(token, audio_item['stream']['token']) self.assertEqual(10, audio_item['stream']['offsetInMilliseconds'...
georgidimov/cannon-wars
tests/test_position.py
Python
gpl-2.0
1,788
0
import unittest from src.position import Position class TestPosition(unittest.TestCase): def test_getters(self): position = Position(1, 2) x = position.get_horizontal_position() y = position.get_vertical_position() self.assertEqual(x, 1) se
lf.assertEqual(y, 2) def test_setters(self): position = Position() position.set_horizontal_position(21) position.set_vertical_position(42) x = position.get_horizontal_position() y = position.get_ve
rtical_position() self.assertEqual(x, 21) self.assertEqual(y, 42) def test_defualt_values(self): position = Position() x = position.get_horizontal_position() y = position.get_vertical_position() self.assertEqual(x, 0) self.assertEqual(y, 0) def test_to...
timpalpant/calibre
src/calibre/ebooks/pdf/render/from_html.py
Python
gpl-3.0
16,407
0.004815
#!/usr/bin/env python2 # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:fdm=marker:ai from __future__ import (unicode_literals, division, absolute_import, print_function) __license__ = 'GPL v3' __copyright__ = '2012, Kovid Goyal <kovid at kovidgoyal.net>' __docformat__ = 'restructuredtext en' ...
port QWebSettings from PyQt5.QtWebKitWidgets import QWebView, QWebPage from calibre import fit_image from calibre.constants import iswindows from calibre.ebooks.oeb.display.webview import load_html from calibre.ebooks.pdf.re
nder.common import (inch, cm, mm, pica, cicero, didot, PAPER_SIZES) from calibre.ebooks.pdf.render.engine import PdfDevice from calibre.ptempfile import PersistentTemporaryFile def get_page_size(opts, for_comic=False): # {{{ use_profile = not (opts.override_profile_si...
rohitranjan1991/home-assistant
homeassistant/components/freebox/const.py
Python
mit
2,269
0.000881
"""Freebox component constants.""" from __future__ import annotations import socket from homeassistant.components.sensor import SensorEntityDescription from homeassistant.const import DATA_RATE_KILOBYTES_PER_SECOND, PERCENTAGE, Platform DOMAIN = "freebox" SERVICE_REBOOT = "reboot" APP_DESC = { "app_id": "has
s", "app_name": "Home Assistant", "app_version": "0.106", "device_name": s
ocket.gethostname(), } API_VERSION = "v6" PLATFORMS = [Platform.BUTTON, Platform.DEVICE_TRACKER, Platform.SENSOR, Platform.SWITCH] DEFAULT_DEVICE_NAME = "Unknown device" # to store the cookie STORAGE_KEY = DOMAIN STORAGE_VERSION = 1 CONNECTION_SENSORS: tuple[SensorEntityDescription, ...] = ( SensorEntityDescri...
UCSUR-Pitt/wprdc-etl
test/unit/test_schema.py
Python
mit
1,363
0.001467
from operator import itemgetter from unittest import TestCase import pipeline as pl from marshmallow import fields class FakeSchema(pl.BaseSchema): str = fields.String() int = fields.Integer() num = fields.Number() datetime = fields.D
ateTime() date = fields.Date(dump_to='a_different_name') not_there = fields.String(load_only=True) class TestSchema(TestCase): def test_ckan_serialization(self): fields = FakeSchema().serialize_to_ckan_fields() self.assertListEqual( sorted(fields, key=itemgetter('id')), ...
{'id': 'datetime', 'type': 'timestamp'}, {'id': 'int', 'type': 'numeric'}, {'id': 'num', 'type': 'numeric'}, {'id': 'str', 'type': 'text'} ] ) def test_ckan_serialization_caps(self): fields = FakeSchema().serialize_to_ckan_fields(capi...
philipp-sumo/kitsune
kitsune/wiki/forms.py
Python
bsd-3-clause
12,054
0.000083
import re from django import forms from django.conf import settings from django.template.defaultfilters import slugify from tower import ugettext_lazy as _lazy from kitsune.products.models import Product, Topic from kitsune.sumo.form_fields import MultiUsernameField, StrippedCharField from kitsune.wiki.config import...
e?'), initial=True, requir
ed=False) category = forms.ChoiceField( choices=CATEGORIES, # Required for non-translations, which is # enforced in Document.clean(). required=False, label=_lazy(u'Category:'), help_text=_lazy(u'Type of article')) topics = forms.MultipleChoiceField( labe...
jose36/plugin.video.live.ProyectoLuzDigital-
servers/servertools.py
Python
gpl-2.0
17,227
0.029961
# -*- coding: utf-8 -*- #------------------------------------------------------------ # pelisalacarta - XBMC Plugin # Utilidades para detectar vídeos de los diferentes conectores # http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/ #------------------------------------------------------------ #LvX Edited Patched i...
ers."+serverid) server_module = getattr(servers_module,serverid) devuelve.extend( server_module.find_videos(data) ) except ImportError:
logger.info("No existe conector para "+serverid) except: logger.info("Error en el conector "+serverid) import traceback,sys from pprint import pprint exc_type, exc_value, exc_tb = sys.exc_info() lines = traceback.format_exception(exc_type, exc_value, e...
HMSBeagle1831/rapidscience
rlp/newsfeed/urls.py
Python
mit
133
0
from django.conf.urls import
url from . import views urlpatterns = [ url(r'^$', views.newsitem_list, name=
'newsitem_list'), ]
blueboxgroup/keystone
keystone/controllers.py
Python
apache-2.0
6,964
0
# Copyright 2012 OpenStack Foundation # # Lice
nsed 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 Lic...
"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 oslo.serialization import jsonutils import webob from keystone.common import extension from keystone.common import json_...
krayush07/deep-attention-text-classifier-tf
global_module/run_module/run_test.py
Python
bsd-3-clause
1,283
0
from __future__ import absolute_import from __future__ import division from __future__ import print_function from global_module.settings_module import set_dict import global_module.implementation_module.test as test_model from global_module.utility_code import convert_pred_to_class as convert #######################...
, mtest, dict_obj): test_model.run_test(session, mtest, d
ict_obj) def test_util(): """ Utility function to execute the testing pipeline :return: """ dict_obj = load_dictionary() return dict_obj def main(): """ Starting module for testing :return: """ print('STARTING TESTING') session, mtest, dict_obj = initialize_test_sessi...
dbarbier/ot-svn
python/doc/sphinxext/numpydoc/linkcode.py
Python
gpl-3.0
2,510
0.001992
# -*- coding: utf-8 -*- """ linkcode ~~~~~~~~ Add external links to module code in Python object descriptions. :copyright: Copyright 2007-2011 by the Sphinx team, see AUTHORS. :license: BSD, see LICENSE for details. """ from __future__ import division, absolute_import, print_function import warn...
value = signode.get(key) if not value: value = '' info[key] = value if not info: continue # Call user cod
e to resolve the link uri = resolve_target(domain, info) if not uri: # no source continue if uri in uris or not uri: # only one link per name, please continue uris.add(uri) onlynode = addnodes.o...
CospanDesign/nysa-dionysus-platform
dionysus/misc.py
Python
gpl-2.0
8,094
0.001112
# Copyright (c) 2008-2012, Neotion # 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 an...
chieved: take the closest, smaller value or fallback to the next unit that allows the exact representation of the input value """ size = int(size) if size > lim_m: ssize = size >> 20 if floor or (ssize << 20) == size: ...
if size > lim_k: ssize = size >> 10 if floor or (ssize << 10) == size: return '%d%sKiB' % (ssize, sep) return '%d%sbyte%s' % (size, sep, (plural and 's' or ''))
pkimber/enquiry
enquiry/migrations/0001_initial.py
Python
apache-2.0
1,028
0.000973
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Enquiry', fields=[ ('id', models.AutoField(auto...
ey=True, verbose_name='ID')), ('created', models.DateTimeField(auto_now_add=True)), ('modified', models.DateTimeField(auto_now=True)), ('name', models.CharField(max_le
ngth=100)), ('description', models.TextField()), ('email', models.EmailField(blank=True, max_length=75)), ('phone', models.CharField(blank=True, max_length=100)), ], options={ 'ordering': ['-created'], 'verbose_name_...
rafaelwerneck/kuaa
classifiers/libSVM_3_17/grid.py
Python
gpl-3.0
15,616
0.045402
#!/usr/bin/env python __all__ = ['find_parameters'] import os, sys, traceback, getpass, time, re from threading import Thread from subprocess import * import multiprocessing #Werneck import platform #------- if sys.version_info[0] < 3: from Queue import Queue else: from queue import Queue telnet_workers = [] ssh_w...
ce\n") gnuplot.write(b"unset ztics\n") gnuplot.write(b"set view 0,0\n") gnuplot.write("set title \"{0}\"\n"
.format(options.dataset_title).encode()) gnuplot.write(b"unset label\n") gnuplot.write("set label \"Best log2(C) = {0} log2(gamma) = {1} accuracy = {2}%\" \ at screen 0.5,0.85 center\n". \ format(best_log2c, best_log2g, best_rate).encode()) gnuplot.write("set label \"C = {0} gamma = {1}\"" " at ...
lafranceinsoumise/api-django
agir/mailing/migrations/0007_segment_events_organizer.py
Python
agpl-3.0
552
0.001818
# Generated by Django 2.2.5 on 2019-10-02 16:31 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [("maili
ng", "0006_auto_20191002_1752")] operations = [ migrations.AddField( model_name="segment", name="events_organizer", field=models.BooleanField( blank=True, default=False, verbose_name="Limiter aux organisateurices (sans effe...
]