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
pkoutsias/SickRage
sickbeard/rssfeeds.py
Python
gpl-3.0
982
0.002037
# coding=utf-8 import re import urlparse from feedparser.api import parse from feedparser.util import FeedParserDict from sickbeard import logger from sickrage.helper.exceptions import ex def getFeed(url, request_headers=None, handlers=None): parsed = list(urlparse.urlparse(url)) parsed[2] = re.sub("/{2,}", ...
elif 'error' in feed.feed: err_code = feed.feed['err
or']['code'] err_desc = feed.feed['error']['description'] logger.log(u'RSS ERROR:[%s] CODE:[%s]' % (err_desc, err_code), logger.DEBUG) else: logger.log(u'RSS error loading url: ' + url, logger.DEBUG) except Exception as e: logger.log(u'RSS error: ' + ex(e...
smirolo/djaodjin-signup
signup/urls/accounts.py
Python
bsd-2-clause
2,655
0.003766
# Copyright (c) 2015, Djaodjin Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and t...
2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMP...
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, STR...
honeybadger-io/honeybadger-python
examples/flask-blueprint/app.py
Python
mit
454
0
import logging from flask import Flask from honeybadger.contrib import FlaskHoneybadger from blueprint import simple_page logger = logging.getLogger(__name__) app = Flask(__name__) app.config['HONEYBADGER_ENVIRONMENT'] = 'honeybadger-example' app.config['HONEYBADGER_API_KEY'] = '<your key>' app.config['HONEYBADGER_...
RAMS_FILTERS'] = 'password, secret, credit-card' FlaskHoneybadger(app, report_exceptions=True) app.regist
er_blueprint(simple_page)
batpad/osmcha-django
osmchadjango/changeset/migrations/0022_auto_20160222_2358.py
Python
gpl-3.0
428
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('changeset', '0021_auto_201
60222_2345'), ] operations = [ migrations.AlterField( model_name='suspicionreasons', na
me='name', field=models.CharField(max_length=255, db_index=True), ), ]
lthurlow/Network-Grapher
proj/external/matplotlib-1.2.1/lib/mpl_toolkits/axisartist/axisline_style.py
Python
mit
5,156
0.001746
from matplotlib.patches import _Style, FancyArrowPatch from matplotlib.transforms import IdentityTransform from matplotlib.path import Path import numpy as np class _FancyAxislineStyle: class SimpleArrow(FancyArrowPatch): """ The artist class that will be returned for SimpleArrow style. """...
e call signature is :: __call__(self, axis_artist, path, transform) When called, this should return a mpl artist with following methods implemented. :: def set_path(self, path): # set the path for axisline. de
f set_line_mutation_scale(self, scale): # set the scale def draw(self, renderer): # draw """ _style_list = {} class _Base(object): # The derived classes are required to be able to be initialized # w/o arguments, i.e., all its argument (except self) must have ...
abhijo89/Django-facebook
django_facebook/management/commands/extend_tokens.py
Python
bsd-3-clause
620
0
from django_facebook.management.commands.base import CustomBaseCommand from django_facebook.utils import queryset_iterator from optparse import make_option import datetime class ExtendTokensCommand(Custo
mBaseCommand): he
lp = 'Extend all the users access tokens\'s, per hour' option_list = CustomBaseCommand.option_list + ( make_option('--all', action='store_true', dest='all', default=False, help='Extend all of them at once' ),...
xingjian-f/Leetcode-solution
357. Count Numbers with Unique Digits.py
Python
mit
482
0.029046
class Solution(o
bject): def intersect(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: List[int] """ from collections import Counter nums2 = Counter(nums2) nums1 = Counter(nums1) ret = [] for i in nums1: cnt = min...
t([1,2,3,2], [2,2])
illume/numpy3k
numpy/doc/broadcasting.py
Python
bsd-3-clause
5,413
0.000185
""" ======================== Broadcasting over arrays ======================== The term broadcasting describes how numpy treats arrays with different shapes during arithmetic operations. Subject to certain constraints, the smaller array is "broadcast" across the larger array so that they have compatible shapes. Broadc...
It starts with the trailing dimensions, and works its way forward. Two dimensions are compatible when 1) they are equal, or 2) one of them is 1 If these conditions are not met, a ``Value
Error: frames are not aligned`` exception is thrown, indicating that the arrays have incompatible shapes. The size of the resulting array is the maximum size along each dimension of the input arrays. Arrays do not need to have the same *number* of dimensions. For example, if you have a ``256x256x3`` array of RGB valu...
txomon/pytest
testing/test_session.py
Python
mit
10,953
0.000365
from __future__ import absolute_import from __future__ import division from __future__ import print_function import pytest from _pytest.main import EXIT_NOTESTSCOLLECTED class SessionTests(object): def test_basic_testitem_events(self, testdir): tfile = testdir.makepyfile( """ def ...
t = BrokenRepr1() pytest.raises(Exception, 'repr(t)') def test_implicit_bad_repr1(self): t = BrokenRepr1() assert t.foo == 1 """ ) reprec = testdir.inline_run(p) passed, skipped, failed = reprec.listoutcomes() ...
led[0].longrepr.reprcrash.message assert ( out.find( """[Exception("Ha Ha fooled you, I'm a broken repr().") raised in repr()]""" ) != -1 ) # ' def test_skip_file_by_conftest(self, testdir): testdir.makepyfile( conftest=""" ...
Altarika/feet
feet/commands/extract.py
Python
lgpl-2.1
2,821
0
# -*- coding: utf8 -*- # Extract entities from text # # Author: Romary Dupuis <romary.dupuis@altarika.com> # # Copyright (C) 2016 Romary Dupuis # Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html from commis import Comm
and from commis i
mport color from feet.entities.extractor import Extractor from feet.entities.registry import Registry class ExtractCommand(Command): name = 'extract' help = 'extract a list of entities from text' args = { '--text': { 'metavar': 'TEXT', 'required': False, 'help...
jrichte43/ProjectEuler
Problem-0171/solutions.py
Python
gpl-3.0
917
0.007634
__problem_title__ = "Finding numbers for which the sum of the squares of the digits is a square" __problem_url___ = "https://projecteuler.net/problem=171" __problem_description__ = "For a positive integer , let f( ) be the sum of the squares of the " \ "digits (in base 10) of , e.g. f(3) = 3 ...
such that f( ) is a perfect square." import timeit class Solution(): @staticmethod def solution1(): pass @staticmethod def time_solutions(): setup = 'from __m
ain__ import Solution' print('Solution 1:', timeit.timeit('Solution.solution1()', setup=setup, number=1)) if __name__ == '__main__': s = Solution() print(s.solution1()) s.time_solutions()
onecloud/neutron
neutron/plugins/plumgrid/drivers/fake_plumlib.py
Python
apache-2.0
2,992
0
# Copyright 2013 PLUMgrid, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by ...
def delete_router(self, tenant_id, router_id): pass def add_router_interface(self, te
nant_id, router_id, port_db, ipnet): pass def remove_router_interface(self, tenant_id, net_id, router_id): pass def create_floatingip(self, floating_ip): pass def update_floatingip(self, floating_ip_orig, floating_ip, id): pass def delete_floatingip(self, floating_ip_...
alexston/calibre-webserver
src/tinycss/page3.py
Python
gpl-3.0
5,107
0.000783
# coding: utf8 """ tinycss.page3 ------------------ Support for CSS 3 Paged Media syntax: http://dev.w3.org/csswg/css3-page/ Adds support for named page selectors and margin rules. :copyright: (c) 2012 by Simon Sapin. :license: BSD, see LICENSE for more details. """ from __future__ impor...
s', 'line', 'column' def __init__(self, at_keyword, declarations, line, column): self.at_keyword = at_keyword self.declarat
ions = declarations self.line = line self.column = column class CSSPage3Parser(CSS21Parser): """Extend :class:`~.css21.CSS21Parser` for `CSS 3 Paged Media`_ syntax. .. _CSS 3 Paged Media: http://dev.w3.org/csswg/css3-page/ Compared to CSS 2.1, the ``at_rules`` and ``selector`` attributes...
scyv/testing-iot
streetlight/main.py
Python
mit
3,281
0.003048
# streetlight # Example for the code of an IoT device that is still in development but must be tested. # This is the SUT - System Under Test import RPi.GPIO as GPIO import paho.mqtt.client as mqtt import json ## CONSTANTS ################################################################## MQTT_HOST = "<MQTT_HOST>" ST...
_event_detect(CHANNEL_IN_LIGHT_SENSOR, GPIO.BOTH, callback=
on_light_sensor_event, bouncetime=200) mqtt_client.connect(MQTT_HOST, 1883, 60) try: # Process network traffic and dispatch callbacks. mqtt_client.loop_forever() except KeyboardInterrupt: pass GPIO.cleanup()
edx/edx-analytics-pipeline
edx/analytics/tasks/tests/acceptance/test_module_engagement.py
Python
agpl-3.0
17,667
0.003906
# pylint: disable=line-too-long """ End to end test of the per-module engagement workflow. """ import datetime import logging import ddt from edx.analytics.tasks.tests.acceptance import AcceptanceTestCase, when_elasticsearch_available log = logging.getLogger(__name__) @ddt.ddt class ModuleEngagementAcceptanceTest...
start_date, end_date, metric, range_type, low_value
, high_value FROM module_engagement_metric_ranges') results = cursor.fetchall() self.assertItemsEqual( [row for row in results], [ ('edX/DemoX/Demo_Course', datetime.date(2015, 4, 10), datetime.date(2015, 4, 17), 'discussion_contributions', 'low', 0, 6.0), ...
Cue/eventlet
tests/stdlib/test_ftplib.py
Python
mit
451
0.002217
from eventlet import patc
her from eventlet.green import asyncore from eventlet.green import ftplib from eventlet.green import threading from eventlet.green import socket patcher.inject('test.test_ftplib', globals()) # this test only fails on python2.7/pyevent/--with-xunit; screw that try: TestTLS_FTPClass.test_data_connection = lambda *a...
__ == "__main__": test_main()
aawadall/PyProjMan
UnitTesting/test_task_exceptions.py
Python
mit
1,048
0.001908
from unittest import TestCase from PyProjManCore.task import Task class TestTaskOperationsExceptions(TestCase): """Test Exceptions for Task operations""" def test_append_duplicate_prereq(self): """Test appending duplicate prerequisites to a task, it should be unique""" root = Task("Root Task"...
dependency, i.e. a Task depends on itself, or a task has both prerequisite and child the same
""" self.fail("Not implemented ") def test_append_duplicate_dep(self): """Test appending duplicate dependants to a task, it should be unique""" root = Task("Root Task") child = Task("Child Task") root.append_dependant(child) root.append_dependant(child) s...
open-synergy/opnsynid-l10n-indonesia
l10n_id_partner_identification_bpjs/__openerp__.py
Python
agpl-3.0
635
0
# -*- coding: utf-8 -*- # Copyright 2018 OpenSynergy Indonesia # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Partner Identification - BPJS", "version": "8.0.1.0.0", "author": "OpenSynergy Indonesia", "website": "https://opensynergy-indonesia.com", "
license": "AG
PL-3", "depends": [ "partner_identification", ], "external_dependencies": { "python": [ "openupgradelib", ], }, "data": [ "data/res_partner_id_category_data.xml", ], "installable": True, "pre_init_hook": "_load_partner_identification_data",...
JudTown17/solutions-geoprocessing-toolbox
data_management/test/test_geonames_tools/TestUtilities.py
Python
apache-2.0
1,403
0.006415
#------------------------------------------------------------------------------ # Copyright 2013 Esri # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENS...
ributed under th
e License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. #------------------------------------------------------------------------------ # Name: TestUtil...
NeuralEnsemble/neurotune
examples/example_1/data_analysis.py
Python
bsd-3-clause
489
0
from pyelectro import
analysis as pye_analysis from matplotlib import pyplot file_name = "100pA_1a.csv" t, v = pye_analysis.load_csv_data(file_name) analysis_var = { "peak_delta": 0.1, "baseline": 0, "dvdt_threshold": 2, "peak_threshold": 0, } analysis = pye_analysis.IClampAnalysis( v, t, analysis_var, start_analysis...
pyplot.show()
18F/sauceclient
setup.py
Python
apache-2.0
1,651
0.000606
#!/usr/bin/env python # # Copyright (c) 2013 Corey Goldberg # # This file is part of: sauceclient # https://github.com/cgoldberg/sauceclient # # 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 L...
port os from distutils.core import setup this_dir = os.path.abspath(os.path.dirname(__file__)) with open(os.path.join(this_dir, 'README.rst')) as f: LONG_DESCRIPTION = '\n' + f.read() from sauceclient import __version__ setup( name='sauceclient', version=__version__, py_modules=['sauceclient'], ...
cription='Python client library for Sauce Labs API.', long_description=LONG_DESCRIPTION, url='http://cgoldberg.github.com/sauceclient/', download_url='http://pypi.python.org/pypi/sauceclient', keywords='saucelabs selenium testing'.split(), license='Apache v2.0', classifiers=[ 'Developmen...
enikesha/ga-bitbot
libs/call_metrics.py
Python
gpl-3.0
2,700
0.008148
""" call_metrics v0.01 a class function decorator which collects metrics (number of calls and total execution time) Copyright 2012 Brian Monkaba This file is part of ga-bitbot. ga-bitbot is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as publishe...
self._metrics[func.__name__]['calls'] += 1 return result return _decorator #decorator which can be used on funcitons #uses the global _metrics dictionary def call_metrics(func): @wraps(func) def _decorator(*args, **kwargs):
start = time.time() result = func(*args, **kwargs) finish = time.time() if not _metrics.has_key(func.__name__): _metrics.update({func.__name__:{'total_time':0,'calls':0}}) _metrics[func.__name__]['total_time'] += finish - start _metrics[func.__name__]['calls'] += 1 ...
andreas-p/admin4
modPg/_pgsql.py
Python
apache-2.0
17,772
0.029147
# The Admin4 Project # (c) 2013-2014 Andreas Pflug # # Licensed under the Apache License, # see LICENSE.TXT for conditions of usage # http://initd.org/psycopg/docs/ import psycopg2 import select import logger import adm import re import threading from wh import xlt, modPath from Crypto.PublicKey._slowmath import rsa...
) else: row=None if row: self.curRow = pgRow(self.cursor, row, self.colNames) else: self.curRow=None def HasMore(self): return self.curRow != None def Next(self): row=self.curRow if row: self.__fetchone() return row
def getDict(self): d={} for row in self: d[row[0]] = row.getDict() return d def getDictList(self): d=[] for row in self: d.append(row.getDict()) return d def getList(self): d=[] for row in self: d.append(row[0]) return d def __iter__(self): class Rowset...
jamespcole/home-assistant
homeassistant/components/rflink/light.py
Python
apache-2.0
10,785
0
""" Support for Rflink lights. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/light.rflink/ """ import logging import voluptuous as vol from homeassistant.components.light import ( ATTR_BRIGHTNESS, PLATFORM_SCHEMA, SUPPORT_BRIGHTNESS, Light) from h...
DEVICE_DEFAULTS_SCHEMA, vol.Optional(CONF_AUTOMATIC_ADD, default=True): cv.boolean, vol.Optional(CONF_DEVICES, default={}): { cv.string: vol.Schema({ vol.Optional(CONF_NAME): cv.string, vol.Optional(CONF_TYPE): vol.Any(TYPE_DIMMABLE, TYPE_SWITCHABLE, ...
ES, default=[]): vol.All(cv.ensure_list, [cv.string]), vol.Optional(CONF_GROUP_ALIASES, default=[]): vol.All(cv.ensure_list, [cv.string]), vol.Optional(CONF_NOGROUP_ALIASES, default=[]): vol.All(cv.ensure_list, [cv.string]), vol.Optiona...
caot/intellij-community
python/testData/refactoring/extractsuperclass/moveAndMakeAbstractImportExistsPy3/source_module.py
Python
apache-2.0
80
0.0125
clas
s MyClass(): @classmethod def foo_met
hod(cls): spam = "eggs"
Valeureux/wezer-exchange
__unreviewed__/community_project/__init__.py
Python
agpl-3.0
963
0
# -*- coding: utf-8 -*- ############################################################################## # # Author: Yannick Buron and Va
leureux Copyright Valeureux.org # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This progra...
# GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## import community_project
Flexget/Flexget
flexget/plugins/clients/qbittorrent.py
Python
mit
12,568
0.001512
import os from loguru import logger from requests import Session from requests.exceptions import RequestException from flexget import plugin from flexget.event import event from flexget.utils.template import RenderError logger = logger.bind(name='qbittorrent') class OutputQBitTorrent: """ Example: q...
t RequestException as e: msg = str(e) raise plugin.PluginError( 'Error when trying to send request to qBittorrent: {}'.format(msg) ) def connect(self, config): """ Connect to qBittorrent Web UI. Username and password not necessary if 'Bypass authentic...
'https' if config['use_ssl'] else 'http', config['host'], config['port'] ) self.check_api_version('Check API version failed.', verify=config['verify_cert']) if config.get('username') and config.get('password'): data = {'username': config['username'], 'password': config['pas...
SRombauts/LoggerCpp
cpplint.py
Python
mit
160,846
0.008287
#!/usr/bin/python # # Copyright (c) 2009 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of ...
he following disclaimer # in the documentation and/or other materials provided wi
th the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIE...
testmana2/test
DebugClients/Python/DebugThread.py
Python
gpl-3.0
3,920
0.004337
# -*- coding: utf-8 -*- # Copyright (c) 2002 - 2015 Detlev Offenbach <detlev@die-offenbachs.de> # """ Module implementing the debug thread. """ import bdb import sys from DebugBase import DebugBase class DebugThread(DebugBase): """ Class implementing a debug thread. It represents a thread in the pyth...
et_ident(se
lf, id): """ Public method to set the id for this thread. @param id id for this thread (int) """ self.__ident = id def get_ident(self): """ Public method to return the id of this thread. @return the id of this thread (int) ...
gully/Starfish
Starfish/utils.py
Python
bsd-3-clause
11,039
0.009602
import numpy as np import multiprocessing as mp import Starfish.constants as C import csv import h5py from astropy.table import Table from astropy.io import ascii def multivariate_normal(cov): np.random.seed() N = cov.shape[0] mu = np.zeros((N,)) result = np.random.multivariate_normal(mu, cov) prin...
r_plot(flatchain, base, format=".pdf"): ''' Make a triangle plot of just M vs i ''' import matplotlib matplotlib.rc("font", size=8) matplotlib.rc("lines", linewidth=0.
5) matplotlib.rc("axes", linewidth=0.8) matplotlib.rc("patch", linewidth=0.7) import matplotlib.pyplot as plt #matplotlib.rc("axes", labelpad=10) from matplotlib.ticker import FormatStrFormatter as FSF from matplotlib.ticker import MaxNLocator import triangle labels = [r"$M_\ast\enskip ...
hrayr-artunyan/shuup
shuup_tests/core/test_enums.py
Python
agpl-3.0
763
0
# This file is part of Shuup. # # Copyright (c) 2012-2015, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from django import forms from django.db import models from e
numfields import Enum, EnumIntegerField class Color(Enum): RED = 0 GREEN = 1 class Labels: RED = 'red' GREEN = 'green' class Colored(models.Model): color = EnumIntegerF
ield(Color, default=Color.RED) class ColoredForm(forms.ModelForm): class Meta: model = Colored fields = ["color"] def test_form_enum_field_choices(): choices = ColoredForm.base_fields['color'].choices assert choices == [(0, 'red'), (1, 'green')]
axinging/chromium-crosswalk
third_party/WebKit/Tools/Scripts/webkitpy/tool/commands/commandtest.py
Python
bsd-3-clause
2,622
0.001144
# Copyright (C) 2009 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the f...
ptions.obsolete_patches = True options.open_bug = True options.port = 'MOCK port' options.update_changelogs = False options.quiet = True options.reviewer = 'MOCK reviewer' command.bind_to_tool(tool) OutputCap
ture().assert_outputs(self, command.execute, [options, args, tool], expected_stdout=expected_stdout, expected_stderr=expected_stderr, expected_exception=expected_exception, expected_logs=expected_logs)
jayoshih/ricecooker
docs/conf.py
Python
mit
19,912
0.001708
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # ricecooker documentation build configuration file, created by # sphinx-quickstart on Wed Sep 21 19:57:19 2016. # # 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 #...
ry. These files are copied # directly to the root of the documentation. # # html_extra_path = [] # If not None, a 'Last updated on:' timestamp is inserted at every page # bottom, using the given strftime format. # The empty string is equivalent to '%b %d, %Y'. # # html_last_updated_fmt
= None # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. # # html_use_smartypants = True # Custom sidebar templates, maps document names to template names. # # html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # templ...
koki-sato/capture-the-flag
write-ups/OverTheWire/Natas/solver/natas18.py
Python
mit
700
0.01
# -*- coding: utf-8 -*- import requests URL = 'http://natas18.natas.labs.overthewire.org/' AUTH = ('natas18', 'xvKIqDjy4OPv7wCRgDlmj0pFsCsDjhdP') def get_password(): param = { 'username': 'admin', 'password': 'hoge' } for i in range(640): coo
kies = { 'PHPSESSID': str(i) }
r = requests.post(URL, auth=AUTH, data=param, cookies=cookies) if 'You are an admin.' in r.text: print "[+] %s: Hit!" % i print r.text break else: if (i % 10) == 0: print "[-] %s: failed." % i def main(): get_password() if __na...
mancoast/CPythonPyc_test
fail/313_test_urllib2.py
Python
gpl-3.0
51,087
0.001644
import unittest from test import support import os import io import socket import urllib.request from urllib.request import Request, OpenerDirector # XXX # Request # CacheFTPHandler (hard to write) # parse_keqv_list, parse_http_list, HTTPDigestAuthHandler class TrivialTests(unittest.TestCase): def test_trivial(...
ompatibility. (In the HTTP case, normalization to .title()-case is done
by urllib2 before sending headers to http.client). >>> url = "http://example.com" >>> r = Request(url, headers={"Spam-eggs": "blah"}) >>> r.has_header("Spam-eggs") True >>> r.header_items() [('Spam-eggs', 'blah')] >>> r.add_header("Foo-Bar", "baz") >>> items = sorted(r.header_items(...
SHASHANKB/spark
python/pyspark/ml/param/__init__.py
Python
apache-2.0
17,158
0.000991
# # 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 us...
convert %s to list of strings" % value) @staticmethod def toVector(v
alue): """ Convert a value to a MLlib Vector, if possible. """ if isinstance(value, Vector): return value elif TypeConverters._can_convert_to_list(value): value = TypeConverters.toList(value) if all(map(lambda v: TypeConverters._is_numeric(v), ...
MediaKraken/MediaKraken_Deployment
source/metadata/metadata_provider_anidb.py
Python
gpl-3.0
10,547
0.006447
""" Copyright (C) 2015 Quinn D Granfor <spootdev@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2, as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but ...
fetch_titles_file(): # since new titles
file....recheck by title self.com_net_anidb_aid_by_title(title_to_search) else: return None else: return local_db_result async def com_net_anidb_connect(self, user_name, user_password): """ Remote api calls """ await c...
xively/ee_live_2014
python/pull-red.py
Python
mit
921
0.013029
#!/usr/bin/env python # # simple script to repeatedly publish an MQTT message # # uses the Python MQTT client from the Paho project # http://eclipse.org/paho # # Andy Piper @andypiper http://andypiper.co.uk # # 2011/09/15 first version # 2012/05/28 updated t
o use new pure python client from mosquitto # 2014/02/03 updated to use the Paho client # # pip install paho-mqtt # python blast.py import paho.mqtt.client as paho import os import time import sys import random random.seed() # Create a client mypid = os.getpid() client_uniq = "pubclient_"+str(mypid) mqttc = paho....
nect(broker, port, 60) msg = "red" # remain connected and publish while mqttc.loop() == 0: mqttc.publish("vote", "!" + msg + "~", 0, False) #qos=0, retain=n print "published: %s" % msg time.sleep(random.uniform(0.1, 0.3)) pass
yuhangwang/MirrorAI
special_topic/barcode/try.py
Python
mit
1,895
0.016887
# source: http://www.pyimagesearch.com/2014/11/24/detecting-barcodes-images-python-opencv/ # import the necessary packages import numpy as np import argparse import cv2 # construct the argument parse and parse the arguments ap = argparse.ArgumentParser() ap.add_argument("-i", "--image", required = True, help = "path t...
y, ddepth = cv2.CV_32F, dx = 1, dy = 0, ksize = -1) gradY = cv2.Sobel(gray, ddepth = cv2.CV_32F, dx = 0, dy = 1, ksize = -1) # subtract the y-gradient from
the x-gradient gradient = cv2.subtract(gradX, gradY) gradient = cv2.convertScaleAbs(gradient) # blur and threshold the image blurred = cv2.blur(gradient, (9, 9)) (_, thresh) = cv2.threshold(blurred, 225, 255, cv2.THRESH_BINARY) # construct a closing kernel and apply it to the thresholded image kernel = cv2.getStruct...
psarka/uplift
uplift/ensemble/base.py
Python
bsd-3-clause
4,748
0
""" Base class for ensemble-based estimators. """ # Authors: Gilles Louppe # License: BSD 3 clause import multiprocessing import numpy as np from ..base import clone from ..base import BaseEstimator from ..base import MetaEstimatorMixin class BaseEnsemble(BaseEstimator, MetaEstimatorMixin): """Base class for al...
Parameters ---------- base_estimator : object, optional (default=None) The base estimator from which the ensemble is built. n_estimators : integer The number of estimators in the ensemble. estimator
_params : list of strings The list of attributes to use as parameters when instantiating a new base estimator. If none are given, default parameters are used. Attributes ---------- base_estimator_ : estimator The base estimator from which the ensemble is grown. estimators_ : li...
MatheusDaeuble/admsolucoesblog
blog/models.py
Python
bsd-3-clause
1,053
0.039886
from django.db import models from ckeditor.fields import RichTextField from djang
o.contrib.a
uth.models import User class Categoria(models.Model): id = models.AutoField(primary_key=True) nome = models.CharField(max_length=100, blank=False) def __str__(self): return self.nome def __unicode__(self): return self.nome def upload_location(instance, filename): return "post/{}/{}".format(instance.sl...
D-X-Y/NATS-Bench
nats_bench/api_topology.py
Python
mit
20,399
0.001765
##################################################### # Copyright (c) Xuanyi Dong [GitHub D-X-Y], 2020.08 # ############################################################################## # NATS-Bench: Benchmarking NAS Algorithms for Architecture Topology and Size # ######################################################...
str1 = "{:14s} FLOP={:6.2f} M,
Params={:.3f} MB, latency={:} ms.".format( dataset, flop, param, "{:.2f}".format(latency * 1000) if latency is not None and latency > 0 else None, ) train_info = information.get_metrics(dataset, "train") if dataset == "cifar...
EvgenKo423/psd-tools
src/psd_tools/cli.py
Python
mit
1,922
0.001561
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals, print_function import logging import docopt import psd_tools.reader import psd_tools.decoder from psd_tools import PSDImage from psd_tools.user_api.layers import group_layers from psd_tools.debug import pprint from psd_tools.version impo...
ert <psd_filename> <out_filename> [options] psd-tools.py export_layer <psd_filename> <layer_index> <out_filename> [options] psd-tools.py debug <filename> [options] psd-tools.py -h | --help psd-tools.py --version Options: -v --verbose Be more verbose. -...
ding [default: latin1]. """ args = docopt.docopt(main.__doc__, version=__version__) if args['--verbose']: logger.setLevel(logging.DEBUG) else: logger.setLevel(logging.INFO) encoding = args['--encoding'] if args['convert']: psd = PSDImage.load(args['<psd_filename>'], en...
falcaopetri/enqueuer-api
api/migrations/0006_auto_20161015_2113.py
Python
bsd-3-clause
543
0.001842
# -*- co
ding: utf-8 -*- # Generated by Django 1.10.2 on 2016-10-16 00:13 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('api', '0005_queue_name'), ] operations = [ migrati...
delete=django.db.models.deletion.CASCADE, to='api.MediaService'), ), ]
willicab/instalador
instalador/clases/keyboard.py
Python
gpl-2.0
4,131
0.000242
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' 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 i...
nde está almacedado layout' i = 0 exists = False f
or lay in self.all_layouts(): if lay.name == layout: exists = True break i += 1 if exists: return i else: return -1 _xkb_rules_cache = None def XKB_Rules(): '''Este método nos permite usar la cache para el archivo de...
public/testmon
test/coveragepy/__init__.py
Python
mit
98
0.020408
"""b
acktest.py, backunttest.py and coveragetest.py are all taken from coverage.py version
3.7.1"""
CaliopeProject/CaliopeServer
src/cid/forms/siim2/ficha_catastral/models.py
Python
agpl-3.0
6,118
0.011317
# -*- encoding: utf-8 -*- #Caliope Entities from cid.core.forms import FormNode from cid.core.entities import (VersionedNode, RelationshipFrom, CaliopeUser, One, NotConnected, DateTimeProperty, StringProperty, IntegerProperty, FloatProperty, CaliopeJSONPro...
_acueducto_desc = StringProperty() red_acueducto_valor = FloatProperty() red_alcantarillado_desc = StringProperty() red_alcantarillado_valor = FloatProperty() red_gas_desc = StringProperty() red_gas_valor = FloatProperty() red_energia_desc = StringProperty() red_energ...
riales CONDICIONES INDUSTRIALES DE LA ZONA Subtitulo de CONDICIONES FÍSICAS Y AMBIENTALES DEL PREDIO zopra_desc = StringProperty() zopra_valor = FloatProperty() residuos_solidos_desc = StringProperty() residuos_solidos_valor = FloatProperty() pasivos_ambientales_desc = StringProperty() ...
jfisher-usgs/DigitalLibrary
filterObjectValues.py
Python
gpl-2.0
552
0.016304
## Script (Python) "filterObjectValues" ##bind container=container ##bind context=context ##bind namespace= ##bind script=script ##bind subpat
h=traverse_subpath ##parameters=values=None ##title= ## from ZTUtils import LazyFilter from AccessControl import getSecurityManager checkPermission=getSecurityManager().checkPermission items = [] raw_items = context.objectValues(values) secure_items = LazyFilter(raw_items, skip='') for item in secure_items: if chec...
ion('Access contents information', item): items.append(item) return items
TylerFisher/birdseye
template/fabfile/data.py
Python
mit
84
0.011905
#!/usr/bin/env pytho
n """ Commands that update or process the application d
ata. """
crooks/PyClean
pyclean.py
Python
gpl-3.0
67,006
0.001522
# vim: tabstop=4 expandtab shiftwidth=4 autoindent import INN import datetime import logging import logging.handlers import os import o
s.path import re import shelve import sys import time import traceback # In Python2.4, utils was called Utils try: from email.utils import parseaddr except ImportError: from email.Utils import parseaddr # Python 2.4 doesn't have hashlib try: from ha
shlib import md5 except ImportError: from md5 import md5 try: import configparser except ImportError: import ConfigParser configparser=ConfigParser try: from sys import intern except ImportError: pass # First, define some high-level date/time functions def now(): return datetime.datetime....
adamewing/tebreak
scripts/bam_cpm_mask.py
Python
mit
2,815
0.005329
#!/usr/bin/env python import pysam import argparse import multiprocessing as mp import subprocess import logging logger = logging.getLogger(__name__) FORMAT = '%(asctime)s %(message)s' logging.basicConfig(format=FORMAT) logger.setLevel(logging.INFO) from math import log10 import pandas as pd import scipy.stats as s...
s in sorted(cn_segs): out.write('%s\n' % str(s)) data = pd.DataFrame.from_csv(outfile, sep='\t', header=0, index_col=None) data['z'] = ss.zscore(data['CPM']) highcov = data.loc[data['z'] >
float(args.z)] highcov.to_csv(outfile, sep='\t', index=False) if __name__ == '__main__': parser = argparse.ArgumentParser(description='Build mask from BAM based on CPM') parser.add_argument('--bam', required=True, help='indexed BAM') parser.add_argument('-f', '--fai', required=True, help='fasta inde...
doctorguile/pyqtggpo
ggpo/common/runtime.py
Python
gpl-2.0
647
0.003091
# -*- coding: utf-8 -*- import platform __all__ = ['IS_WINDOWS', 'IS_OSX', 'IS_LINUX', 'Phonon', 'GeoIP2Reader', 'winsound'] IS_WINDOWS = False IS_OSX = False IS_LINUX = False _platform = platform.system() if _platform == 'Windows': IS_WINDOWS = True elif _platform == 'Darwin': IS_OSX = True elif _platform =...
pass winsound = None if IS_WINDOWS: try:
import winsound except ImportError: pass
GeorgeGkas/WifiFactoryPass-GreekTool
wifitools/speed_touch.py
Python
lgpl-3.0
1,873
0.011746
import hashlib import sys import binascii import re import os import sys, os.path localdir = repr(os.path.dirname(os.path.realpath(sys.argv[0]))) localdir = localdir.replace("\\\\","/") localdir = localdir.replace("\'","") def ascii2hex(char): return hex(ord(char))[2:].upper() def thomson_calc(...
prodid1 = prodidnum / (36*36) prodid2 = (prodidnum / 36) % 36 prodid3 = prodidnum % 36 serial = 'CP%02d%02d%s%s%s' % (year-2000,prodweek,ascii2hex(charset[prodid1:prodid1+1]),ascii2hex(charset[prodid2:prodid2+1]),ascii2hex(charset[prodid3:prodid3+1]))...
ssid = sha1sum[-6:] accesskey = sha1sum[0:10] if len(ssidend) == 4: accesskey = accesskey.lower() pwd.append(accesskey) else: pwd.append(accesskey) where...
tokland/shoogle
shoogle/__init__.py
Python
gpl-3.0
107
0
__author__ = 'Arnau Sanchez' __email__ = '
pyarnau@gmail.com' __version__ = '0.1.3' fr
om .shoogle import *
varmarakesh/devops-toolbox
devops-toolbox/nginx/install.py
Python
isc
369
0.00813
__author__ = 'rakesh.varma' from fabric.api import * class nginx_install: def __init__(self, ho
st_ip, host_user, host_key_file): env.host_string = host_ip env.user = host_user env.key_filename = host_key_file
def install(self): sudo('apt-get update') sudo('apt-get install nginx') sudo('service nginx restart')
klahnakoski/MoDataSubmission
pyLibrary/jsons/ref.py
Python
mpl-2.0
7,353
0.00204
# 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 _...
UTE ref.path = "/".join(url.path.rstrip("/").split("/")[:-1]) + "/" + ref.path path = ref.path if os.sep != "\\" else ref.path[1::].replace("/", "\\") try: if DEBUG: _Log.note("reading file {{path}}", path=path) content = File(path).read() except Exception, e: c...
rue, leaves=True) except Exception, e: if not _Except: _late_import() e = _Except.wrap(e) try: new_value = _convert.ini2value(content) except Exception, f: raise _Log.error("Can not read {{file}}", file=path, cause=e) new_value = _replace_ref(...
TwoBitAlchemist/PyBaseConvert
base_convert.py
Python
mit
2,899
0
#! /usr/bin/env python """ Convert arbitrary numbers between integer bases from 2 to 64. """ import string import sys from decimal import Decimal ALL_DIGITS = ''.join(map(str, range(10))) + string.ascii_letters + '+/' DIGIT_MAP = dict(enumerate(ALL_DIGITS)) DIGIT_RMAP = dict(zip(DIGIT_MAP.values(), DIGIT_MAP.keys()))...
frac_digits.append(int(product)) product -= int(product)
if frac_digits: result += '.' + ''.join(map(str, frac_digits)) return result if result else '0' if __name__ == '__main__': handle_error = sys.exit try: sys.argv[1] except IndexError: print('Usage: %s NUM [from_base [to_base [round_to]]]' % sys.argv[0]) sys.exit(1) p...
Injabie3/Red-DiscordBot
cogs/punish.py
Python
gpl-3.0
48,408
0.002644
from datetime import datetime import discord from discord.ext import commands import inspect import logging import os import re import textwrap import time from .mod import CaseMessageNotFound, NoModLogAccess from .utils import checks from .utils.chat_formatting import pagify, box, warning, error, info, bold from .uti...
onOverwrite.from_pair(allow, deny) def overwrite_to_dict(overwrite): allow, deny = overwrite.pair() return { 'allow' : allow.value, 'deny' : deny.value } def format_permissions(permissions, include_null=False): entr
ies = [] for perm, value in sorted(permissions, key=lambda t: t[0]): if value is True: symbol = "\N{WHITE HEAVY CHECK MARK}" elif value is False: symbol = "\N{NO ENTRY SIGN}" elif include_null: symbol = "\N{RADIO BUTTON}" else: continu...
ppwwyyxx/tensorflow
tensorflow/python/kernel_tests/bias_op_base.py
Python
apache-2.0
11,357
0.006516
# 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...
, np_value): # fill the
input value to at least 3-dimension np_value = self._AtLeast3d(np_value) # move the last dimension to second np_dim = list(range(np_value.ndim)) np_dim_new = list(np_dim[0:1]) + list(np_dim[-1:]) + list(np_dim[1:-1]) return np.transpose(np_value, np_dim_new) def _NCHWToNHWC(self, np_value): ...
CingHu/neutron-ustack
neutron/extensions/uos_net_ratelimits.py
Python
apache-2.0
1,922
0
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright (c) 2013 OpenStack Foundation. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www....
ONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from
neutron.api import extensions from neutron.api.v2 import attributes as attr RATE_LIMIT = 'uos:rate_limit' EXTENDED_ATTRIBUTES_2_0 = { 'networks': {RATE_LIMIT: {'allow_post': True, 'allow_put': True, 'default': 600, 'is_visi...
ktbs/ktbs
utest/test_ktbs_engine_trace_obsels.py
Python
lgpl-3.0
2,337
0.008986
from .test_ktbs_engine import KtbsTestCase from unittest import skipUnless from pytest import raises as assert_raises from ktbs.engine.lock import WithLockMixin from ktbs.engine.lock import get_semaphore_name from ktbs.engine.service import make_ktbs class TestKtbsTraceObsels(KtbsTestCase): """Test features of o...
).etags assert get_etags() == [ etag ] assert get_etags(limit=100) == [etag,] assert get_etags(limit=1) == [etag, mstag, pstag,] assert get_etags(limit=2) == [etag, mstag, pstag,] assert get_etags(limit=3) == [etag, mstag,] assert get_etags(limit=4) == [etag, mstag,] ...
assert get_etags(limit=5) == [etag,] assert get_etags(limit=1, offset=1) == [etag, mstag, pstag,] assert get_etags(limit=1, offset=2) == [etag, mstag,] assert get_etags(limit=1, offset=3) == [etag, mstag,] assert get_etags(limit=1, offset=4) == [etag,] assert get_etags(limit=1...
partofthething/infopanel
infopanel/tests/test_mqtt.py
Python
gpl-3.0
818
0
"""Test MQTT connections.""" import unittest from infopanel import
mqtt from infopanel.tests import load_test_config class TestMqtt(unittest.TestCase): """Test connectivity with MQTT.""" @classmethod def setUpClass(cls): cls.conf = load_test_config() def setUp(self): """Set up each test.""" data = {} self.client
= mqtt.MQTTClient(data, self.conf["mqtt"]) @unittest.skip( "Something wrong with the test.mosquitto.org connection from travis ci" ) def test_connect(self): """ Make sure we can connect. This relies on the test.mosquitto.org test server. """ self.client.sta...
LogicalDash/kivy
examples/widgets/actionbar.py
Python
mit
826
0
from kivy.base import runTouchApp from kivy.lang im
port Builder runTouchApp(Builder.load_string(''' ActionBar: pos_hint: {'top':1} ActionView: use_separator: True ActionPrevious: title: 'Action Bar' with_previous: False ActionOverflow: ActionButton: icon: 'atlas://data/images/defaulttheme/audi...
gh' ActionButton: important: True text: 'Important' ActionButton: text: 'Btn2' ActionButton: text: 'Btn3' ActionButton: text: 'Btn4' ActionGroup: text: 'Group1' ActionButton: text:...
n1k0/djortunes
django_fortunes/models.py
Python
mit
2,141
0.002802
from datetime import datetime from django.db import models from django.contrib.auth.models import User from django.contrib.contenttypes import generic from django.contrib.comments.models import Comment from django.utils.translation import ugettext_lazy as _ from django.template.defaultfilters import slugify from djan...
une_detail', (), { 'slug': self.slug, 'year': self.pub_date.year, 'month': self.pub_date.month, 'day': self.pub_date.day })
def save(self): "Saves a fortune after havng checked and generated its slug" self.check_slug() super(Fortune, self).save()
nexdatas/selector
nxsselector/Data.py
Python
gpl-3.0
3,391
0
#!/usr/bin/env python # This file is part of nexdatas - Tango Server for NeXus data writer # # Copyright (C) 2014-2017 DESY, Jan Kotanski <jkotan@mail.desy.de> # # nexdatas is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the ...
# but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with nexdatas. If not, see <http://www.gnu.org/lic...
us.external.qt import Qt except Exception: from taurus.qt import Qt from .EdListDlg import EdListWg import logging #: (:obj:`logging.Logger`) logger object logger = logging.getLogger(__name__) class Data(Qt.QObject): """ User data tab widget """ #: (:class:`taurus.qt.Qt.pyqtSignal`) dirty signal ...
kaoscoach/crits
crits/locations/handlers.py
Python
mit
4,991
0.003206
from mongoengine.base import ValidationError from crits.core.class_mapper import class_from_id from crits.core.crits_mongoengine import EmbeddedLocation from crits.core.handlers import get_item_names from crits.locations.location import Location def get_location_names_list(active): listing = get_item_names(Locat...
:type description: str :param latitude: The new latitude. :type latitude: str :param longitude: The new long
itude. :type longitude: str :returns: dict with key 'success' (boolean) and 'message' (str) if failed. """ crits_object = class_from_id(type_, id_) if not crits_object: return {'success': False, 'message': 'Cannot find %s.' % type_} crits_object.edit_location(location_name, ...
kostaspl/SpiderMonkey38
testing/mozbase/mozdevice/mozdevice/devicemanagerADB.py
Python
mpl-2.0
28,078
0.002244
# 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/. import re import os import shutil import tempfile import time import traceback from devicemanager import DeviceManager,...
gerADB(DeviceManager): """ Implementation of DeviceManager interface that uses the Android "adb" utility to communicate with the device. Normally used to communicate with a device that is directly connected with the host machine over a USB port. """ _haveRootShell = False _haveSu = Fals...
connected = False default_timeout = 300 def __init__(self, host=None, port=5555, retryLimit=5, packageName='fennec', adbPath='adb', deviceSerial=None, deviceRoot=None, logLevel=mozlog.ERROR, autoconnect=True, runAdbAsRoot=False, serverHost=None, serverPort...
ptphp/PyLib
src/pyside/mainwindow/newWin.py
Python
apache-2.0
901
0.00444
#coding:utf-8 ''' Created on Sep 24, 2012 @author: joseph ''' from PySide import QtGui, QtCore class Window(QtGui.QMainWindow): def __init__(self): QtGui.QMainWindow.__init__(self) menu = self.menuBar().addMenu(self.tr('
View')) action = menu.addAction(self.tr('New Window')) action.triggered.connect(self.handleNewWindow) def handleNewWindow(self): window = QtGui.QMainWindow(self) window.setAttribute(QtCore.Qt.WA_DeleteOnClose) window.setWindowTitle(self.tr('New Window')) window.show(...
# self.window.setWindowTitle(self.tr('New Window')) # self.window.show() if __name__ == '__main__': import sys app = QtGui.QApplication(sys.argv) window = Window() window.resize(300, 300) window.show() sys.exit(app.exec_())
sauloal/pycluster
pypy-1.9_64/lib-python/2.7/ctypes/test/test_refcounts.py
Python
mit
2,502
0.003597
import unittest import ctypes import gc MyCallback = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int) OtherCallback = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int, ctypes.c_ulonglong) import _ctypes_test dll = ctypes.CDLL(_ctypes_test.__file__) class RefcountTestCase(unittest.TestCase): def test_1(self): fro...
ssertEqual(result, -18) cb = None gc.collect() self.assertEqual(grc(callback), 2) def test_refcount(self): from sys import getrefcount as grc def func(*args): pass
# this is the standard refcount for func self.assertEqual(grc(func), 2) # the CFuncPtr instance holds atr least one refcount on func: f = OtherCallback(func) self.assertTrue(grc(func) > 2) # and may release it again del f self.assertTrue(grc(func) >= 2) ...
synicalsyntax/zulip
zproject/default_settings.py
Python
apache-2.0
16,883
0.001185
import os from typing import TYPE_CHECKING, Any, Dict, List, Optional from scripts.lib.zulip_tools import deport from .config import DEVELOPMENT, PRODUCTION, get_secret if TYPE_CHECKING: from django_auth_ldap.config import LDAPSearch from typing_extensions import TypedDict if PRODUCTION: from .prod_sett...
c BigBlueButton servers. BIG_BLUE_BUTTON_
URL = get_secret('big_blue_button_url', development_only=True) # Max state storage per user # TODO: Add this to zproject/prod_settings_template.py once stateful bots are fully functional. USER_STATE_SIZE_LIMIT = 10000000 # Max size of a single configuration entry of an embedded bot. BOT_CONFIG_SIZE_LIMIT = 10000 # Ex...
polyaxon/polyaxon
platform/polycommon/polycommon/conf/handlers/settings_handler.py
Python
apache-2.0
1,970
0.001523
#!/usr/bin/python # # Copyright 2018-2021 Polyaxon, 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 ...
() def set( # pylint:disable=arguments-differ self, option: Option, value: Any, **kwargs ) -> None: raise ConfException( "The settings backend does not allow to set
values, " "are you sure the key `{}` was correctly defined.".format(option.key) ) def delete( # pylint:disable=arguments-differ self, option: Option, **kwargs ) -> None: raise ConfException( "The settings backend does not allow to delete values, " "a...
Najsztub/SzczecinHome
restate/restate.py
Python
mit
1,236
0.013754
# -*- coding: utf-8 -*- # MN: 08/04/16 import numpy as np import pandas as pd import re import matplotlib.pyplot as plt import matplotlib import seaborn as sn
s from data.data import clean_data matplotlib.style.use('ggplot') def plot_price_area(out, show = False): g = sns.FacetGrid(df, col="rooms", col_wrap=2) g.map(plt.scatter, "pow", "price") g.savefig(out) if show: plt.show() def plot_year_hist(out, show = False): ax = df.build_year.astype(...
year_hist.png") if show: plt.show() plt.close(fig) if __name__ == "__main__": print "Load data" df = pd.read_csv("data/items_otodom.pl_080416_10.csv", encoding = 'utf-8') print "Clean data" df = clean_data(df) # leave only interesting observaions df=df[df.price >50] df=df[df...
tessera-metrics/tessera
tessera-server/tessera/_version.py
Python
apache-2.0
89
0
__versio
n_info__ = (0, 11, 0, 'beta') __version__ = '.'.join(map(str,
__version_info__))
Fuchai/Philosophy-Machine
modular/vgg.py
Python
apache-2.0
2,350
0.002128
import torch.nn as nn import math class VGG(nn.Module): def __init__(self, features, num_classes=1000): super(VGG, self).__init__() self.features = features self.classifier = nn.Sequential( nn.Linear(8192, 4096), nn.ReLU(True), nn.Dropout(), ...
kernel_size[0] * m.kernel_size[1] * m.out_channels m.weight.data.normal_(0, math.sqrt(2. / n)) if m.bias is not None: m.bias.data.zero_() elif isinstance
(m, nn.BatchNorm2d): m.weight.data.fill_(1) m.bias.data.zero_() elif isinstance(m, nn.Linear): n = m.weight.size(1) m.weight.data.normal_(0, 0.01) m.bias.data.zero_() def make_layers(cfg, batch_norm=False): layers = [] ...
t-amerssonis/okami
src/Okami/third-parts/gitpy/__init__.py
Python
mit
1,673
0
# Copyright (c) 2009, Rotem Yaari <vmalloc@gmail.com> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributi
ons of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials pr
ovided with the distribution. # * Neither the name of organization nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY Rotem Yaari ''AS IS'' AND ANY # EXPRESS OR IMPLIED WA...
darragjm/PokemonGo-Map
pogom/pokelists.py
Python
agpl-3.0
2,118
0.016997
rare_pokemon = ( "Dragonite", "Flareon", "Exeggutor", "Arcanine", "Victreebel", "Magmar", "Charizard", "Nidoking", "Gengar", "Vileplume", "Rapidash", "Raichu", "Machamp", "Venusaur", "Electabuzz", "Cloyster", "Golduck", "Starmie", "Gyarados", "Jolteon", "Weezing", "Weepinbell", "Kabutops", "Vaporeon", "Lapras", "Blasto...
Dratini", "Charmander", "Magnemite", "Lickitung", "Bulbasaur", "Grimer", "Pikachu", "Mankey", "Horsea", "Shellder", "Machop", "Slowpoke", "Rhyhorn", "Exeggcute", "Abra", "Diglett", "Tentacool", "Geodude", "Vulpix", "Seel", "Drowzee", "Sandshrew", "Onix", "Chansey") ultra_rare_pokemon = ( "Dragonite", "Flareon", "Exeggu...
treebel", "Magmar", "Charizard", "Nidoking", "Gengar", "Vileplume", "Rapidash", "Raichu", "Machamp", "Venusaur", "Electabuzz", "Cloyster", "Gyarados", "Kabutops", "Lapras", "Blastoise", "Alakazam", "Magneton", "Nidoqueen", "Aerodactyl", "Snorlax", "Muk", "Poliwrath", "Omastar", "Primeape", "Kingler", "Golem", "Ninetale...
imito/odin
odin/bay/layers/autoregressive_layers.py
Python
mit
6,507
0.003074
import numpy as np import six import tensorflow as tf from tensorflow_probability.python.bijectors.masked_autoregressive import ( AutoregressiveNetwork, _create_degrees, _create_input_order, _make_dense_autoregressive_masks, _make_masked_constraint, _make_masked_initializer) from tensorflow_probability.pyth...
he network's input layers. self._network.input_spec = None # Record that t
he layer has been built. super(AutoregressiveNetwork, self).build(input_shape) def call(self, x, conditional_input=None): """Transforms the inputs and returns the outputs. Suppose `x` has shape `batch_shape + event_shape` and `conditional_input` has shape `conditional_batch_shape + conditional_event...
algorythmic/bash-completion
test/t/test_pydoc.py
Python
gpl-2.0
264
0
import pytest class TestPydoc: @pytest.mark.complete("pydoc r", require_cmd=True) def test_1(self
, completion): assert completion @pytest.mark.complete("
pydoc -", require_cmd=True) def test_2(self, completion): assert completion
KredekPth/Kurs_django
contact/migrations/0001_initial.py
Python
mit
661
0.001513
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-04-27 19:21 from __future__ import unicode_literals from django.db import migrations, models
class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Message', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ...
('email', models.EmailField(max_length=254)), ('message', models.TextField()), ], ), ]
EvanK/ansible
lib/ansible/modules/cloud/azure/azure_rm_devtestlabvirtualnetwork_facts.py
Python
gpl-3.0
6,547
0.001833
#!/usr/bin/python # # Copyright (c) 2019 Zim Kalinowski, (@zikalino) # # 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 ANSIBLE_METADATA = {'metadata_version': '1.1', ...
, 'name': d.get('name', None), 'id': d.get('id', None), 'external_provider_resource_id': d.get('external_provider_resource_id', None), 'provisioning_state': d.get('provisioning_state', None), 'description': d.get('description', None) } return d...
main()
adrian-lang/margolith
solyanka/solyanka/__init__.py
Python
bsd-3-clause
1,936
0.000517
import sys from . import ( utils, env, defs, context, layers, parser, preprocessor, loader, analyzer, generator) LAYERS = ( (parser.Parser, "
parse"), (preprocessor.Preprocessor, "transform_ast"), (loader.Loader, "expand_ast"), (analyzer.Analyzer, "expand_ast"), (generator.Generator, "expand_ast") ) def _get_context_args_from_settings(string, settings):
return { "main_file_hash": utils.get_string_hash(string), "main_file_name": settings["main_file_name"], "module_paths": settings["module_paths"], "loaded_modules": settings["loaded_modules"], "test_mode_on": settings["test_mode_on"], "env": env.Env() } def _updat...
szha/mxnet
tests/nightly/dist_async_kvstore.py
Python
apache-2.0
1,994
0.003009
#!/usr/bin/env python # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "L...
s and limitations # under the License. # pylint: skip-file import sys sys.path.insert(0, "../../python/") import mxnet as mx kv = mx.kv.create('dist_async') my_rank = kv.rank nworker = kv.num_workers def test_gluon_trainer_type
(): def check_trainer_kv_update(weight_stype, update_on_kv): x = mx.gluon.Parameter('x', shape=(10,1), lr_mult=1.0, stype=weight_stype) x.initialize(ctx=[mx.cpu(0), mx.cpu(1)], init='zeros') try: trainer = mx.gluon.Trainer([x], 'sgd', {'learning_rate': 0.1}, ...
xifle/home-assistant
homeassistant/components/media_player/gpmdp.py
Python
mit
12,337
0
""" Support for Google Play Music Desktop Player. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/media_player.gpmdp/ """ import logging import json import os import socket import time import voluptuous as vol from homeassistant.components.media_player ...
sable=unused-argument def gpmdp_configuration_callback(callback_data): """The actions to do when our configuration callback is called.""" while True: from websocket import _exceptions
try: msg = json.loads(websocket.recv()) except _exceptions.WebSocketConnectionClosedException: continue if msg['channel'] != 'connect': continue if msg['payload'] != "CODE_REQUIRED": continue pin...
RichardHyde/SublimeText.Packages
postToDayone.py
Python
mit
366
0.035519
import sublime, sublime_plugin import urllib.request, webbrowser class PostToDayOneCommand(sublime_plugin.TextCommand): def run(self, edit): selections = self.view.sel() selection = self.view.substr(selections[0]) url = "dayone://post?entry=%s
" % urllib.request.quote(selection) f = we
bbrowser.open(url) self.view.replace(edit, selections[0], "")
pylessard/python-udsoncan
udsoncan/services/SecuredDataTransmission.py
Python
mit
2,392
0.020067
from . import * from udsoncan.Response import Response from udsoncan.exceptions import * class SecuredDataTransmission(BaseService): _sid = 0x84 class Code: GeneralSecurityViolation = Response.Code.GeneralSecurityViolation - 0x38 SecuredModeRequested = Response.Code.SecuredMo...
Response.Code.SecuredModeRequested, Response.Code.InsufficientProtection, Response.Code.TerminationWithSignatureRequested,
Response.Code.AccessDenied, Response.Code.VersionNotSupported, Response.Code.SecuredLinkNotSupported, Response.Code.Certifica...
robmcmullen/peppy
i18n.in/make-podict.py
Python
gpl-2.0
13,109
0.003814
#! /usr/bin/env python # -*- coding: iso-8859-1 -*- """Generate python dictionaries catalog from textual translation description. This program converts a textual Uniforum-style message catalog (.po file) into a python dictionary Based on msgfmt.py by Martin v. Löwis <loewis@informatik.hu-berlin.de> """ import sys...
else: for prefix in [u'', u'&']: for suffix in [u'', u'...', u':']:
if not prefix and not suffix: continue keyword = prefix + id.decode(self.current_encoding) + suffix if keyword in self.template and keyword not in self.messages: print ("adding pre/suffixed translation ...
Silance/classTranscribe
p2fa-vislab-master/detect_breaths.py
Python
mit
4,234
0.002834
try: import simplejson as json except: import json import os import re import subprocess import click from radiotool.composer import Speech, Segment, Composition from align import do_alignment ac_re = re.compile(r"\[Ac=(-?\d+)") def alignment_with_breaths(speech_file, alignment_file, out_alignment_file=None...
separate_tracks=False) p
rint "# classifying p%06d.wav" % pause_idx print "# segment length:", x["end"] - x["start"] cls = classify_htk( 'tmpaudio/p%06d.wav' % pause_idx) # cls = breath_classifier.classify( # 'tmp/pauses/p%06d.wav' % pause_idx) ...
lyuboraykov/columba
tests/test_mailgun_provider.py
Python
mit
1,859
0.008607
#!/usr/bin/env python3 import pytest from providers.mailgun import MailGunProvider from send_error import SendError import init_test_objects def test_mailgun_send_positive(): """Straightforward mailgun send test. Will fail if an error is raised by the provider.""" mailgun_provider = MailGunProvider(init_test...
end_missing_recipients(): """The provider should raise a SendError if it has missing sender field""" mailgun_
provider = MailGunProvider(init_test_objects.MAILGUN_TEST_AUTHENTICATION + 's', init_test_objects.MAILGUN_TEST_DOMAIN) test_message = init_test_objects.init_message() test_message.sender = '' with pytest.raises(SendError) as send_error: mailgun_provider.send(test_message) assert send_err...
mconlon17/vivo-1.6-upgrade
tools/test_string_from_document.py
Python
bsd-3-clause
883
0.012458
""" test_string_from_document.py -- given a document structure,
return a string representation Version 0.1 MC 2013-12-28 -- Initial version. """ __author__ = "Michael Conlon" __copyright__ = "Copyright 2013, University of Florida" __license__ = "BSD 3-Clause license" __version__ = "0.1" import vivotools as vt from datetime import datetime from Bio imp...
"19247798", "21493414", "12099768", "11410031", "20143936", "16934145" ] for pmid in pmids: handle = Entrez.efetch(db="pubmed", id=pmid, retmode="xml") records = Entrez.parse(handle) for record in records: print "\n",pmid,"\n", \ vt.string_from_document(vt.d...
jds2001/ocp-checkbox
plugins/final_prompt.py
Python
gpl-3.0
1,402
0.00214
# # This file is part of Checkbox. # # Copyright 2008 Canonical Ltd. # # Checkbox 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. # # C...
super(FinalPrompt, self).register(manager) # Final should be prompted first self._manager.reactor.call_on("prompt-finish", self.prompt_
finish, -100) self._manager.reactor.call_on("report-final-text", self._on_report_final_text, -100) def _on_report_final_text(self, text): self.final_text = text def prompt_finish(self, interface): interface.show_text(self.final_text, next=_("_Finish")) factory = FinalPrompt
blackPantherOS/packagemanagement
rpmanager/PackagePool.py
Python
apache-2.0
10,079
0.008136
#!/usr/bin/env python # -*- coding: iso-8859-2 -*- import string import copy import os import gzip import gtk import commands try: from backports import lzma except ImportError: from lzma import LZMAFile as lzma import singletons from common import * import common; _ = common._ from Source import * from Pack...
lzma(source.hdlist) for line in file: if line[:6] != '@info@': continue fields = line.strip()[7:].split('@') longname = fields[0] size = int(fields[2]) category = fields[3]
self.AddPackage(longname, size, category, source) def RegisterUpgradablePackages(self): upl = commands.getoutput('urpmq --auto-select --whatrequires').split() l = len (upl) i = 0 self.upgradable_packages = [] self.upgradable_packages_long = [] while i ...
GGiecold/PySCUBA
src/PySCUBA/PySCUBA_design.py
Python
mit
15,073
0.006369
#!/usr/bin/env python # -*- coding: utf-8 -*- # PySCUBA/src/PySCUBA/PySCUBA_design.py # Author: Gregory Giecold for the GC Yuan Lab # Affiliation: Harvard University # Contact: g.giecold@gmail.com; ggiecold@jimmy.harvard.edu from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except Att...
mUtf8("dataTypeComboBox")) self.dataTypeComboBox.addItem(_fromUtf8("")) self.dataTypeComboBox.addItem(_fromUtf8("")) self.dataTypeComboBox.addItem(_fromUtf8("")) self.withinGridVerticalLayout_1.addWidget(self.dataTypeComboBox) self.withinGridVerticalLayout_2 = QtGui.QVB
oxLayout() self.withinGridVerticalLayout_2.setObjectName( _fromUtf8("with
b33j0r/climactic
climactic/suite.py
Python
gpl-2.0
2,252
0
#! /usr/bin/env python """ ``climactic.suite`` ------------------- .. autoclass:: ClimacticTestSuite """ import logging import unittest from pathlib import Path from climactic.case import ClimacticTestCase logger = logging.getLogger(__name__) class ClimacticTestSuite(unittest.TestSuite): """ A collection...
def collect_file(cls, target_path, base_path=None): logger.trace( " + Loading yml file {!r}", str(target_path) ) yield from ClimacticTestCase.from_path( target_path, base_path=base_path )
bewest/insulaudit
src/insulaudit/devices/onetouch2.py
Python
mit
2,920
0.065411
from insulaudit.log import io, logger as log from insulaudit import lib, core from insulaudit.data import glucose import time HEADER = [ 0x11, 0x0D ] STX = 0x02 ETX = 0x03 TIMEOUT = 0.5 RETRIES = 3 def ls_long( B ): B.reverse( ) return lib.BangLong( B ) def ls_int( B ): B.reverse( ) return lib.BangInt( ...
R response = '' def __call__( self, port ): self.response = port.readline( ).strip( ) return self.response def decode( self, msg ): return str( msg ) def isEmpty( self, response ): return response == '' class ReadSerial( OneTouchCommand ): code = list(
bytearray( b'DM@' ) ) class ReadFirmware( OneTouchCommand ): code = list( bytearray( b'DM?' ) ) class ReadRFID( OneTouchCommand ): code = list( bytearray( b'DMID' ) ) class ReadGlucose( OneTouchCommand ): code = list( bytearray( b'DMP' ) ) def __call__( self, port ): head = port.readline( ).strip( ) ...
rlowrance/re-local-linear
Codes.py
Python
mit
6,954
0.001582
"provide contents of CoreLogic's code files" import pandas as pd import pdb from pprint import pprint import unittest class Codes(object): def __init__(self, path_parcels='../data/input/corelogic-code-tables/2580_Code_Tables.csv', path_deeds='../data/input/corelogic-code-tables...
scription) in recoded_descriptions else original_description) if original_description != description: if self._verbose:
print 'recoded', table, code, original_description, description safely_insert(table, code, description, ignore, to_description) safely_insert(table, description, code, ignore, to_code) seen.add((table, code, original_description)) return to_code, to_description def _...
Frojd/wagtail-geo-widget
tests/examplesite/management/commands/create_superuser_if_none_exists.py
Python
mit
888
0.001126
from django.contrib.auth import get_user_model from django.core.management.base imp
ort BaseCommand class Command(BaseCommand): """ Create superuser if none exist Example: manage.py create_superuser_if_none_exists --user=admin --password=123 """ def add_arguments(self, parser): parser.add_argument("--user", required=True) parser.add_argument("--password"...
l() if User.objects.exists(): return username = options["user"] password = options["password"] email = options["email"] User.objects.create_superuser(username=username, password=password, email=email) self.stdout.write('Local user "{}" was created'.format(...
jessamynsmith/eggtimer-server
periods/tests/management/commands/test_fix_timezone_for_period_data.py
Python
mit
1,295
0.001544
import datetime import pytz from django.test import TestCase from periods import models as period_models from periods.management.commands import fix_timezone_for_period_data from periods.tests.factories import FlowEventFactory TIMEZONE = pytz.timezone("US/Eastern") class TestCommand(TestCase): def setUp(self):...
self.assertEqual(0, period_models.FlowEvent.objects.count()) def test_fix_timezone_for_period_data(self): self.command.handle() periods = period_models.FlowEvent.objects.all() self.assertEqual(2, periods.count()) self.assertEqual(pytz.utc.localize(datetime.datetime(2014, 1, 31, ...
iods[1].timestamp)
jorgehog/kMC
apps/Quasi2DLoaded/parse_tools.py
Python
gpl-3.0
2,241
0.001339
__author__ = 'jorgehog' from numpy import * def interpolate(value_array, time_array, time, start=0): if start >= len(time_array): return start, 0, 0 i = start while time_array[i] < time: i += 1 if i == len(time_array): return i, 0, 0 if i == 0: if time ...
return derivative def combine_results(time_array, value_array, do_roughen=True): times = set() for time in time_array: time = asarray(time) times = times.union(set(time)) times = array(sorted(list(times))) if do_roughen: times = roughen_single(times) all_f_t = zeros([...
merate(times): for i in range(len(value_array)): loc, scale, all_f_t[i][ti] = interpolate(value_array[i], time_array[i], time, starts[i]) scales[ti] += scale starts[i] = loc if scales[ti] == 0: print "ERROR IN SCALING", ti, time sys.exit(1) ...
punchagan/zulip
zerver/lib/rest.py
Python
apache-2.0
7,852
0.001783
from functools import wraps from typing import Any, Callable, Dict, Mapping, Set, Tuple, Union, cast from django.http import HttpRequest, HttpResponse from django.urls import path from django.urls.resolvers import URLPattern from django.utils.cache import add_never_cache_headers from django.views.decorators.csrf impor...
# for some special views (e.g. serving a file that has been # uploaded), we support using the same URL for web and API clients. if ( "override_api_url_scheme" in view_flags and request.META.get("HTTP_AUTHORIZATION", None) is not None ): # This request ...
rate limiting, because there are good reasons clients # might need to (e.g.) request a large number of uploaded # files or avatars in quick succession. target_function = authenticated_rest_api_view(skip_rate_limiting=True)(target_function) elif "override_api_url_scheme" in vi...
Sorsly/subtle
google-cloud-sdk/lib/googlecloudsdk/command_lib/deployment_manager/type_providers.py
Python
mit
6,219
0.005628
# Copyright 2017 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
be parsed as yaml """ if not options_file: return type_provider file_contents = files.GetFileContents(options_file) yaml_content = None try: yaml_content = yaml.safe_load(file_contents) except yaml.YAMLError, exc: raise exceptions.ConfigError( 'Could not load yaml file {0}: {1}'.format...
ntent: if 'collectionOverrides' in yaml_content: type_provider.collectionOverrides = [] for collection_override_data in yaml_content['collectionOverrides']: collection_override = dm_beta_base.GetMessages().CollectionOverride( collection=collection_override_data['collection']) ...