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
nuagenetworks/vspk-python
vspk/v6/fetchers/nuikepsks_fetcher.py
Python
bsd-3-clause
2,093
0.002867
# -*- coding: utf-8 -*- # # Copyright (c) 2015, Alcatel-Lucent Inc, 2017 Nokia # 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 copyrigh...
IES, INCLUDING, BUT NOT LIMITED TO, THE IM
PLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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...
ryanfobel/multispeq1.py
multispeq1/proxy.py
Python
gpl-3.0
996
0.001004
import uuid from path_helpers import path import numpy as np
try: from base_node_rpc.proxy import ConfigMixinBase, StateMixinBase import arduino_helpers.hardware.teensy as teensy from .node import (Proxy as _Proxy, I2cProxy as _I2cProxy,
SerialProxy as _SerialProxy) class ProxyMixin(object): ''' Mixin class to add convenience wrappers around methods of the generated `node.Proxy` class. For example, expose config and state getters/setters as attributes. ''' host_package_name = ...
franosincic/edx-platform
openedx/core/djangoapps/programs/signals.py
Python
agpl-3.0
1,604
0.00187
""" This module contains signals / handlers related to programs. """ import logging from django.dispatch import receiver from openedx.core.djangoapps.signals.signals import COURSE_CERT_AWARDED from openedx.core.djangoapps.programs.models import ProgramsApiConfig LOGGER = logging.getLogger(__name__) @receiver(COUR...
None """ if not ProgramsApiConfig.current().is_certification_enabled: return # schedule background task to process LOGGER.debug( 'handling COURSE_CERT_AWARDED: username=%s, course_key=%s, mode=%s, status=%s',
user, course_key, mode, status, ) # import here, because signal is registered at startup, but items in tasks are not yet able to be loaded from openedx.core.djangoapps.programs import tasks tasks.award_program_certificates.delay(user.username)
CTSRD-SOAAP/chromium-42.0.2311.135
third_party/WebKit/Source/devtools/scripts/check_injected_script_source.py
Python
bsd-3-clause
3,363
0.002081
#!/usr/bin/env python # Copyright (c) 2014 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 ...
ck list: # - instanceof, since e.g. "obj instanceof Error" may throw if Error is overridden and is not a function # - Object.prototype.toString() # - Array.prototype.* # - Function.prototyp
e.* # - Math.* # - Global functions black_list_call_regex = re.compile(r"\sinstanceof\s+\w*|\bMath\.\w+\(|(?<!InjectedScriptHost)\.(" + proto_functions + r")\(|[^\.]\b(" + global_functions + r")\(") errors_found = False for i, line in enumerate(lines): for match in re.finditer(black_list_ca...
andim/optimmune
fig4/fig4.py
Python
mit
2,501
0.005198
#### # Figure 4 # needs: # - data/*.npz produced by run.py #### import glob import sys sys.path.append('..') from lib.mppaper import * import lib.mpsetup as mpsetup import lib.immune as immune files = sorted((immune.parse_value(f, 'epsilon'), f) for f in glob.glob("data/*.npz")) import run sigma = run.sigma #### le...
= axis_labelpad
mpsetup.despine(ax) fig.tight_layout(pad=tight_layout_pad) fig.subplots_adjust(top=0.85) #### right figures #### epsilon_illustration = 0.2 epsilon, f = [tup for tup in files if tup[0] == epsilon_illustration][0] npz = np.load(f) P1 = npz['P1'] P2 = npz['P2'] Qbase = npz['Qbase'] Q1 = npz['Q1'] Q2 = npz['Q2'] x = npz...
jeisenma/ProgrammingConcepts
11-gui/slidy.py
Python
bsd-3-clause
289
0.069204
from slider import * d
ef setup(): global slidy size(400,200) slidy = Slider( Rect(50,80,300,40), minVal=100, maxVal=255 ) def draw(): background(slidy.value) slidy.draw() def mousePressed(): slidy.press() def mouseDragged(): slidy.drag() def mouseReleased(): slid
y.release()
pcubillos/MCcubed
tests/test_logging.py
Python
mit
2,057
0.002917
# Copyright (c) 2015-2021 Patricio Cubillos and contributors. # MC3 is open-source software under the MIT license (see LICENSE). import pytest import mc3.utils as mu log_content = ["Debugging", "Hello, this is log", "Headline", """ :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: Warning: ...
e, verb=verb) log.debug('Debugging') log.msg('Hello, this is log') log.head('Headline') log.warning('Warning!') log.close() with open(log_file, 'r') as f: content = f.read() assert content == '\n'.join(log_content[3-verb:4]) def test_log_error(tmp_path): verb = 2 log_file ...
debug('Debugging') log.msg('Hello, this is log') log.head('Headline') log.warning('Warning!') with pytest.raises(SystemExit): log.error('Error') # Line number in log_content must match this one with open(log_file, 'r') as f: content = f.read() assert content == '\n'.join(log_c...
aaron-fz/neutron_full_sync
neutron/tests/unit/db/firewall/test_db_firewall.py
Python
apache-2.0
53,076
0.000113
# Copyright 2013 Big Switch Networks, 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 ...
.import_object(fw_plugin) ext_mgr = api_ext.PluginAwareExtensionManager( extensions_path, {constants.FIREWALL: self.plugin}
) app = config.load_paste_app('extensions_test_app') self.ext_api = api_ext.ExtensionMiddleware(app, ext_mgr=ext_mgr) def _test_list_resources(self, resource, items, neutron_context=None, query_params=None): if resource.endsw...
jocelynj/weboob
weboob/tools/config/iniconfig.py
Python
gpl-3.0
4,039
0.001486
# -*- coding: utf-8 -*- # Copyright(C) 2010 Christophe Benz # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, version 3 of the License. # # This program is distributed in the hope that it will...
., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. from __future__ import with_statement from ConfigParser import RawConfigParser, DEFAULTSECT import logging import os from weboob.tools.ordereddict import OrderedDict from .iconfig import IConfig __all__ = ['INIConfig'] class INIConfig(IConfig): ROO...
T = 'ROOT' def __init__(self, path): self.path = path self.values = OrderedDict() self.config = RawConfigParser() def load(self, default={}): self.values = OrderedDict(default) if os.path.exists(self.path): logging.debug(u'Loading application configuration ...
julienawilson/news-project
news_project/manage.py
Python
mit
810
0
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "news_project.settings") try: from django.core.management import exe
cute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the # issue is really that Django is missing to avoid masking other # exceptions on Python 2. try: import django except ImportError: raise ImportE...
onment variable? Did you " "forget to activate a virtual environment?" ) raise execute_from_command_line(sys.argv)
TakesxiSximada/TIL
python/python3.6/err2.py
Python
apache-2.0
95
0.031579
def
kab(n): if n in (0, 1): return [1] for i in range(n): b
yield i * 2
Princeton-CDH/winthrop-django
winthrop/books/management/commands/import_nysl.py
Python
apache-2.0
12,753
0.000941
''' Import command for Winthrop team's spreadsheet. It can be invoked using:: python manage.py import_nysql [--justsammel] /path/to/csv The ``--justsammel`` flag skips import of records to avoid reproducing duplicates, but rebuilds the ``is_sammelband`` flag set and produces an output list. The expect behavior i...
lds = [ 'Number of Pages', 'Type of Volume', 'Subject Tagging (separate with semicolons)', 'EDITION', 'Books with important relationships to this text (separate with semicolons)', 'NYSL DESCRIPTION', 'Other documents that demonstrate this relationship (separate wi...
'Provenance', 'Physical Size' ] def add_arguments(self, parser): parser.add_argument('input_file') parser.add_argument( '--justsammel', action='store_true', dest='just_sammel', default=False, help='Just make sammelband conne...
harisbal/pandas
pandas/core/sparse/api.py
Python
bsd-3-clause
206
0
# pylint: disable=W0611 # flake8: noqa from pandas.core.arrays.sparse import Sparse
Array, SparseDtype from pandas.core.sparse.series import SparseSeries from pandas.core.sparse.frame import SparseDataF
rame
TE-ToshiakiTanaka/stvex
test/data/testcase/library_android_04.py
Python
mit
692
0.001445
import os import sys import time from stve.log import LOG as L from stve.script import StveTestCase class TestCase(StveTestCase): def __init__(self, *args, **kwargs): super(TestCase,
self).__init__(*args, **kwargs) @classmethod def setUpClass(cls): L.info("*** Start TestCase : %s *** " % __file__) def test(self): self.assertTrue("stve.android" in self.service.keys()) adb = self.service["stve.android"].get(self.get("android.serial")) self.assertTrue(ad...
e : %s *** " % __file__)
sourabhv/python-koans-solutions
python3/koans/about_classes.py
Python
mit
4,953
0.000202
#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * class AboutClasses(Koan): class Dog: "Dogs need regular walkies. Never, ever let them drive." def test_instances_of_classes_can_be_created_adding_parentheses(self): # NOTE: The .__name__ attribute will convert the class ...
name def test_init_provides_initial_values_for_instance_variables(self): fido = self.Dog5("Fido") self.assertEqual("Fido", fido.name) def test_args_must_match_init(self): with self.assertRaises(TypeError): self.Dog5() # THINK ABOUT IT: # Why is this so? ...
ido = self.Dog5("Fido") rover = self.Dog5("Rover") self.assertEqual(False, rover.name == fido.name) # ------------------------------------------------------------------ class Dog6: def __init__(self, initial_name): self._name = initial_name def get_self(self): ...
puttarajubr/commcare-hq
corehq/apps/fixtures/upload.py
Python
bsd-3-clause
19,677
0.002643
from couchdbkit import ResourceNotFound from corehq.apps.fixtures.exceptions import FixtureUploadError, ExcelMalformatException, \ DuplicateFixtureTagException, FixtureAPIException from django.core.validators import ValidationError from django.utils.translation import ugettext as _, ugettext_noop from corehq.apps.f...
'") % {'title': e.title}) except ExcelMalformatException as e: raise FixtureUploadError(_("Uploaded excel file has following formatting-problems: '%(e)s'") % {'e': e}) except FixtureAPIException as e: raise FixtureUploadError(unicode(e)) except Exception: raise FixtureUploadError(_("...
d this failure. " "Please make sure the excel file is correctly formatted and try again.")) def validate_file_format(file_or_filename): """ Does basic validation on the uploaded file. Raises a FixtureUploadError if something goes wrong. """ workbook = FixtureWork...
devopsec/threatdetectionservice
api/company/endpoint.py
Python
apache-2.0
13,001
0.013845
from flask import jsonify, request from flask_restful import Resource, reqparse from api.sql.models import * #import all of the models from models.py from api.parse_json import * #for json arg parsing class companyUtils: ''' Decoupling of re-usable methods in a static context Note: jsonify does not handle...
any_data.query.filter_by(company_name=_company_name_).first() if x != None: return { 'response': 200, 'poc': x.poc } else: return { 'response': 400, 'message': 'Company...
ified company are not available' } except Exception as e: return {'response': 400} @staticmethod def get_all_poc_list(): try: # load_only("company_name") x = company_data.query.all() if x != None: co_poc_list = [] ...
caiges/populous
populous/blogs/urls.py
Python
bsd-3-clause
1,526
0.007208
from django.conf.urls.defaults import * urlpatterns = patterns('populous.blogs.views', url(r'^collections/$', 'collection_index', name="blogs-collection_index"), url(r'^collections/(?P<slug>[-\w]+)/$', ...
'blogs_list', name="blogs-list"), url(r'^(?P<blog_slug>[-\w]+)/$',
'blog_detail', name="blogs-entry_archive"), url(r'^(?P<blog_slug>[-\w]+)/(?P<year>\d{4})/$', 'blog_archive_year', name="blogs-entry_archive_year"), url(r'^(?P<blog_slug>[-\w]+)/(?P<...
bfontaine/rogue_scores
rogue_scores/web/stats.py
Python
mit
1,355
0
# -*- coding: UTF-8 -*- """ This modules helps computing interesting stats about the scores stored on the Web server. """ import re from collections import defaultdict def stats(scores): """ Compute stats on a ``ScoresStore``, and return a dict that can then be used in a template. Each value is a string...
sters match a crit
eria for one of these keys, only one of them will be picked. """ if not scores: return {} users = defaultdict(int) killers = defaultdict(int) maxlvl = 0 maxlvl_user = None for s in scores: users[s.user] += 1 if s.status == 'killed' and s.cause: kill...
iluminite/django-configglue
django_configglue/tests/test_configglue.py
Python
lgpl-3.0
15,104
0.000927
# -*- coding: utf-8 -*- # Copyright 2010-2011 Canonical Ltd. This software is licensed under the # GNU Lesser General Public License version 3 (see the file LICENSE). import inspect import textwrap from cStringIO import StringIO from optparse import BadOptionError from unittest import TestCase import django from con...
ns = dict([(name, value) for (name, value) in i
nspect.getmembers(settings) if name.isupper()]) schema = schemas.build(django.get_version(), options) # get known django schema # fail for unknown versions of django django_schema = schemas.get(django.get_version(), strict=True) self.assert_schemas_equal(schema(), django_schema(...
MalloyPower/parsing-python
front-end/testsuite-python-lib/Python-3.5.0/Lib/test/test_smtplib.py
Python
mit
47,462
0.001729
import asyncore import email.mime.text from email.message import EmailMessage from email.base64mime import body_encode as encode_base64 import email.utils import socket import smtpd import smtplib import io import re import sys import time import select import errno import textwrap import unittest from test import sup...
lhost') smtp.quit() except OSError as e: if e.errno == errno.EADDRINUSE:
self.skipTest("couldn't bind to port %d" % port) raise def testNOOP(self): smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3) expected = (25
pexip/pygobject
gi/_option.py
Python
lgpl-2.1
13,192
0.000152
# -*- Mode: Python -*- # pygobject - Python bindings for the GObject library # Copyright (C) 2006 Johannes Hoelzl # # glib/option.py: GOption command line parser # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by th...
r.__init__(self, Option, 'error', description) self.name = name self.parser = None self.help_description = help_description if defaults: self.defaults = defaults self.values = None
self.translation_domain = translation_domain if option_list: for option in option_list: self.add_option(option) def _create_option_list(self): self.option_list = [] self._create_option_mappings() def _to_goptiongroup(self, parser): def callback(op...
openstack/horizon
horizon/utils/validators.py
Python
apache-2.0
2,698
0
# Copyright 2012 Nebula, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agree...
icmp_type): if icmp_type == -1: return raise ValidationError(_("Not a valid ICMP type")) def val
idate_icmp_code_range(icmp_code): if not netutils.is_valid_icmp_code(icmp_code): if icmp_code == -1: return raise ValidationError(_("Not a valid ICMP code")) def validate_ip_protocol(ip_proto): if ip_proto < -1 or ip_proto > 255: raise ValidationError(_("Not a valid IP prot...
beerbauf/Arduino-SC-Interface
src/SerialComunication.py
Python
gpl-3.0
1,152
0.001736
''' Project: Arduino SC Interface - A GUI for Arduino serial comunication @author: Andrea Cirillo <sabageek.blogspot.com> @copyright: 2012 Andrea Cirillo @license: GPL-3 This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as p...
ither version
3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You...
google/rekall
tools/layout_expert/layout_expert/parsers/c_parser.py
Python
gpl-2.0
18,196
0.000165
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2016 Google Inc. All Rights Reserved. # # Authors: # Arkadiusz Socała <as277575@mimuw.edu.pl> # Michael Cohen <scudette@google.com> # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the...
ype manager about the types. if result.name: self.type_manager.add_type(result.name, result) return result def _create_type_definition(self, type_definition, field): """Creates the token definition from inspecting results in tok.""" # The initial type definition we dete...
n = type_definition # Is it a pointer to function? if field.function_args: if field.function_pointer: definition = c_ast.CPointer(c_ast.CFunction()) else: definition = c_ast.CFunction() # We detected pointers - Add pointer references. ...
apophys/err
tests/mention_test.py
Python
gpl-3.0
568
0.001761
from os import path extra_plugin_
dir = path.join(path.dirname(path.realpath(__file__)), "mention_plugin") def test_foreign_mention(testbot): assert "Somebody mentioned toto!" in testbot.exec_command( "I am telling you something @toto" ) def test_testbot_mention(testbot): assert "Somebody mentioned me!" in testbot.exec_command( ...
) def test_multiple_mentions(testbot): assert "Somebody mentioned toto,titi!" in testbot.exec_command( "I am telling you something @toto and @titi" )
ychab/privagal
privagal/urls.py
Python
bsd-3-clause
689
0
# -*- coding: utf-8 -*- from __future__ import u
nicode_literals from django.conf import settings from django.conf.urls import include, url from django.views.i18n import javascript_catalog from wagtail.wagtailadmin import urls as wagtailadmin_urls from wagtail.wagtailcore import urls as wagtail_urls from privagal.core import urls as privagalcore_urls urlpatterns ...
(r'^jsi18n/$', javascript_catalog, name='javascript-catalog'), url(r'^gallery/', include('privagal.gallery.urls', namespace='galleries')), url(r'^{}'.format(settings.MEDIA_URL[1:]), include(privagalcore_urls)), url(r'', include(wagtail_urls)), ]
jia200x/RIOT
tests/xtimer_usleep_short/tests/01-run.py
Python
lgpl-2.1
832
0.001202
#!/usr/bin/env python3 # Copyright (C) 2017 Michel Rottleuthner
<michel.rottleuthner@haw-hamburg.de> # # This file is subject to the terms and conditions of the GNU Lesser # General Public License v2.1. See the file LICENSE in the top level # directory for more details. import sys import pexpect from testrunner import run def testfunc(ch
ild): child.expect(u"This test will call xtimer_usleep for values from \\d+ down to \\d+\r\n") i = 500 while (i >= 0): try: child.expect(u"going to sleep \\d+ usecs...\r\n", timeout=3) except pexpect.TIMEOUT: print("xtimer stuck when trying to sleep %d usecs" % (i+1...
afg984/nthucourses
courses/migrations/0003_auto_20150403_2325.py
Python
bsd-3-clause
630
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): depen
dencies = [ ('courses', '0002_auto_20150403_2321'), ] operations = [ migrations.AddField( model_name='course', name='departments', field=mo
dels.ManyToManyField(to='courses.Department'), ), migrations.AddField( model_name='course', name='semester', field=models.ForeignKey(to='courses.Semester', default=1), preserve_default=False, ), ]
omar-AM/python-pgp
pgp/cipher/tests/test_twofish.py
Python
gpl-3.0
4,392
0
# python-pgp A Python OpenPGP implementation # Copyright (C) 2014 Richard Mitchell # # 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 3 of the License, or # (at your option) any la...
ier.com/code/twofish-kat.zip # ecb_ival.txt ('00000000000000000000000000000000', '9f589f5cf6122c32b6bfec2f2ae8c35a', '00000000000000000000000000000000', '128-bit key
'), ('00000000000000000000000000000000', 'cfd1d2e5a9be9cdf501f13b892bd2248', '0123456789abcdeffedcba98765432100011223344556677', '192-bit key'), ('00000000000000000000000000000000', '37527be0052334b89f0cfccae87cfa20', '0123456789abcdeffedcba987654321000112233445566778899aabbccddeeff', '256...
hawkeyexp/plugin.video.netflix
packages/mysql-connector-python/mysql/connector/protocol.py
Python
mit
29,453
0.00034
# Copyright (c) 2009, 2018, Oracle and/or its affiliates. All rights reserved. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License, version 2.0, as # published by the Free Software Foundation. # # This program is also distributed with certain s...
ket += self._connect_with_db(client_flags, database) packet += struct.pack('<H', charset) if client_flags & ClientFlag.PLUGIN_AUTH: packet += auth_plugin.encode('utf8') + b'\x00' return packet def parse_handshake(self, packet): """Parse a MySQL Handshake-packet""" ...
Error("Protocol mismatch; server version = {}, " "client version = {}".format(res["protocol"], PROTOCOL_VERSION))
AlbertoPeon/invenio
modules/webaccess/lib/access_control_config.py
Python
gpl-2.0
35,364
0.00574
## 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 Software Foundation; either version 2 of the ## Lic...
Robot": ExternalAuthRobot(enforce_external_nicknames=True, use_zlib=True) } # CFG_TEMP_EMAIL_ADDRESS # Temporary email address for logging in with an OpenID/OAuth provider which # doesn't supply email address CFG_TEMP_EMAIL_ADDRESS = "%s@NOEMAIL" # CFG_OPENID_PROVIDERS # CFG_OAUTH1_PROVIDERS # CFG_OAUTH2_PROVIDER...
ed with an temporary # email address like CFG_TEMP_EMAIL_ADDRESS % randomstring # # Order of the login buttons can be changed by CFG_EXTERNAL_LOGIN_BUTTON_ORDER # in invenio.websession_config CFG_OPENID_PROVIDERS = [ 'google', 'yahoo', 'aol', 'wordpress', 'myvidoop', 'openid', 'verisign', ...
patricmutwiri/pombola
pombola/core/migrations/0050_del_social_auth.py
Python
agpl-3.0
243
0
# encoding: utf-8 from
. import AppRemoveMigration class Migration(AppRemoveMigration): app_name = 'social_auth' tables = [ 'social_auth_association', 'social_a
uth_nonce', 'social_auth_usersocialauth', ]
seakers/daphne_brain
AT/recommendation/urls.py
Python
mit
164
0.006098
from django.urls import path from . import views urlpatterns = [ path('procedure', views.Pdf
Viewer.as_view())
, path('figure', views.PngViewer.as_view()) ]
jimflim/blender-scripts
extend.py
Python
gpl-2.0
8,848
0.004973
# ##### BEGIN GPL LICENSE BLOCK ##### # # 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 distrib...
olate_all_segments(spl) for spl in shape_ob.data.splines] def get_shape_bounds(shape_ob): ''' > shape_ob: bezier shape object < returns min X, max X, min Y, max Y ''' return (shape_ob.bound_box[0][0], shape_ob.bound_box[4][0], shape_ob.bound_box[0][1], shape_ob.bound_box[3][1]) d...
max, ymin, ymax) returns furthest projection of p2->p1 inside bounds ''' x1, y1 = p1[0], p1[1] x2, y2 = p2[0], p2[1] if abs(x1-x2) > abs(y1-y2): if x1 < x2: #return intersect_line_line_2d(p1, p1_handle, Vector((bounds[0], 0)), Vector((bounds[0], 1))) return (Vector((...
sippy/b2bua
sippy/Security/SipNonce.py
Python
bsd-2-clause
5,055
0.005143
# Copyright (c) 2020 Sippy Software, Inc. All rights reserved. # # All rights reserved. # # Redistribut
ion 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 the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation and/or # ...
jubalh/MAT
libmat/hachoir_editor/typed_field.py
Python
gpl-2.0
8,361
0.000837
from hachoir_core.field import ( RawBits, Bit, Bits, PaddingBits, RawBytes, Bytes, PaddingBytes, GenericString, Character, isInteger, isString) from field import FakeField class EditableField(FakeField): """ Pure virtual class used to write editable field class. """ _is_altered = Fals...
def _getSize(self): if self._value is not None: return self._computeSize() else: return FakeField._getSize(sel
f) size = property(_getSize) def _write(self, output): raise NotImplementedError() def writeInto(self, output): if self._is_altered: self._write(output) else: return FakeField.writeInto(self, output) class EditableFixedField(EditableField): """ Ed...
weiting-chen/manila
manila/db/migrations/alembic/versions/533646c7af38_remove_unused_attr_status.py
Python
apache-2.0
2,171
0.002303
# Copyright 2015 Mirantis, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, s...
OLUMN_NAME = 'status' TABLE_NAMES = ('network_allocations', 'security_services') def upgrade(): for t_name in TABLE_NAMES: try: op.drop_column(t_name, COLUMN_NAME) except Exception: LOG.error(_LE("Column '%s' could not be dropped"), COLUMN_NAME) raise def down...
op.add_column( t_name, sql.Column( COLUMN_NAME, # NOTE(vponomaryov): original type of attr was enum. But # alembic is buggy with enums [1], so use string type # instead. Anyway we have no reason to keep en...
JConwayAWT/PGSS14CC
lib/python/multimetallics/solvers/ExampleSolver.py
Python
gpl-2.0
1,857
0.013463
#------------------------------------------------------------------------------- # Name: Example solver # Purpose: Example solver # # Author: Martin Schneider # # Created: 07/14/2014 # Copyright: (c) Martin 2014 # Licence: Creative Commons (CC) #---------------------------------------...
er atoms self.particle = genParticle(self.definingString,int(self.numberOfAtoms)) # self.definingString looks like:
"Pt50Au30" #print "my defining string is " + self.definingString # self.numberOfAtoms looks like: "80" (you'll need to call int(self.numberOfAtoms)) #print "my number of atoms is " + self.numberOfAtoms #do all of your solving stuff you want... #FINAL_SOLUTION = IMPLEMENT_FINAL_SOLUTION()...
ltowarek/budget-supervisor
third_party/nordigen/test/test_status6e6_enum.py
Python
mit
933
0
# coding: utf-8 """ Nordigen Account Information Services API No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501 OpenAPI spec version: 2.0 (v2) Generated by: https://github.com/swagger-api/swagger-codegen.git "
"" from __future__ import absolute_import import unittest import nordigen from nordigen.models.status6e6_enum import Status6e6
Enum # noqa: E501 from nordigen.rest import ApiException class TestStatus6e6Enum(unittest.TestCase): """Status6e6Enum unit test stubs""" def setUp(self): pass def tearDown(self): pass def testStatus6e6Enum(self): """Test Status6e6Enum""" # FIXME: construct object wi...
skamayker/docker_mail
postfixadmin/ADDITIONS/import_users_from_csv.py
Python
gpl-2.0
6,787
0.008251
#!/usr/bin/env python # -*- coding: utf-8 -*- # Script takes a CSV list of users and does a 'bulk' insertion into mysql. # # Copyright (C) 2009 Simone Piccardi # # 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 Softw...
opy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # import csv import getopt import sys import re import time import random, string from datetime import datetime from crypt import crypt t...
db module, you must install it' print 'on Debian systems just use the command' print ' apt-get install python-mysqldb' def usage(): print "Usage: inspostadmusers.py [options] users.csv" print " -h print this help" print " -t test run, do not insert, just print" print...
niclabs/ratadns-filters
tests/test_rdbit.py
Python
mit
925
0
import unittest import StringIO from packetsexample import PacketsExample from prers import RdBit class TestRdBit(unittest.TestCase): def reinit(self): self.__stringbuffer1 = StringIO.StringIO() self.__p1 = RdBit(self.__stringbuffer1) def data_example(self): data = PacketsExample() ...
data.set_expected("set", 5) data.put_information('rdBit', ["set"]) return data def test_data_example(self): self.reinit() example = self.data_example() for packet in example: self.__p1(packet) result = self.__p1.get_data() for rdbit in e...
.expected_value(rdbit), result[rdbit])
dimven/SpringNodes
py/FamilyInstance.ByHostAndPoint.py
Python
mit
1,222
0.026187
#Copyright(c) 2016, Dimitar Venkov # @5devene, dimitar.ven@gmail.com import clr clr.AddReference("RevitServices") import RevitServices from RevitServices.Persistence import DocumentManager from RevitServices.Transactions import TransactionManager doc = DocumentManager.Instance.CurrentDBDocument clr.AddReference("Rev...
s[i].ToXyz(True) j = 0 if ftp_len else i k = 0 if hst_len else i try:
if not ftype[j].IsActive : ftype[j].Activate() level = doc.GetElement(host[k].LevelId) nf = doc.Create.NewFamilyInstance(p,ftype[j],host[k],level,strt) OUT.append(nf.ToDSType(False)) except: OUT.append(None) TransactionManager.Instance.TransactionTaskDone()
colab/colab
colab/accounts/admin.py
Python
gpl-2.0
1,320
0
from django.contrib import admin from django.contrib.auth import get_user_model from django.contrib.auth.admin import UserAdmin from django.utils.translation import ugettext_lazy as _ from .forms import ColabSetUsernameForm, UserChangeForm User = get_user_model() class CustomUserAdmin(UserAdmin): form = UserCh...
(_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser', 'groups')}), (_('Important dates'), {'fields': ('last_login', 'date_joined')}) ) add_fieldsets = ( ...
'email', 'password1', 'password2'), }), ) admin.site.register(User, CustomUserAdmin)
HiroIshikawa/21playground
visualizer/_app_boilerplate/venv/lib/python3.5/site-packages/requests/adapters.py
Python
mit
17,495
0.001029
# -*- coding: utf-8 -*- """ requests.adapters ~~~~~~~~~~~~~~~~~ This module contains the transport adapters that Requests uses to define and maintain connections. """ import os.path import socket from .models import Response from .packages.urllib3.poolmanager import PoolManager, proxy_from_url from .packages.urllib...
rom_url( proxy, proxy_headers=proxy_headers, num_pools=self._pool_connections, maxsize=self._pool_maxsize, block=self._pool_block, **proxy_kwargs) return self.proxy_manager[proxy] def cert_verify
(self, conn, url, verify, cert): """Verify a SSL certificate. This method should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param conn: The urllib3 connection object associated with the cert. ...
sdphome/UHF_Reader
u-boot-2015.04/tools/patman/gitutil.py
Python
gpl-3.0
19,567
0.001993
# Copyright (c) 2011 The Chromium OS Authors. # # SPDX-License-Identifier: GPL-2.0+ # import command import re import os import series import subprocess import sys import terminal import checkpatch import settings # True to use --no-decorate - we check this in Setup() use_no_decorate = True def LogCmd(commit_range,...
ut) return patch_count def NameRevision(commit_hash): """Gets the revision name for a commit Args: commit_hash: Commit hash to look up Return: Name of revision, if any, else None """ pipe = ['git', 'name-rev', commit_hash] stdout = command.RunPipe([pipe], capture=True, one...
e upstream for a branch This lists out top commits on a branch and tries to find a suitable upstream. It does this by looking for the first commit where 'git name-rev' returns a plain branch name, with no ! or ^ modifiers. Args: git_dir: Git directory containing repo branch: Name of br...
ShifuML/pyshifu
main.py
Python
apache-2.0
73
0
from pyshi
fu.shifu import Shi
fu shifu = Shifu() shifu.new("hello", ".")
buckbaskin/Insight
flaskserver/app/home/__init__.py
Python
apache-2.0
131
0.015267
from flask import B
lueprint blueprint = Blueprint('home', __name__, template_folder='templates') from app.home imp
ort endpoints
MoRgUiJu/morguiju.repo
plugin.video.pelisalacarta/servers/vimpleru.py
Python
gpl-2.0
1,920
0.01407
# -*- coding: utf-8 -*- #------------------------------------------------------------ # pelisalacarta - XBMC Plugin # Conector para vimple.ru # http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/ #------------------------------------------------------------ import re from core import config from core import logger...
vidor en el texto pasado def find_videos(data):
encontrados = set() devuelve = [] # http://player.vimple.ru/iframe/21ff2440e9174286ad8c22cd2efb94d2 patronvideos = 'vimple.ru/iframe/([a-f0-9]+)' logger.info("[vimple.ru] find_videos #"+patronvideos+"#") matches = re.compile(patronvideos,re.DOTALL).findall(data) for match in matches: ...
unicef-zambia/zambia-ureport
zambiaureport/users/migrations/0001_initial.py
Python
bsd-3-clause
2,693
0.005199
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import django.utils.timezone import django.core.validators class Migration(migrations.Migration): dependencies = [ ('auth', '0001_initial'), ] operations = [ migrations.CreateModel( ...
e=False, auto_created=True, primary_key=True)), ('password', models.CharField(max_length=128, verbose_name='password')), ('last_login', models.DateTimeField(default=django.utils.timezone.now, verbose_name='last login')), ('is_superuser', models.BooleanField(default=False,...
ext='Required. 30 characters or fewer. Letters, digits and @/./+/-/_ only.', unique=True, max_length=30, verbose_name='username', validators=[django.core.validators.RegexValidator('^[\\w.@+-]+$', 'Enter a valid username.', 'invalid')])), ('first_name', models.CharField(max_length=30, verbose_name='first...
mindriot101/srwmodule
testing/test_util_cache.py
Python
mit
1,169
0.002566
try: import cPickle as pickle except ImportError: import pickle from srw.util import cache import os import unittest class TestCache(unittest.TestCase): cache_stub = 'cachestub' cache_name = '.{0}.cpickle'.format(cache_stub) def setUp(self): if os.path.isfile(self.cache_name): ...
s.cached_function = cached_function def test_that_a_value_without_a_cache_creates_one(self): self.cached_function() assert os.path.isfile(self.cache_name) def test_cache_contents(self): self.cached_function() self.cached_function() assert pickle.load(open(self.cache_na...
format(cache_stub) @cache(cache_stub, directory=os.path.dirname(cache_path)) def do_test(): return 5 if os.path.isfile(cache_path): os.remove(cache_path) assert do_test() == 5 assert os.path.isfile(cache_path)
bengosney/rhgd3
gardens/migrations/0011_auto_20170806_1654.py
Python
gpl-3.0
613
0.001631
# -*- coding: utf-8 -*- # Generated by Django 1.11.3 on 2017-08-06 16:54 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('gardens', '0010_auto_20170726_2100'), ] operations = [ migrations.RemoveFie...
name='main', ), migrations.AddField( model_name='garden', name='short_description', field=models.CharField(blank=True, max_length=150, verbose_name='Short D
escription'), ), ]
sriramsv/assist
my_assist/compat.py
Python
bsd-3-clause
400
0.0025
# -*- coding: utf-8 -*- """Python 2/3 compatibility module.""" import sys PY2 = int(sys.version[0]) ==
2 if PY2: text_type = unicode # noqa binary_type = str string_types = (str, unicode) # noqa unicode = unicode # noqa basestring = basestring # noqa else: text_type = str binary_type = bytes string_types = (str,) un
icode = str basestring = (str, bytes)
Alignak-monitoring-contrib/alignak-backend
alignak_backend/models/graphite.py
Python
agpl-3.0
6,079
0.00181
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Resource information of graphite """ def get_name(friendly=False): """Get name of this resource :return: name of this resource :rtype: str """ if friendly: # pragma: no cover return 'Graphite connection' return 'graphite' def get_do...
: 'integer', 'empty': False, 'default': 2004 }, 'graphite_address': { 'schema_version': 1, 'title': 'Graphite address', 'comment': '', 'typ
e': 'string', 'required': True, 'empty': False, }, 'graphite_port': { 'schema_version': 1, 'title': 'Graphite port', 'comment': '', 'type': 'integer', 'empty': False, '...
tmenjo/cinder-2015.1.0
cinder/tests/api/contrib/test_types_manage.py
Python
apache-2.0
14,935
0
# Copyright 2011 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requ...
ertRaises(webob.exc.HTTPNotFound, self.controller._delete, req, '777') self.assertEqual(1, len(fake_notifier.NOTIFICATIONS)) def test_volume_types_with_volumes_destroy(self): self.stubs.Set(volume_types, 'get_volume_type', return_volume_types_get_vol...
ith_volumes_destroy) req = fakes.HTTPRequest.blank('/v2/fake/types/1') self.assertEqual(0, len(fake_notifier.NOTIFICATIONS)) self.controller._delete(req, 1) self.assertEqual(1, len(fake_notifier.NOTIFICATIONS)) def test_create(self): self.stubs.Set(volume_types, 'create', ...
dragondjf/musicplayer
gui/utils/__init__.py
Python
gpl-2.0
619
0
#!/usr/bin/python # -*- coding: utf-8 -*- import os import functools views = {} def collectView(func): @functools.wraps(func) def wrapper(*args, **kwargs): self = args[0] if hasattr(self, 'view
ID'): views.update({self.viewID: self}) func(*args, **kwargs) return wrapper def setSkinForApp(qssfile): from PyQt5.QtWidgets import QApplication if os.path.exists(qssfile): fd = open(qssfile, "r") style = fd.read()
fd.close() QApplication.instance().setStyleSheet(style) else: QApplication.instance().setStyleSheet("")
macs03/demo-cms
cms/lib/python2.7/site-packages/djangocms_link/fields.py
Python
mit
1,238
0.001616
from django.conf import settings if 'django_select2' in settings.INSTALLED_APPS: from django_select2.fields import AutoModelSelect2Field class PageSearchField(AutoModelSelect2Field): search_fields = [ 'title_set__title__icontains', 'title_set__me
nu_title__icontains', 'title_set__slug__icontains' ] def get_queryset(self): queryset = super(PageSearchField, self).get_queryset() return queryset.distinct() def security_check(self, request, *args, **kwargs): user = request.user if ...
and not user.is_anonymous() and user.is_staff: return True return False class UserSearchField(AutoModelSelect2Field): search_fields = ['username__icontains', 'firstname__icontains', 'lastname__icontains'] def security_check(self, request, *args, **kwargs): u...
jswoboda/NonMaxwellianExperiments
spcorrdecimateall.py
Python
mit
12,891
0.016678
#!/usr/bin/env python """ spcorrdecimateall.py John Swoboda """ import os import numpy as np import tables import glob import matplotlib.pyplot as plt import pdb import ioclass from IQTools import CenteredLagProduct, FormatIQ if __name__ == "__main__": ## Define input params Input spcor_dir = '/Volumes/ISRDriv...
.array([fullfiledict2['/S/Cal']['Beamcodes'][0]])),0) #beamcodes_noise =np.concatenate(( beamcodes_noise,np.array([fullfiledict2['/S/Noise']['Beamcodes'][0]])),0) #cal_pint = np.concatenate((cal_pint, np.array([fullfiledict2['/S/Cal']['PulsesIntegrated'][0]])),0) #caldata = np.concat...
([fullfiledict2['/S/Noise']['PulsesIntegrated'][0]])),0) #noise_pwer = np.concatenate((noise_pwer, np.array([fullfiledict2['/S/Noise/Power']['Data'][0]])),0) #noise_data =np.concatenate((noise_data, np.array([fullfiledict2['/S/Noise/Acf']['Data'][0]])),0) patternlocdic = patternlocdi...
shagi/guifiadmin
guifiadmin/urls.py
Python
agpl-3.0
1,144
0
"""guifiadmin URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-...
Add a URL to urlpatterns: url(r'^blog/', include(blog_urls)) """ from django.conf.urls import include, url from django.contrib import admin from django.views.generic import Template
View urlpatterns = [ url(r'^$', TemplateView.as_view(template_name='home.html'), name='home'), url(r'^admin/', admin.site.urls), url(r'^chaining/', include('smart_selects.urls')), url(r'^invoices/', include('invoices.urls')), url(r'^guifi/', include('guifi.urls')), url(r'^vpn/', include('vpn.ur...
catalyzeio/python-sample-app
sampleapp/settings.py
Python
apache-2.0
2,799
0.000357
""" Django settings for sampleapp project. Generated by 'django-admin startproject' using Django 1.8.1. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ """ # Build pa...
'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOpt
ionsMiddleware', 'django.middleware.security.SecurityMiddleware', ) ROOT_URLCONF = 'sampleapp.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'djan...
mavlyutovrus/interval_index
python/graphs_9_hdfs_indices.py
Python
apache-2.0
5,475
0.009863
# -*- coding: utf-8 -*- import matplotlib.pyplot as plt import matplotlib from pylab import * import numpy from copy_reg import remove_extension from heapq import heappush from mpl_toolkits.axes_grid1 import host_subplot import mpl_toolkits.axisartist as AA colors = ["red", "green", "blue", "orange", "brown", "black",...
t_zorder(1) ylabel = plt.ylabel("Time
per one query [ms]") ylabel.set_fontsize(font_size) xlabel = plt.xlabel("Queries count x1000") xlabel.set_fontsize(font_size) for ytick in plt.yticks()[1]: ytick.set_fontsize(font_size) for xtick in plt.xticks()[1]: xtick.set_fontsize(font_size) if 1: ...
n2o/chicken-roulette
chickenrun.py
Python
mit
4,411
0.004307
#!/usr/bin/env python3 import pyglet from random import shuffle, randint import sys import math import time from threading import Thread import resources from board import Board from chicken import Chicken # Prepare winner screen trigger_winner = False STATE = "intro" player = pyglet.media.Player() def show_winner...
erval(update, 1/120.0) def play_movie(): """ Prepare video and start it """ global player vidPath = "chickenrun.mp4"
source = pyglet.media.StreamingSource() MediaLoad = pyglet.media.load(vidPath) player.queue(MediaLoad) player.eos_action = player.EOS_STOP player.on_player_eos = video_finished player.on_eos = video_finished time.sleep(1) player.play() def upda...
CiscoSystems/os-sqe
lab/nodes/asr.py
Python
apache-2.0
393
0.002545
from lab.nodes import LabNode class Asr(LabNode): def cmd(self, command): from fabric.api import settings, run with settings(host_string='{user}@{ip}'.format(user=self._username, ip=self._ip), password=self._password, connection_attempts=50, warn_only=False):
return run(command, shell=False) def configure_for_osp7(self, topology):
return None
devsenexx/gtxamqp
gtxamqp/utils.py
Python
mit
245
0
from StringIO import StringIO def format_failure(failure): """ get formatted failure :param failure: An instance of a twisted failure """ tb_txt = StringIO(
) failure.printTraceback(tb_txt) return tb_txt.getvalue()
tysonclugg/django
tests/template_tests/test_logging.py
Python
bsd-3-clause
4,731
0.001057
import logging from django.template import Context, Engine, Variable, VariableDoesNotExist from django.test import SimpleTestCase, ignore_warnings from django.utils.deprecation import RemovedInDjango21Warning class TestHandler(logging.Handler): def __init__(self): super().__init__() self.log_reco...
= True @property def template_name(self): return "template_name" @property def template(self): return Engine().from_string('') @property def article(self): raise TestObject.SilentDoesNotExist("Att...
ibute does not exist.") def __iter__(self): return iter(attr for attr in dir(TestObject) if attr[:2] != "__") def __getitem__(self, item): return self.__dict__[item] Variable('article').resolve(TestObject()) self.assertEqual( self.t...
Harold2017/myfirstflasky
app/chart/views.py
Python
mit
2,433
0.004932
from flask import render_template, flash, redirect, url_for, request from flask_login import login_required, current_user from ..models import User, Sensors, Sensor_data from . import chart from pytz import timezone # import pygal from pyecharts import Line import os from ..main.forms import SelectMultipleSensorForm t...
tipleSensorForm(sensors, prefix="sensorform") valid = 0 if form.validate_on_submit(): options = form.sensor.data line = Line(width=800, height=400) for sensor in options: sensor_data = Sensor_data.query.filter_by(sensor_id=sensor).order_by(-Sensor_dat...
nfo=utc).astimezone(tzchina).strftime('%Y/%m/%d-%H:%M:%S')) data.append(i.value) if len(data) is 0: no_sensor = 0 return render_template('no_sensor_dat.html', no_sensor=no_sensor) else: s = Sensors.query.filt...
robclark/chromium
tools/isolate/trace_inputs_test.py
Python
bsd-3-clause
5,097
0.006082
#!/usr/bin/env python # Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import cStringIO import logging import os import unittest import sys FILE_NAME = os.path.abspath(__file__) ROOT_DIR = os.path.dirn...
ef test_sig_unexpected(self): lines = [ '27 exit_group(0)
= ?', ] try: self._test_lines(lines, [], []) self.fail() except KeyError, e: self.assertEqual(27, e.args[0]) if __name__ == '__main__': VERBOSE = '-v' in sys.argv logging.basicConfig(level=logging.DEBUG if VERBOSE else logging.ERROR) unittest.main()
Azure/azure-sdk-for-python
sdk/agrifood/azure-mgmt-agrifood/azure/mgmt/agrifood/operations/_locations_operations.py
Python
mit
5,027
0.004376
# 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 ...
ype: Dict[str, Any] body_content = self._serialize.body(body, 'CheckNameAvailabilityRequest') body_content_kwargs['content'] = body_content request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = self._client._pipeline.run(request,...
in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = s...
nils-tekampe/duplicity
duplicity/backends/gdocsbackend.py
Python
gpl-2.0
8,939
0.003356
# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*- # # Copyright 2011 Carlos Abalde <carlos.abalde@gmail.com> # # This file is part of duplicity. # # Duplicity 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 Foundat...
% (source_path.get_filename(), self.folder.title.text)) assert not file.close() def _get(self, remote_filename, local_path): entries = self._fetch_entries(self.folder.resource_id.text, GDocsBackend.BACKUP_DOCUMENT_TYPE, ...
es) == 1: entry = entries[0] self.client.DownloadResource(entry, local_path.name) else: raise BackendException("Failed to find file '%s' in remote folder '%s'" % (remote_filename, self.folder.title.text)) def _list(self): entrie...
missionpinball/mpf
mpf/platforms/p_roc.py
Python
mit
22,477
0.001691
"""Contains the drivers and interface code for pinball machines which use the Multimorphic R-ROC hardware controllers. This code can be used with P-ROC driver boards, or with Stern SAM, Stern Whitestar, Williams WPC, or Williams WPC95 driver boards. Much of this code is from the P-ROC drivers section of the pyprocgam...
ort PDBConfig, PROCBasePlatform from mpf.core.utility_functions import Util from mpf.platforms.p_roc_devices import PROCDriver MYPY = False if MYPY: # pragma: no cover from mpf.core.machine import MachineController # pylint:
disable-msg=cyclic-import,unused-import class PRocHardwarePlatform(PROCBasePlatform, DmdPlatform, SegmentDisplaySoftwareFlashPlatform): """Platform class for the P-ROC hardware controller. Args: ---- machine: The MachineController instance. """ __slots__ = ["dmd", "alpha_display", "aux_...
lesina/labs2016
Laba04/task_18.py
Python
gpl-3.0
862
0.016241
#!/usr/bin/p
ython3 from pyrob.api import * @task def task_8_28(): if wall_is_above() != True: while (wall_is_above() != True): move_up() while (wall_is_on_the_left() != True): move_left() while(wall_is_on_the_right(
) != True and wall_is_beneath() and wall_is_above()): move_right() if wall_is_above() != True: while (wall_is_above() != True): move_up() while(wall_is_on_the_left() != True): move_left() while (wall_is_on_the_left() != True and wall_is_beneath...
LostProperty/wsgiappversion
wsgiappversion/__init__.py
Python
mit
62
0
from .b
ase import ApplicationVersion, package_versi
on # noqa
rspavel/spack
var/spack/repos/builtin/packages/py-requests-toolbelt/package.py
Python
lgpl-2.1
807
0.004957
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See t
he top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class PyRequestsToolbelt(PythonPackage): """A toolbelt of useful classes and functions to be used with python-requests""" homepage = "https://toolbelt.readthedocs.org/" url = "https://p...
.tar.gz" version('0.9.1', sha256='968089d4584ad4ad7c171454f0a5c6dac23971e9472521ea3b6d49d610aa6fc0') version('0.8.0', sha256='f6a531936c6fa4c6cfce1b9c10d5c4f498d16528d2a54a22ca00011205a187b5') depends_on('py-setuptools', type='build') depends_on('py-requests@2.0.1:2.999', type=('build', 'run'))
grantmcconnaughey/django-reports
djreports/__init__.py
Python
bsd-3-clause
51
0
__v
ersion__ = '0.
1.0' from .reports import Report
dlacy/spark_playground
libguides/0_harvest.py
Python
unlicense
1,710
0.004094
import json import urllib import urllib.request from http.cookiejar import CookieJar import requests import html import re import time from pyspark.sql import SparkSession, Row from pyspark.sql.types import StructType, StructField, IntegerType, StringType def get_guide(url): import requests
try: response = requests.get(url, allow_redirects=False) if response.status_cod
e == 200: # Try to get the data and json.load it 5 times, then give up tries = 5 while tries >= 0: try: print(" ---------- trying: ", url) content = response.text return content except: ...
xijunlee/leetcode
382.py
Python
mit
1,001
0.007992
#!/usr/bin/env python # coding=utf-8 # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None import random
class Solution(object): def __init__(self, head): """ @param head The linked list's head. Not
e that the head is guaranteed to be not null, so it contains at least one node. :type head: ListNode """ self.head = head k = 0 tmp = head while tmp: k += 1 tmp = tmp.next self.length = k def getRandom(self): """ ...
Comunitea/CMNT_00098_2017_JIM_addons
partner_consolidate/models/__init__.py
Python
agpl-3.0
184
0.005464
# -*- coding: ut
f-8 -*- # © 2016 Comunitea - Javier Colmenero <javier@comunitea.com> # License AGPL-3 - See http://www.gnu.org/li
censes/agpl-3.0.html import res_partner import account
dubrayn/dubrayn.github.io
examples/multiprocessing/client.py
Python
mit
289
0.010381
#!/usr/b
in/env python3 from multiprocessing.managers import BaseManager class QueueManager(BaseManager): pass QueueManager.register('get_queue') m = QueueManager(address=('127.0.0.1', 50000), authkey=b'abracadabra') m.connect() queue = m.get_queue() queue.put('hell
o') print(queue.get())
lmcinnes/pynndescent
pynndescent/sparse_nndescent.py
Python
bsd-2-clause
10,204
0.003038
# Author: Leland McInnes <leland.mcinnes@gmail.com> # Enough simple sparse operations in numba to enable sparse UMAP # # License: BSD 3 clause from __future__ import print_function import locale import numpy as np import numba from pynndescent.utils import ( tau_rand_int, make_heap, new_build_candidates, ...
bose: print("\t", n + 1, " / ", n_iters) (new_candidate_neighbors, old_candidate_neighbors) = new_build_candidates( current_graph, max_candidates, rng_state, n_threads ) c = 0 for i in ran
ge(n_blocks + 1): block_start = i * block_size block_end = min(n_vertices, (i + 1) * block_size) new_candidate_block = new_candidate_neighbors[block_start:block_end] old_candidate_block = old_candidate_neighbors[block_start:block_end] dist_thresholds = curren...
TheLazyHase/dragon_dice_simulator
business/dice/face/missile_with_special/bullseye.py
Python
gpl-3.0
1,129
0.003543
# -*- coding: utf-8 *-* # Copyright (c) 2013 Tisserant Pierre # # This file is part of Dragon dice simulator. # # Dragon dice simulator is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General
Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Dragon dice simulator is distribut
ed 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 Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # alon...
diefenbach/django-lfs
lfs/integrationtests/wmtests.py
Python
bsd-3-clause
1,998
0.002503
import os from django.conf import settings from windmill.authoring import djangotest from lfs.core.models import Shop from lfs.catalog.models import Product class CartPriceIntegrationTest(djangotest.WindmillDjangoUnitTest): test_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'windmilltests', 'gr...
UG = True so that our static content gets server settings.
DEBUG = True fixtures = ['lfs_price_test.xml'] def setUp(self): # Our data is loaded from fixtures self.assertEqual(1, Shop.objects.count()) # Check that apple is using GrossPriceCalculator apple = Product.objects.get(slug='apple') self.assertEqual('lfs.net_price.NetPri...
fsbayer/staply
staply/__init__.py
Python
gpl-2.0
1,227
0.000815
# ------------------------------------------------------------------------------------------------ # Software: Stem Applier (staply) # Description: Applies inflections to stem morphemes # Version: 0.0.1a # Module: Main # # Author: Frederic Bayer # Email: f.bayer@computer.org # Institu...
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 PURPOS
E. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-13SA. # ---------------------------------------------------...
CIGIHub/greyjay
greyjay/articles/migrations/0049_articlelistpage_filter_for_interviews.py
Python
mit
431
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('articles', '0048_articlepage_interview'), ] operations = [ migrations.AddField( model_name='articlelistpage', ...
name=
'filter_for_interviews', field=models.BooleanField(default=False), ), ]
aptana/Pydev
tests/org.python.pydev.refactoring.tests/src/python/codegenerator/generatedocstring/testGenerateDocstringRangeSelected.py
Python
epl-1.0
324
0.024691
class Test(object): def method(self): print "method" def ##|nested(): print "nes
ted"##| nested() ##r class Test(object): def method(self): print "method" def nested(): ''' ##| ''' print
"nested" nested()
x75/mavlink
pymavlink/mavutil.py
Python
lgpl-3.0
36,824
0.005893
#!/usr/bin/env python ''' mavlink python utility functions Copyright Andrew Tridgell 2011 Released under GNU GPL version 3 or later ''' import socket, math, struct, time, os, fnmatch, array, sys, errno from math import * from mavextra import * if os.getenv('MAVLINK09') or 'MAVLINK09' in os.environ: import mavlin...
0''' return not 'MAVLINK09' in os.environ def evaluate_expression(expression, vars): '''evaluation an expression''' try: v = eval(expression, globals(), vars) except NameError: return None
except ZeroDivisionError: return None return v def evaluate_condition(condition, vars): '''evaluation a conditional (boolean) statement''' if condition is None: return True v = evaluate_expression(condition, vars) if v is None: return False return v mavfile_global = ...
Tomcuzz/OctaHomeAutomation
OctaHomeDeviceInput/models.py
Python
mit
1,014
0.023669
from django.db import models from OctaHomeCore.models import * class ButtonInputDevice(InputDevice): ButtonOneAction = models.ForeignKey('OctaHomeCore.TriggerEvent', related_name="oneButtonActions", blank=True, null=True, on_dele
te=models.SET_NULL) ButtonTwoAction = models.ForeignKey('OctaHomeCore.TriggerEvent', related_name="twoButtonActions", blank=True, null=True, on_delete=models.SE
T_NULL) class Meta: db_table = u'ButtonInputDevice' class MotionInputDevice(InputDevice): TriggerAction = models.ForeignKey('OctaHomeCore.TriggerEvent', related_name="motionActions", blank=True, null=True, on_delete=models.SET_NULL) WaitTime = models.IntegerField() # in seconds TimeOutTaskCeleryId = models.Tex...
epuzanov/ZenPacks.community.DellMon
ZenPacks/community/DellMon/migrate/removeOldDellReports.py
Python
gpl-2.0
1,108
0.008123
################################################################################ # # This program is part of the DellMon Zenpack for Zenoss. # Copyright (C) 2008, 2009, 2010 Egor Puzanov. # # This program can be used under the GNU General Public License version 2 # You can find full information here: http://www.zenoss....
te import Version class removeOldDellReports(ZenPackMigration): version = Version(2, 3) def migrate(self, pack): if hasattr(pack.dmd.Reports, 'Device Reports'): devReports = pack.dmd.Reports['Device Reports'] if hasattr(devReports, 'Dell DRAC Controllers'): dev...
rollers') if hasattr(devReports, 'Dell Storage Controllers'): devReports._delObject('Dell Storage Controllers') removeOldDellReports()
gem/oq-engine
openquake/hazardlib/gsim/arroyo_2010.py
Python
agpl-3.0
9,135
0.00635
# -*- coding: utf-8 -*- # vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright (C) 2014-2022 GEM Foundation # # OpenQuake 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 Licen...
0.3930 0.0150 0.3673 -0.0264 0.7292 0.4419 0.5800 0.400 0.2735 1.1533 0.4067 0.0134 0.3956 -0.0317 0.7272 0.4574 0.5653 0.450 0.0990 1.1662 0.4127 0.0117 0.3466 -0.0267 0.7216 0.4249 0.5833 0.500 -0.0379 1.2206 0.4523 0.0084 0.3519 -0.0338 0.7189 0.4265 0.5788 0.550 -...
0.650 -0.6673 1.2995 0.4785 0.0051 0.3361 -0.0192 0.7065 0.4096 0.5756 0.700 -0.7154 1.3263 0.5068 0.0034 0.3200 -0.0243 0.7070 0.3999 0.5830 0.750 -0.7015 1.2994 0.5056 0.0029 0.3364 -0.0122 0.7092 0.4113 0.5778 0.800 -0.8581 1.3205 0.5103 0.0023 0.3164 -0.0337 0.6974 ...
gw0/myhdl
myhdl/_traceSignals.py
Python
lgpl-2.1
7,071
0.005233
# This file is part of the myhdl library, a Python package for using # Python as a Hardware Description Language. # # Copyright (C) 2003-2008 Jan Decaluwe # # The myhdl library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public License as # published by t...
%s %s(%i) $end" % (w, s._code, n, memindex), file=f) else: print("$var real 1 %s %s(%i) $end" % (s._code, n, memindex), file=f) memindex += 1 print("$upscope $end", file=f) for i in range(curlevel): print(
"$upscope $end", file=f) print(file=f) print("$enddefinitions $end", file=f) print("$dumpvars", file=f) for s in siglist: s._printVcd() # initial value print("$end", file=f)
vpetersson/docker-py
tests/unit/api_build_test.py
Python
apache-2.0
5,217
0
import gzip import io import docker from docker import auth from .api_test import BaseAPIClientTest, fake_request, url_prefix class BuildTest(BaseAPIClientTest): def test_build_container(self): script = io.BytesIO('\n'.join([ 'FROM busybox', 'RUN mkdir -p /tmp/test', ...
eaders_with_dict_and_no_auth_configs(self): headers = {'foo': 'bar'} expected_headers = { 'foo': 'bar' } self.client._set_auth_headers(headers) self.asse
rtEqual(headers, expected_headers)
Erotemic/local
depricated/speech/Examples/notepad_example.py
Python
gpl-3.0
2,882
0.004511
# # This file is part of Dragonfly. # (c) Copyright 2007, 2008 by Christo Butcher # Licensed under the LGPL. # # Dragonfly is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published # by the Free Software Foundation, either version 3 of the...
POSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with Dragonfly. If not, see # <http://www.gnu.org/licenses/>. # """ This module is a simple example of Dragonfly use. It shows how to use Dragon...
Natlink macros by placing it in the "My Documents\Natlink folder" or "Program Files\NetLink/MacroSystem". """ from dragonfly import (Grammar, AppContext, MappingRule, Dictation, Key, Text) #--------------------------------------------------------------------------- # Create this module...
Punto0/rcc
website_purchase_collective/controllers/main.py
Python
agpl-3.0
40,168
0.007718
# -*- coding: utf-8 -*- import werkzeug import logging import pprint from urlparse import urlparse, parse_qs from openerp import SUPERUSER_ID from openerp import http from openerp.http import request from openerp.tools.translate import _ from openerp.addons.website.models.website import slug from openerp.addons.web.con...
PPR] = { 'p
roduct': p, 'x':x, 'y': y, 'class': " ".join(map(lambda x: x.html_class or '', p.website_style_ids)) } if index<=PPG: maxy=max(maxy,y+(pos/PPR)) index += 1 # Format table according to HTML needs rows = self.table.items() rows.s...
jmcnamara/XlsxWriter
xlsxwriter/test/comparison/test_chart_line05.py
Python
bsd-2-clause
1,358
0
############################################################################### # # Tests for XlsxWriter. # # SPDX-License-Identifier: BSD-2-Clause # Copyright (c), 2013-2022, John McNamara, jmcnamara@cpan.org # from ..excel_comparison_test import ExcelComparisonTest from ...workbook import Workbook class TestCompar...
by Excel. """ def setUp(self): self.set_filename('chart_line05.xlsx') def test_create_file(self): """Test the creation o
f a simple XlsxWriter file.""" workbook = Workbook(self.got_filename) worksheet = workbook.add_worksheet() chart = workbook.add_chart({'type': 'line', 'subtype': 'stacked'}) chart.axis_ids = [108321408, 108634112] data = [ [1, 2, 3, 4, 5], [2, 4, 6, 8,...
xieta/mincoin
qa/rpc-tests/invalidblockrequest.py
Python
mit
4,319
0.00301
#!/usr/bin/env python3 # Copyright (c) 2015-2016 The Bitcoin Core developers # Copyright (c) 2015-2019 The Mincoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. from test_framework.test_framework import Compariso...
merkle root and blockheader unchanged but invalidate the block. ''' block2 = create_block(self.tip, create_coinbase(height), self.block_time) self.block_time += 1 # b'0x51' is OP_TRUE tx1 =
create_transaction(self.block1.vtx[0], 0, b'\x51', 50 * COIN) tx2 = create_transaction(tx1, 0, b'\x51', 50 * COIN) block2.vtx.extend([tx1, tx2]) block2.hashMerkleRoot = block2.calc_merkle_root() block2.rehash() block2.solve() orig_hash = block2.sha256 block2_ori...
JacekKarnasiewicz/HomePage
apps/tree_traversal/admin.py
Python
mit
124
0
from django.contri
b import admin from .models import Catalog, Item admin.site.register(Catalog) a
dmin.site.register(Item)
rmk135/objects
tests/unit/providers/test_dict_py2_py3.py
Python
bsd-3-clause
8,060
0.000248
"""Dependency injector dict provider unit tests.""" import sys import unittest from dependency_injector import providers class DictTests(unittest.TestCase): def test_is_provider(self): self.assertTrue(providers.is_provider(providers.Dict())) def test_provided_instance_provider(self): prov...
): provider = providers.Dict() \ .add_kwargs(a1='i1') \ .add_kwargs(a2='i2') self.assertEqual(provider.kwargs, {'a1': 'i1', 'a2': 'i2'}) def test_add_kwargs_non_string_keys(self): a1 = object() a2 = object() provider = providers.Dict() \ ....
l(provider.kwargs, {a1: 'i1', a2: 'i2'}) def test_add_kwargs_string_and_non_string_keys(self): a2 = object() provider = providers.Dict() \ .add_kwargs(a1='i1') \ .add_kwargs({a2: 'i2'}) self.assertEqual(provider.kwargs, {'a1': 'i1', a2: 'i2'}) def test_set_kwarg...
compatibleone/accords-platform
pyaccords/pysrc/ec2instanceinfo.py
Python
apache-2.0
13,279
0.001958
############################################################################## #copyright 2013, Hamid MEDJAHED (hmedjahed@prologue.fr) Prologue # #Licensed under the Apache License, Version 2.0 (the "License"); # #you may not use this file
except in compliance with the License. # #You may obtain a copy of the License at # #
# # http://www.apache.org/licenses/LICENSE-2.0 # # # #Unless required by applicable law or agreed to in writing, software # #distributed under the License is distributed on an "AS IS" BASIS...
andreaso/ansible
lib/ansible/modules/monitoring/icinga2_feature.py
Python
gpl-3.0
4,541
0.003083
#!/usr/bin/python # -*- coding: utf-8 -*- """ Ansible module to manage Icinga2 feature state (c) 2016, Loic Blot <loic.blot@unix-experience.fr> Sponsored by Infopro Digital. http://www.infopro-digital.com/ Sponsored by E.T.A.I. http://www.etai.fr/ This file is part of Ansible Ansible is free software: you can redi...
"Ensure icinga2 is installed and present in binary path.") else: # If feature is alr
eady in good state, just exit if re.search("Disabled features:.* %s[ \n]" % self.module.params["name"], out) \ and self.module.params["state"] == "absent" or \ re.search("Enabled features:.* %s[ \n]" % self.module.params["name"], out) \ and self.mo...
ericawright/bedrock
tests/pages/firefox/whatsnew/whatsnew_73.py
Python
mpl-2.0
595
0
# This Sourc
e 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/. from selenium.webdriver.common.by import By from pages.base import BaseP
age class FirefoxWhatsNew73Page(BasePage): URL_TEMPLATE = '/{locale}/firefox/73.0/whatsnew/all/{params}' _set_default_button_locator = (By.ID, 'set-as-default-button') @property def is_default_browser_button_displayed(self): return self.is_element_displayed(*self._set_default_button_locator...
optiflows/tukio
tests/test_workflow.py
Python
apache-2.0
7,788
0
import asyncio from unittest import TestCase from tukio.task import register, TaskHolder, tukio_factory from tukio.utils import FutureState from tukio.workflow import Workflow, WorkflowTemplate @register('basic', 'execute') class BasicTask(TaskHolder): async def execute(self, event): pass @register('cr...
onfig['init_ok'] async def execute(self, event): # Or crash here raise Exception @register('cancel', 'execute') class CancelTask(TaskHolder): async def execute(self, event): Workflow.current_workflow().cancel() await asyncio.sleep(1.0) @register('sleep', 'execute') class Sl...
e': 'ok', 'tasks': [ {'id': '1', 'name': 'basic'}, {'id': '2', 'name': 'basic'}, {'id': '3', 'name': 'basic'}, {'id': '4', 'name': 'basic'}, ], 'graph': { '1': ['2', '3'], '2': ['4'], '3': [], '4': []...