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
ncmatson/OSTE
app/views.py
Python
mit
2,380
0.006723
from app import app, grabber, merge, segment from flask import render_template, request, url_for, jsonify import cv2 import numpy as np import os, re def rm(dir, pattern): for f in os.listdir(dir): if re.search(pattern, f): os.remove(os.path.join(dir, f)) @app.route('/') @app.route('/index') d...
dg'+time+'.png') smart_areas = segment.get_areas(smart_contours.values()) # 'dumb' meanas that the segment
ation was on the original image dumb_contours = segment.dumb_contours('app/static/img/dg'+time+'.png','app/static/img/dumy_dg'+time+'.png') dumb_areas = segment.get_areas(dumb_contours.values()) # uses 'smart' locations to pick out contours in the 'dumb' image buildings = merge.intersect(smart_contours...
natano/python-git-orm
git_orm/serializer.py
Python
isc
1,101
0
import re import textwrap __all__ = ['dumps', 'loads'] SPLIT_ITEMS = re.compile(r'\n(?!\s)').split MATCH_ITEM = re.compile(r''' (?P<key>\w+): # key \s? (?P<value>.*?)$ # first line (?P<value2>.+)? # optional continuation line(s) ''', re.MULTILINE | re.DOTALL | re.VERBOSE).match def...
items(): comment = comments.get(k, None)
if comment: s += '# ' + '\n '.join(comment.splitlines()) + '\n' value = v or '' s += '{}: {}\n'.format(k, value.replace('\n', '\n ')) return s def loads(serialized): data = {} lineno = 0 for item in SPLIT_ITEMS(serialized): if not item.startswith('#') an...
samuelcolvin/aiohttp-devtools
aiohttp_devtools/runserver/utils.py
Python
mit
732
0.001366
class MutableValue: """ Used to avoid warnings (and in future errors) from aiohttp when the app context is modified. """ __slots__ = 'value', def __init__
(self, value=None): self.value = value def change(self, new_value): self.value = new_value def __len__(self): return len(self.value) def __repr__(self): return repr(self
.value) def __str__(self): return str(self.value) def __bool__(self): return bool(self.value) def __eq__(self, other): return MutableValue(self.value == other) def __add__(self, other): return self.value + other def __getattr__(self, item): return getattr...
PrasannaBarate/ExpenseTracker-Django
DailyExpenses/migrations/0001_initial.py
Python
apache-2.0
998
0.003006
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-06-06 06:33 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations...
ll=True)),
('user', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL)), ], ), ]
invisiblek/python-for-android
python3-alpha/python3-src/Lib/test/test_import.py
Python
apache-2.0
24,643
0.000203
import builtins import imp from importlib.test.import_ import test_relative_imports from importlib.test.import_ import util as importlib_util import marshal import os import py_compile import random import stat import sys import unittest import textwrap from test.support import ( EnvironmentVarGuard, TESTFN, check...
at.S_IRGRP | stat.S_IROTH | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)) __import__(TESTFN) fn = imp.cache_from_source(fname) if not os.path.exists(fn): self.fail("__import__ did not result in creation of " ...
o file") s = os.stat(fn) self.assertEqual( stat.S_IMODE(s.st_mode), stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH) finally: del sys.path[0] remove_files(TESTFN) unload(TESTFN)...
KyleKing/recipes
noxfile.py
Python
mit
139
0
"""nox-p
oetry configuration file.""" from calcipy.dev.noxfile
import build_check, build_dist, check_safety, coverage, tests # noqa: F401
klahnakoski/SpotManager
vendor/mo_math/hashes.py
Python
mpl-2.0
593
0
# 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 wa
s not distributed with this file, # You can obtain one at http://mozilla.org/MPL/2.0/. # # Contact: Kyle Lahnakoski (kyle@lahnakoski.com) # from __future__ import absolute_import, division, unicode_literals from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives.hashes import SHA2...
alesaccoia/chew-broadcaster
install-utils/release/osx/release_util.py
Python
gpl-2.0
13,845
0.004478
from xml.etree import ElementTree as ET def qn_tag(n, t): return { 'ce': str(ET.QName('http://catchexception.org/xml-namespaces/ce', t)), 'sparkle': str(ET.QName('http://www.andymatuschak.org/xml-namespaces/sparkle', t)) }[n] def create_channel(m): if m['stable']: return 'stable' ...
kage_type) ET.SubElement(item, 'title').text = title ET.SubElement(item, qn_tag('sparkle', 'releaseNotesLink')).text = '{0}/notes.html'.format(base_url) ET.SubElement(item, 'pubDate').text = formatdate() ET.SubElement(item, qn_tag('ce', 'packageType')).text = package_type if m['stable']: E...
e', 'deployed')).text = 'false' version = m['tag']['name'] else: version = m['jenkins_build'] ET.SubElement(item, 'enclosure', { 'length': str(os.stat(package_path).st_size), 'type': 'application/octet-stream', 'url': '{0}/{1}-{2}.zip'.format(base_url, user_version, pack...
sjsucohort6/openstack
python/venv/lib/python2.7/site-packages/neutronclient/tests/unit/vpn/test_cli20_ipsecpolicy.py
Python
mit
8,365
0
# (c) Copyright 2013 Hewlett-Packard Development Company, L.P. # 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...
args = [name, '--descr
iption', description, '--tenant-id', tenant_id, '--auth-algorithm', auth_algorithm, '--encryption-algorithm', encryption_algorithm, '--transform-protocol', transform_protocol, '--encapsulation-mode', encapsulation_mode, '--l...
tgbugs/hypush
hyputils/memex/db/mixins.py
Python
mit
548
0
# -*- coding: utf-8 -*- """Reusable mixins for SQLAlchemy declarative models.""" from __
future__ import unicode_literals import datetime import sqlalchemy as sa class Timestamps(object): created = sa.Column( sa.DateTime, default=datetime.datetime.utcnow, server_default=sa.func.now(), nullable=False, ) updated = s
a.Column( sa.DateTime, server_default=sa.func.now(), default=datetime.datetime.utcnow, onupdate=datetime.datetime.utcnow, nullable=False, )
andrewyoung1991/scons
test/Progress/spinner.py
Python
mit
2,151
0.00093
#!/usr/bin/env python # # __COPYRIGHT__ # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, ...
otice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANT
ABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE ...
ettrig/NIPAP
tests/upgrade-before.py
Python
mit
3,381
0.003253
#!/usr/bin/env python # # This is run by Travis-CI before an upgrade to load some data into the # database. After the upgrade is complete, the data is verified by # upgrade-after.py to make sure that the upgrade of the database went smoothly. # import logging import unittest import sys sys.path.insert(0, '..') sys.pat...
.32.0/24', 'reservation', 'test') p8 = th.add_prefix('192.168.32.1/32', 'reservation', 'test') ps1 = th.add_prefix('2001:db8:1::/48', 'reservation', 'test') ps2 = th.add_prefix('2001:db8:1::/64', 'reservation', 'test') ps3 = th.add_prefix('2001:db8:2::/48', 'reservation', 'test') ...
ength = 112 pool1.save() p2.pool = pool1 p2.save() ps1.pool = pool1 ps1.save() pool2 = Pool() pool2.name = 'upgrade-test2' pool2.save() vrf1 = VRF() vrf1.name = 'foo' vrf1.rt = '123:123' vrf1.save() if __name__ == '__ma...
gmr/tornado-elasticsearch
tornado_elasticsearch.py
Python
bsd-3-clause
46,402
0.000388
"""tornado_elasticsearch extends the official elasticsearch library adding asynchronous support for the Tornado stack. See http://elasticsearch-py.readthedocs.org/en/latest/ for information on how to use the API beyond the introduction for how to use with Tornado:: from tornado import gen from tornado import ...
t_timeout'] = self.request_timeout if self._auth_user and se
lf._auth_password: kwargs['auth_username'] = self._auth_user kwargs['auth_password'] = self._auth_password if body: kwargs['body'] = body if timeout: kwargs['request_timeout'] = timeout kwargs['allow_nonstandard_methods'] = True return kwa...
rbramwell/pulp
bindings/pulp/bindings/bindings.py
Python
gpl-2.0
3,641
0.003845
from pulp.bindings import auth, consumer, consumer_groups, repo_groups, repository from pulp.bindings.actions import ActionsAPI from pulp.bindings.content import OrphanContentAPI, ContentSourceAPI, ContentCatalogAPI from pulp.bindings.event_listeners import EventListenerAPI from pulp.bindings.server_info import ServerI...
"" # Please keep the following in alphabetical order to ease reading self.actions = ActionsAPI(pulp_connection) self.bind = consumer.BindingsAPI(pulp_connection) self.bindings = consumer.BindingSearchAPI(pulp_connection) self.profile = consumer.P
rofilesAPI(pulp_connection) self.consumer = consumer.ConsumerAPI(pulp_connection) self.consumer_content = consumer.ConsumerContentAPI(pulp_connection) self.consumer_content_schedules = consumer.ConsumerContentSchedulesAPI(pulp_connection) self.consumer_group = consumer_groups.ConsumerGro...
DemocracyClub/yournextrepresentative
ynr/apps/elections/tests/test_viewsets.py
Python
agpl-3.0
994
0
import mock from django.utils import timezone from rest_framework.test import APIRequestFactory from elections.api.next.api_views import BallotViewSet class TestBallotViewSet: def test_get_queryset_last_updated_ordered_by_modified(self): factory = APIRequestFactory() timestamp = timezone.now().i...
quest = factory.get("/next/ballots/", {"last_updated": timestamp}) request.query_params = request.GET view = BallotViewSet(request=request) view.queryset = mock.MagicMock() view.get_queryset() view.queryset.with_last_updated.assert_called_once() def test_get_queryset_last_...
t_ordered(self): factory = APIRequestFactory() request = factory.get("/next/ballots/") request.query_params = request.GET view = BallotViewSet(request=request) view.queryset = mock.MagicMock() view.get_queryset() view.queryset.with_last_updated.assert_not_called...
twatteyne/dustlink_academy
views/web/dustWeb/WebPageDyn.py
Python
bsd-3-clause
2,973
0.019509
import logging class NullHandler(logging.Handler): def emit(self, record): pass log = logging.getLogger('WebPage') log.setLevel(logging.ERROR) log.addHandler(NullHandler()) import os import web from viz import Viz import WebPage import WebHandler class WebHandlerDyn(WebHandler.WebHandler):...
username=username) def getDynPath(self): elems = WebPage.WebPage.urlStringTolist(web.ctx.path) for e in elems: if e.startswith('_'): return e[1:] class WebPageDyn(WebPage.WebPage): def __init__(self,subPageLister=Non...
# store params self.subPageLister = subPageLister self.subPageHandler = subPageHandler # initialize parent class WebPage.WebPage.__init__(self,**fvars) # register subPageHandler self.registerPage(WebPage.WebPage(webServer = self.web...
Horrendus/radiocontrol
api/api/admin.py
Python
agpl-3.0
820
0
# REST API Backend for the Radiocontrol Project # # Copyright (C) 2017 Stefan Derkits <stefan@derkits.at> # # 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...
n. # # 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 should have received a copy of the GNU Affero General Public Lice...
u.org/licenses/>. from django.contrib import admin # Register your models here.
scality/manila
manila_tempest_tests/tests/api/admin/test_share_types_negative.py
Python
apache-2.0
4,282
0
# Copyright 2014 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...
red_extra
_specs_to_dict({"key": "value"}) return self.create_share_type(name, extra_specs=extra_specs) @classmethod def resource_setup(cls): super(ShareTypesAdminNegativeTest, cls).resource_setup() cls.member_shares_client = clients.Manager().shares_client @test.attr(type=["gate", "smoke", ...
ESOedX/edx-platform
lms/djangoapps/grades/tests/test_course_data.py
Python
agpl-3.0
4,628
0.003025
""" Tests for CourseData utility class. """ from __future__ import absolute_import import six from mock import patch from lms.djangoapps.course_blocks.api import get_course_blocks from openedx.core.djangoapps.content.block_structure.api import get_course_in_cache from student.tests.factories import UserFactory from x...
duleStoreEnum.Type.split): self.course = CourseFactory.create() # need to re-retrieve the course since the version on the original course isn't accurate. self.course = self.store.get_course(self.course.id) self.user = UserFactory.create() self.collected_structure = ge...
in_cache(self.course.id) self.one_true_structure = get_course_blocks( self.user, self.course.location, collected_block_structure=self.collected_structure, ) self.expected_results = { 'course': self.course, 'collected_block_structure': self.collected_structure,...
tiramiseb/abandoned_calaos-web-installer
calaosapi.py
Python
agpl-3.0
1,520
0.001974
# Copyright 2014 Sebastien Maccagnoni-Munch # # This file is part of Calaos Web Installer. # # Calaos Web Installer 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 Li
cense, # or (at your option) any later version. # # Calaos Web Installer 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 Affero General Public License for more details. # #...
received a copy of the GNU Affero General Public License # along with Calaos Web Installer. If not, see <http://www.gnu.org/licenses/>. import os.path import pickle class CalaosApi: def __init__(self, io, rules): self.io_path = io self.rules_path = rules self.readfiles() def readfi...
yanikou19/pymatgen
fabfile.py
Python
mit
4,544
0.001761
""" Deployment file to facilitate releases of pymatgen. Note that this file is meant to be run from the root directory of the pymatgen repo. """ __author__ = "Shyue Ping Ong" __email__ = "ongsp@ucsd.edu" __date__ = "Sep 1, 2014" import glob import os import json import webbrowser import requests import re import subp...
) with open(filepath, "w") as
f: f.write("Release") def release(skip_test=False): setver() if not skip_test: local("nosetests") publish() log_ver() update_doc() merge_stable() release_github() def open_doc(): pth = os.path.abspath("docs/_build/html/index.html") webbrowser.open("file://" + pth)...
M157q/django-localflavor
tests/test_is.py
Python
bsd-3-clause
9,213
0.000543
from __future__ import unicode_literals from django.test import SimpleTestCase from localflavor.is_.forms import (ISIdNumberField, ISPhoneNumberField, ISPostalCodeSelect) class ISLocalFlavorTests(SimpleTestCase): def test_ISPostalCodeSelect(self): f = ISPostalCodeSelec...
15">415 Bolungarv\xedk</option> <option value="420">420 S\xfa\xf0av\xedk</option> <option value="425">425 Flateyri</option> <option value="430">430 Su\xf0ureyri</option> <option value="450">450 Patreksfj\xf6r\xf0ur</option> <option value="451">451 Patreksfj\xf6r\xf0ur</option> <option value="460">460 T\xe1lknafj\xf6r\x...
dudalur</option> <option value="470">470 \xdeingeyri</option> <option value="471">471 \xdeingeyri</option> <option value="500">500 Sta\xf0ur</option> <option value="510">510 H\xf3lmav\xedk</option> <option value="512">512 H\xf3lmav\xedk</option> <option value="520">520 Drangsnes</option> <option value="522">522 Kj\xf6r...
Michael-F-Bryan/spider_board
spider_board/gui.py
Python
mit
5,607
0.003389
import tkinter as tk from tkinter.filedialog import askdirectory from tkinter.messagebox import showwarning, showerror, showinfo from tkinter import ttk import logging import sys from threading import Thread from spider_board.client import Browser from spider_board.utils import time_job, LOG_FILE, get_logger, humansiz...
olumn=2) self.username = tk.StringVar() self.username_box = ttk.Entry(self.main_frame, textvariable=self.username) self.username_box.grid(row=0, column=3, sticky='nsew') # Make the password label and box ttk.Label(self.main_frame, text='Password:').grid(row=1, ...
me, textvariable=self.password) self.password_box.grid(row=1, column=3, sticky='nsew') # Make the savefile label and box self.savefile_btn = ttk.Button(self.main_frame, text='Browse', command=self.ask_find_directory) self.savefile_btn.grid(row=2, column=...
deklungel/iRulez
old/modules/discovery/discovery.py
Python
mit
1,800
0.012222
#!/usr/bin/env python import sys sys.path.append('/var/www/html/modules/libraries') import avahi import dbus from time import sleep import mysql.connector file = open('/var/www/html/config.php', 'r') for line in file: if "db_name" in line: MySQL_database = line.split('"')[3] elif "db_user" in line: MySQL_us...
r: def __init__(self, name, service, port, txt): bus = dbus.SystemBus() server = dbus.Interface(bus.get_object(avahi.DBUS_NAME, avahi.DBUS_PATH_SERVER), avahi.DBUS_INTERFACE_SERVER) group = dbus.Interface(bus.get_object(avahi.DBUS_NAME, server.EntryGroupNew()),
avahi.DBUS_INTERFACE_ENTRY_GROUP) self._service_name = name index = 1 while True: try: group.AddService(avahi.IF_UNSPEC, avahi.PROTO_INET, 0, self._service_name, service, '', '', port, avahi.string_array_to_txt_array(txt)) except dbu...
eayunstack/python-neutronclient
neutronclient/tests/functional/core/test_readonly_neutron.py
Python
apache-2.0
6,814
0.000294
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # d...
firewall_list = self.parser.listing(self.neutron ('firewall-list')) self.assertTableStruct(firewall_list, ['id', 'name', 'firewall_policy_id']) def test_neutron_firewall_policy_list(self): firewall_pol...
'firewall_rules']) def test_neutron_firewall_rule_list(self): firewall_rule = self.parser.listing(self.neutron ('firewall-rule-list')) self.assertTableStruct(firewall_rule, ['id', 'name', ...
Tomcuzz/OctaHomeAutomation
OctaHomeTempControl/OctaFiles/urls.py
Python
mit
1,656
0.019324
from OctaHomeCore.OctaFiles.urls.base import * from OctaH
omeTempControl.views import * class TempControlOctaUrls(OctaUrls): @classmethod def getUrls(cls): return [ url(r'^TempControl/command/(?P<command>\w+)/$', handleTempCommand.as_view(), name='TempControlCommandWithOutDevice'), url(r'^Te
mpControl/command/(?P<command>\w+)/(?P<deviceType>\w+)/(?P<deviceId>\d+)/$', handleTempCommand.as_view(), name='TempControlCommand'), url(r'^TempControl/command/(?P<command>\w+)/(?P<house>\w+)/(?P<deviceType>\w+)/(?P<deviceId>\d+)/$', handleTempCommand.as_view(), name='TempControlCommand'), url(r'^TempControl/com...
libuparayil/networking-huawei
networking_huawei/tests/unit/drivers/ac/client/test_restclient.py
Python
apache-2.0
11,844
0
# Copyright (c) 2016 Huawei Technologies India Pvt Ltd # 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 #...
methodname, headers={'Content-type': 'application/json', 'Accept': 'application/json'}, timeout=float(cfg.CONF. huawei_ac_config. ...
wei_ac_config.password), **kwargs) def test_rc_process_request_timeout_exception(self): methodname = 'DELETE' url = '/controller/dc/esdk/v2.0/test_url' auth = (cfg.CONF.huawei_ac_config.username, cfg.CONF.huawei_ac_config.password) headers = {'Acc...
alexander-bzikadze/graph_diff
tests/graph/test_graph_with_repetitive_nodes_with_root.py
Python
apache-2.0
1,211
0.000826
import unittest from graph_diff.graph
import rnr_graph, lr_node from graph_diff.graph.graph_with_repetitive_nodes_exceptions import GraphWithRepetitiveNodesKeyError class GraphWithRepetitiveNodesWithRootTest(unittest.TestCase): def setUp(self): self.test_graph = rnr_graph() def test_add_node(self): self.assertFalse(lr_node(1, 1)...
tFalse(lr_node(1, 1) in self.test_graph) self.assertFalse(lr_node(1, 2) in self.test_graph) self.test_graph.add_edge(lr_node(1, 1), lr_node(1, 2)) self.assertTrue(lr_node(1, 1) in self.test_graph) self.assertTrue(lr_node(1, 2) in self.test_graph) def test_add_edge_exp(self): ...
armon/pypred
setup.py
Python
bsd-3-clause
1,228
0.002443
from setuptools import setup __version__ = "0.5.0" # G
et the long description
by reading the README try: readme_content = open("README.md").read() except: readme_content = "" # Create the actual setup method setup(name='pypred', version=__version__, description='A Python library for simple evaluation of natural language predicates', long_description=readme_content, ...
jbedorf/tensorflow
tensorflow/python/summary/summary.py
Python
apache-2.0
17,400
0.003333
# Copyright 2016 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...
, width, channels]` and where `channels` can be: * 1: `tensor` is interpreted as Grayscale. * 3: `tensor` is interpreted as RGB. * 4: `tensor` is interpreted as RGBA. The images have the same number of channels as the input tensor. For float input, the values are normalized one image at a time to fit in ...
values are all positive, they are rescaled so the largest one is 255. * If any input value is negative, the values are shifted so input value 0.0 is at 127. They are then rescaled so that either the smallest value is 0, or the largest one is 255. The `tag` in the outputted Summary.Value protobufs...
Ecotrust/PEW-EFH
mp/scenarios/widgets.py
Python
apache-2.0
4,479
0.014066
from django import forms from django.forms.widgets import * from django.utils.safestring import mark_safe from madrona.analysistools.widgets import SliderWidget, DualSliderWidget class AdminFileWidget(forms.FileInput): """ A FileField Widget that shows its current value if it has one. """ def __init__(...
ange:') output.append(super(AdminFileWidget, self).render(name, value, attrs)) #output.append("</p>") return mark_safe(u''.join(output)) class SliderWidgetWithTooltip(SliderWidget): def __init__(self, min, max, step, id): super(SliderWidgetWithTooltip, self).__init__(min, max, st...
, self).render(*args,**kwargs) img_id = self.id span_id = "%s_content" %self.id #grabbing flatblock outright as including the flatblock template tag in the output html resulted in a literal output of the template tag from flatblocks.models import FlatBlock try: flatb...
wdv4758h/ZipPy
edu.uci.python.benchmark/src/benchmarks/sympy/sympy/physics/mechanics/tests/test_functions.py
Python
bsd-3-clause
5,068
0.004144
from sympy import S, Integral, sin, cos, pi, sqrt, symbols from sympy.physics.mechanics import (Dyadic, Particle, Point, ReferenceFrame, RigidBody, Vector) from sympy.physics.mechanics import (angular_momentum, dynamicsymbols, inertia, inertia_of...
A = RigidBody('A', Ac, a, M, (I, Ac)) assert linear_momentum( N, A, Pa) == 2 * m * q1d* l1 * N.y + M * l1 * q1d * N.y assert angular_momentum( O, N, A, Pa) == 4 * m * q1d * l1**2 * N.z + q1d * N.z def test_kinetic_energy(): m, M, l1 = symbols('m M l1') omega = dynamicsymbols('omeg...
x) Ac = O.locatenew('Ac', l1 * N.x) P = Ac.locatenew('P', l1 * N.x) a = ReferenceFrame('a') a.set_ang_vel(N, omega * N.z) Ac.v2pt_theory(O, N, a) P.v2pt_theory(O, N, a) Pa = Particle('Pa', P, m) I = outer(N.z, N.z) A = RigidBody('A', Ac, a, M, (I, Ac)) assert 0 == kinetic_energy(...
ArchiveTeam/panoramio-discovery
discover.py
Python
unlicense
3,093
0.00097
'''Find valid tags and usernames. The file will contain things like: tag:12345:romance ''' import gzip import re import requests import string import sys import time import random DEFAULT_HEADERS = {'User-Agent': 'ArchiveTeam'} class FetchError(Exception): '''Custom error class when fetching does not meet our...
# Write the valid result one per line to the file line = '{0}\n'.format(shortco
de) gzip_file.write(line.encode('ascii')) gzip_file.close() print('Done') def check_range(start_num, end_num): '''Check if page exists. Each line is like tag:12345:romance ''' for num in range(start_num, end_num + 1): shortcode = num url = 'http://www.panoramio.com/...
wilblack/lilybot
rpi_client/bot_roles/local_settings_generic.py
Python
gpl-2.0
242
0.028926
""" Router.py uses bot_packages in this file to setup command and sensor value routing to the correct bot_role. """ settings= { "bot_name":"rp4.solalla.
ardyh", "bot_roles":"bot", "bot_packag
es":[], "subscriptions":[], }
Camiloasc1/AstronomyUNAL
CelestialMechanics/kepler/constants.py
Python
mit
503
0
from astropy i
mport units as u K_kepler = 0.01720209895 # ua^(3/2) m_{sun} d^(−1) K = 0.01720209908 * u.au ** (3 / 2) / u.d # ua^(3/2) d^(−1) UA = 149597870700 * u.m # m GM1 = 1.32712442099E20 * u.m ** 3 / u.s ** 2 # m^(3) s^(−2) # m1/m2 Mercury = 6023600 Venus = 408523.719 Earth_Moon = 328900.561400 Mars = 3098703.59 Jupiter...
00 Ceres = 2119000000 Palas = 9700000000 Vesta = 7400000000
umitproject/network-admin
netadmin/utils/charts/charttools.py
Python
agpl-3.0
2,781
0.010068
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2011 Adriano Monteiro Marques # # Author: Piotrek Wasilewski <wasi
lewski.piotrek@gmail.com> # # 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 program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # ME...
LBenzahia/cltk
cltk/stem/akkadian/stem.py
Python
mit
2,502
0.000402
""" Get the stem of a word, given a declined form and its gender. TODO: Check this logic with von Soden's Grundriss der akkadischen Grammatik. TODO: Deal with j/y issue. """ __author__ = ['M. Willis Monroe <willismonroe@gmail.com>'] __license__ = 'MIT License. See LICENSE.' ENDINGS = { 'm': { 'singular':...
ngular'].values()) + \ list(self.endings['m']['dual'].values()): stem = noun[:-2] else: print("Unknown feminine noun: {}".format(noun)) else: print("Unknown noun: {}".
format(noun)) return stem
CtopCsUtahEdu/chill-dev
examples/chill/testcases/include.script.py
Python
gpl-3.0
129
0.007752
from chill import * source('include.c') destination('includemodified.c') procedure('main') loop(0) original()
print_code()
doctorrabb/badtheme
detector.py
Python
gpl-3.0
949
0.036881
#!/usr/bin/python from sys import argv from mod
ules.helpers.wpdetector import WordpressDetector from modules.net.scan import is_good_response from modules.const import ERR, NO, OK, INFO def main (): if len (argv) > 1: print INFO + 'Checking site...' if not is_good_response (argv [1]): print ERR + 'Si
te is unavailable! :(' exit (-1) print INFO + 'Detecting wordpress...' wpd = WordpressDetector (argv [1]) if wpd.detect_by_pages (): print OK + 'Wordpress Detected!' if raw_input ('Try to detect Wordpress version? (y/n): ') == 'y': print INFO + 'Detecting Wordpress version...' dec = wpd.detect_...
steinarvk/rigour
rigour/tests/test_secrecy.py
Python
apache-2.0
1,198
0.012521
# Copyright 2015 Google 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, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, eith...
lied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import from rigour.errors import ValidationFailed from rigour.types import * from rigour.constraints import length_between import rigour import pytest def test_secrecy_declare...
hectorsanchez/acheckersgame
intro2.py
Python
gpl-2.0
274
0.007299
import pygame import intro import game class Intro2(intro.Intro): def load_image(self): self.
fondo = pygame.image.load('ima/intro2.png').convert() def go_
to_next(self): new_scene = game.Game(self.world) self.world.change_scene(new_scene)
jacksonwilliams/arsenalsuite
cpp/lib/PyQt4/examples/tutorial/t3.py
Python
gpl-2.0
367
0
#!/usr/bin/env python # PyQt tutorial 3 import s
ys from PyQt4 import QtGui app = QtGui.QApplication(sys.argv) window = QtGui.QWidget() window.resize(200, 120) quit = QtGui.QPushButton("Quit", window) quit.setFont(QtGui.QFont("Times", 18, QtGui.QFont.Bold)) quit.setGeometry(10, 40, 180, 40) quit.clicked.connec
t(app.quit) window.show() sys.exit(app.exec_())
ucsb-seclab/ictf-framework
scoring_ictf/scoring_ictf/game_state_interface.py
Python
gpl-2.0
943
0
class GameStateInterface(object): def __init__(self): self._team_ids_to_names = None self._service_ids_to_names = None def _team_id_to_name_map(self): raise NotImplemen
tedError def _service_id_to_name_map(self): raise NotImplementedError def _scored_events_for_tick(self, tick): raise NotImplementedError @property def team_id_to_name_map(self): if self._team_ids_to_names is None: self._team_ids_to_names = self._team_id_
to_name_map() return self._team_ids_to_names @property def service_id_to_name_map(self): if self._service_ids_to_names is None: self._service_ids_to_names = self._service_id_to_name_map() return self._service_ids_to_names def scored_events_for_tick(self, tick): ...
turbokongen/home-assistant
tests/components/wemo/entity_test_helpers.py
Python
apache-2.0
5,991
0.002838
"""Test cases that are in common among wemo platform modules. This is not a test module. These test methods are used by the platform test modules. """ import asyncio import threading from unittest.mock import patch from pywemo.ouimeaux_device.api.service import ActionException from homeassistant.components.homeassis...
oceed at the same time.""" await async_setup_component(hass, HA_DOMAIN, {}) update = _perform_async_update(hass, wemo_entity) await _async_multiple_call_helper( hass, pywemo_registry, wemo_entity, pywemo_device, update, update, **kwargs ) async def test_async_update_locked_multiple_callbacks( ...
tate updates do not proceed at the same time.""" await async_setup_component(hass, HA_DOMAIN, {}) callback = _perform_registry_callback(hass, pywemo_registry, pywemo_device) await _async_multiple_call_helper( hass, pywemo_registry, wemo_entity, pywemo_device, callback, callback, **kwargs ) asy...
Hofsmo/psse_models
setup.py
Python
gpl-3.0
223
0.004484
# -*- coding: utf-8 -*- """ Created on Wed Dec 14 14:10:41 2016 @author: s
igurdja """ from setuptools import setup, find_packages setup( name="
psse_models", version="0.1", packages=find_packages(), )
strfry/OpenNFB
protocols/2_ch_c3beta_c4smr_kro.py
Python
gpl-3.0
3,567
0.024951
# Thanks to Kurt Othmer for BioExplorer design this is translated from from flow import * class Flow(object): def init(self, context): ch1 = context.get_channel('Channel 1') #ch1 = Notch(50, input=ch1) ch1_dc = DCBlock(ch1).ac ch1_raw = BandPass(0.0, 40.0, input=ch1_dc) ch1_theta = BandPass(3.0, 7.0, inpu...
layout.addWidget(self.ch1_beta_threshold.widget(), 1, 1) layout.addWidget(self.ch1_hibeta_threshold.widget(), 1, 2) layout.addWidget(self.left_spectrum.widget(), 1, 3) layout.addWidget(self.ch2_osci.widget(), 0, 4, 1, 4) layout.addWidget(self.ch2_theta_threshold.widget(), 1, 5) layout.addWidget(self.ch2_...
old.widget(), 1, 6) layout.addWidget(self.ch2_hibeta_threshold.widget(), 1, 7) layout.addWidget(self.right_spectrum.widget(), 1, 4) return w def flow(): return Flow()
jgomezdans/grabba_grabba_hey
grabba_grabba_hey/sentinel3_downloader.py
Python
gpl-2.0
9,042
0.003981
#!/usr/bin/env python """ A simple interface to download Sentinel-1 and Sentinel-2 datasets from the COPERNICUS Sentinel Hub. """ from functools import partial import hashlib import os import datetime import sys import xml.etree.cElementTree as ET import re import requests from concurrent import futures import loggin...
requests.get(query, auth=(user, passwd), verify=False) if r.status_code == 200: return r.text else: raise IOError("Something went wrong! Error code %d" % r.status_code) def download_product(source, target, user="guest", passwd="guest"): """ Download a product from the SentinelScihub si...
source: str A product fully qualified URL target: str A filename where to download the URL specified """ md5_source = source.replace("$value", "/Checksum/Value/$value") r = requests.get(md5_source, auth=(user, passwd), verify=False) md5 = r.text if os.path.exists(target): ...
turbulenz/turbulenz_tools
turbulenz_tools/tools/exportevents.py
Python
mit
25,568
0.003559
#!/usr/bin/env python # Copyright (c) 2012-2013 Turbulenz Limited from logging import basicConfig, CRITICAL, INFO, WARNING import argparse from urllib3 import connection_from_url from urllib3.exceptions import HTTPError, SSLError from simplejson import loads as json_loads, dump as json_dump from gzip import GzipFile ...
print '\r >> %s' % message, if new_line: print def error(message): log('[ERROR] - %s' % message) def warning(message): log('[WARNING] - %s' % message) def _parse_args(): parser = argparse.ArgumentParser(description="Export event logs and anonymised user information of a game.") parse...
e_true", help="silent running") parser.add_argument("--version", action='version', version=__version__) parser.add_argument("-u", "--user", action="store", help="Hub login username (will be requested if not provided)") parser.add_argument("-p", "--password", action="store", ...
nttks/jenkins-test
lms/djangoapps/bulk_email/tests/test_tasks.py
Python
agpl-3.0
24,083
0.003737
""" Unit tests for LMS instructor-initiated background tasks. Runs tasks on answers to course problems to validate that code paths actually work. """ import json from uuid import uuid4 from itertools import cycle, chain, repeat from mock import patch, Mock from smtplib import SMTPServerDisconnected, SMTPDataError, SM...
lf._run_task_with_mock_celery(send_bulk_course_email, task_entry.id, task_entry.task_id) def test_bad_task_id_on_update(self): task_entry = self._create_input_entry() def dummy_update_subtask_status(entry
_id, _current_task_id, new_subtask_status): """Passes a bad value for task_id to test update_subtask_status""" bogus_task_id = "this-is-bogus" update_subtask_status(entry_id, bogus_task_id, new_subtask_status) with self.assertRaises(ValueError): with patch('bulk_...
nabilbendafi/mbed
workspace_tools/toolchains/arm.py
Python
apache-2.0
7,354
0.005167
""" mbed SDK Copyright (c) 2011-2013 ARM Limited Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in wr...
pend("-g") common.append("-O0") else: common.append("-O3") common_c = [ "--md", "--no_depend_system_headers", '-I%s' % ARM_INC ] self.asm = [main_cc] + common + ['-I%s' % ARM_INC] if not "analyze" in self.options: self...
else: self.cc = [join(GOANNA_PATH, "goannacc"), "--with-cc=" + main_cc.replace('\\', '/'), "--dialect=armcc", '--output-format="%s"' % self.GOANNA_FORMAT] + common + common_c + ["--c99"] self.cppc= [join(GOANNA_PATH, "goannac++"), "--with-cxx=" + main_cc.replace('\\', '/'), "--dialect=armcc"...
ChopChopKodi/pelisalacarta
python/main-classic/lib/btserver/dispatcher.py
Python
gpl-3.0
805
0.006211
from monitor import Monitor try: from python_libtorrent import get_libtorrent lt = get_libtorrent() except Exception, e: import libtorrent as lt class Dispatcher(Monitor): def __init__(self, client): super(Dispatcher,self).__init__(client) def do_start(self, th, ses):
self._th = th self._ses=ses self.start() def run(self): if not self._ses: raise Exception('Invalid state, session is not initialized') while self.running: a=self._ses.wait_for_alert(1000) if a: alerts= self._ses.pop_alerts...
cb(lt.alert.what(alert), alert)
chipaca/snapcraft
snapcraft/plugins/v1/waf.py
Python
gpl-3.0
3,034
0
# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*- # # Copyright (C) 2016, 2018, 2020 Canonical Ltd # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3 as # published by the Free Software Foundation. # # This program is distribu...
": [], } schema["required"] = ["source"] return schema
def __init__(self, name, options, project): super().__init__(name, options, project) self._setup_base_tools() def _setup_base_tools(self): self.build_packages.append("python-dev:native") @classmethod def get_build_properties(cls): # Inform Snapcraft of the properties assoc...
cfe-lab/MiCall
micall/tests/test_remap.py
Python
agpl-3.0
54,983
0.000527
from csv import DictWriter from io import StringIO import os import unittest from pathlib import Path from unittest.mock import patch, Mock, DEFAULT from pytest import fixture from micall.core import remap from micall.core.project_config import ProjectConfig from micall.core.remap import is_first_read, is_short_read,...
test1\t99\ttest\t1\t44\t3M\t=\t1\t3\tGCA\tJJJ\n" "tes
t2\t147\ttest\t1\t44\t3M\t=\t1\t-3\tTCA\tJJJ\n" ) expected_conseqs = {'test': 'GCA'} conseqs = remap.sam_to_conseqs(sam_file) self.assertDictEqual(expected_conseqs, conseqs) def testSoftClip(self): sam_file = StringIO( "@SQ\tSN:test\n" "test1\t99\ttes...
floriangeigl/arxiv_converter
tex_utils.py
Python
gpl-3.0
969
0.002064
import re simple_cmd_match = re.compile(r'\\([^\\]+?)\{(.*?)\}') graphics_cmd_match = re.compile(r'\\includegraphics\[.*?\]?\{(.*?)\}') begin_cmd_match = re.compile(r'\\begin{([^}]+?)}(?:(?:\[([^\]]+?)\])|.*)') newcmd_match = re.compile(r'\\.+?\{(.*?)\}\{(.*)\}') # newcmd_match_with_var = re.compile(r'\\[^\\]+?\{(.*?)...
open_braces -= 1 if open
_braces > 0: one_var += char elif open_braces == 0 and one_var: res.append(one_var) one_var = '' if char == '{': open_braces += 1 return res class FileIter: def __init__(self, filename): self.fn = filename self.f = open(self.fn, 'r...
CSSCorp/openstack-automation
file_root/_modules/neutron.py
Python
gpl-2.0
13,539
0
# -*- coding: utf-8 -*- ''' Module for handling openstack neutron calls. :maintainer: <akilesh1597@gmail.com> :maturity: new :platform: all :optdepends: - neutronclient Python adapter :configuration: This module is not usable until the following are specified either in a pillar or in the minion's config file::...
ck-subnet-id name='new_name' ''' neutron_interface.update_subnet(subnet_id, {'subnet': subnet_params}) @_autheticate def update_router(neutron_interface, router_id, **router_params): ''' update given router CLI Example: .. code-block:: bash salt '*' neut
ron.update_router openstack-router-id name='new_name' external_gateway='openstack-network-id' administrative_state=true ''' neutron_interface.update_router(router_id, {'router': router_params}) @_autheticate def router_gateway_set(neutron_interface, router_id, external_gateway): ''' Set ex...
jairtrejo/doko
app/rohan/urls.py
Python
mit
581
0.001721
from django.conf import settings from django.conf.urls
import patterns, include, url from django.contrib import admin from django.conf.urls.static import static from .views import HomeView # Uncomment the next two lines to enable the admin: admin.autodiscover() urlpatterns = ( static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + patterns( ''...
home'), url(r'^admin/', include(admin.site.urls)), url(r'^social/', include('socialregistration.urls', namespace='socialregistration')), ) )
BertrandBordage/django-cachalot
docs/conf.py
Python
bsd-3-clause
8,766
0.006046
# -*- coding: utf-8 -*- # # django-cachalot documentation build configuration file, created by # sphinx-quickstart on Tue Oct 28 22:46:50 2014. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated fil...
': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ ('index', 'django-cachalot.tex', u'django-cachalot Documentati...
, 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_p...
dogsaur/SMS
db_repository/versions/007_migration.py
Python
mit
1,457
0.001373
from sqlalchemy import * from migrate import * from migrate.changeset import schema pre_meta = MetaData() post_meta = MetaData() product = Table('product', pre_meta, Column('id', INTEGER, primary_key=True, nullable=False), Column('product_name', VARCHAR), Column('bar_code', INTEGER), Column('price', N...
'category', String), Column('bar_code', Integer), Column('size', String), Column('inprice', Numeric), Column('price', Numeric), Column('supply_id', Integer), Column('picture_id', Integer), ) def upgrade(migrate_engine): # Upgrade operations go here. Don'
t create your own engine; bind # migrate_engine to your metadata pre_meta.bind = migrate_engine post_meta.bind = migrate_engine pre_meta.tables['product'].columns['supply'].drop() post_meta.tables['product'].columns['supply_id'].create() def downgrade(migrate_engine): # Operations to reverse t...
JoseKilo/week_parser
tests/unit/test_week_parser.py
Python
mit
5,936
0
import pytest import six from mock import call, patch from tests import utils from week_parser.base import parse_row, parse_week, populate_extra_data from week_parser.main import PrettyPrinter def test_populate_extra_data_no_days(): """ If we haven't found any days data, there is not extra data to add ""...
PTION__' populate_extra_data(week_data, description) assert week_data == { 'thu': { 'value': value, 'double': value * 2, 'description': '{} {}'.format(description, value * 2) } } def test_parse_row_single_day(): """ If the input row contains a ...
mon': '3', 'description': '__DESCRIPTION__'} with patch('week_parser.base.populate_extra_data') as mock_populate: week_data = parse_row(row) assert week_data == {'mon': {'day': 'mon', 'value': 3}} assert mock_populate.call_args_list == [call(week_data, '__DESCRIPTION__')] def test_parse_row_day_...
anntzer/numpy
numpy/core/memmap.py
Python
bsd-3-clause
11,688
0.000684
from contextlib import nullcontext import numpy as np from .numeric import uint8, ndarray, dtype from numpy.compat import os_fspath, is_pathlib_path from numpy.core.overrides import set_module __all__ = ['memmap'] dtypedescr = dtype valid_filemodes = ["r", "c", "r+", "w+"] writeable_filemodes = ["r+", "w+"] mode_eq...
: {'r+', 'r', 'w+', 'c'}, optional The file is opened in this mode: +------+-------------------------------------------------------------+ | 'r' | Open existing file for reading only. | +------+-------------------------------------------------------------+ ...
le for reading and writing. | +------+-------------------------------------------------------------+ | 'w+' | Create or overwrite existing file for reading and writing. | +------+-------------------------------------------------------------+ | 'c' | Copy-on-write: assig...
nullable/libxmlquery
documentation/conf.py
Python
mit
8,376
0.00693
# -*- coding: utf-8 -*- # # libxmlquery documentation build configuration file, created by # sphinx-quickstart on Fri Nov 5 15:13:45 2010. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # #...
ue, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this mark...
# If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # out...
paulrouget/servo
tests/wpt/web-platform-tests/xhr/resources/access-control-basic-whitelist-response-headers.py
Python
mpl-2.0
571
0
def main(request, response): headers = { # CORS-safelisted "content-type": "text/plain", "cache-control": "n
o cache", "content-language": "en", "expires": "Fri, 30 Oct 1998 14:19:41 GMT", "last-modified": "Tue, 15 Nov 1994 12:45:26 GMT", "pragma": "no-cache", # Non-CORS-safelisted "x-test": "foobar", "Access-Control-Allow-Origin": "*" } for header in headers: ...
aders.set(header, headers[header]) response.content = "PASS: Cross-domain access allowed."
endlessm/chromium-browser
third_party/catapult/devil/devil/android/cpu_temperature_test.py
Python
bsd-3-clause
4,988
0.005413
#!/usr/bin/env python # Copyright 2019 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. """ Unit tests for the contents of cpu_temperature.py """ # pylint: disable=unused-argument import logging import unittest from devil...
lse(c.IsSupported()) class CpuTemperatureLetCpuCoolToTemperatureTest(CpuTemperatureTest): #
Return values for the mock side effect cooling_down0 = ( [45000 for _ in range(8)] + [43000 for _ in range(8)] + [41000 for _ in range(8)]) @mock.patch('time.sleep', mock.Mock()) def testLetBatteryCoolToTemperature_coolWithin24Calls(self): self.mock_device.ReadFile ...
dtysky/Gal2Renpy
Gal2Renpy/SpSyntax/ScSp.py
Python
mit
352
0.073864
#coding:utf-8 ################################# #Copyright(c) 2014 dtysky ######
########################### im
port G2R class ScSp(G2R.SpSyntax): def Show(self,Flag,Attrs,US,UT,Tmp,FS): sw='' name,Attrs=self.Check(Flag,Attrs,UT,FS) if Attrs['k']=='Main': sw+=' $ store.chapter=' sw+="'Chapter."+Attrs['cp']+Attrs['sc']+"'\n" return sw
ULHPC/easybuild-framework
easybuild/toolchains/compiler/__init__.py
Python
gpl-2.0
1,248
0.001603
## # Copyright 2012-2017 Ghent University # # This file is part of EasyBuild, # originally created by the HPC team of Ghent University (http://ugent.be/hpc/en), # with support of Ghent University (http://ugent.be/hpc), # the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be), # Flemish Research Foundation (F...
rt pk
g_resources pkg_resources.declare_namespace(__name__)
srkukarni/heron
integration_test/src/python/integration_test/core/integration_test_spout.py
Python
apache-2.0
4,617
0.007581
# Copyright 2016 Twitter. 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 agree...
# avoid modification to cls.outputs _outputs = copy.copy(cls.outputs) if user_outpu
t_fields is not None: _outputs.extend(user_output_fields) return HeronComponentSpec(name, python_class_path, is_spout=True, par=par, inputs=None, outputs=_outputs, config=config) def initialize(self, config, context): user_spout_classpath = config.get(integ_const.USER_SPOU...
rsalmaso/django-cms
cms/test_utils/project/pluginapp/plugins/style/models.py
Python
bsd-3-clause
1,967
0.001525
from django.db import models from cms.models import CMSPlugin CLASS_CHOICES = ['container', 'content', 'teaser'] CLASS_CHOICES = tuple((entry, entry) for entry in CLASS_CHOICES) TAG_CHOICES = [ 'div', 'article', 'section', 'header', 'footer', 'aside', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6' ] TAG_CHOICES = tuple...
if self.class_name: classes.append(self.class_name) if self.additional_classes: classes.extend(item.strip() for item in self.addi
tional_classes.split(',') if item.strip()) display.append('.{0}'.format('.'.join(classes))) return ' '.join(display) def get_additional_classes(self): return ' '.join(item.strip() for item in self.additional_classes.split(',') if item.strip())
t11e/django
django/contrib/gis/db/backends/postgis/models.py
Python
bsd-3-clause
2,022
0.000989
""" The GeometryColumns and SpatialRefSys models for the PostGIS backend. """ from django.db import models from django.contrib.gis.db.backends.base import SpatialRefSysMixin class GeometryColumns(models.Model): """ The 'geometry_columns' table from the PostGIS. See the PostGIS documentation at Ch. 4.2.2. ...
the PostGIS documentaiton at Ch. 4.2.1. """ srid = models.IntegerField(primary_key=True) auth_name = models.CharField(max_length=25
6) auth_srid = models.IntegerField() srtext = models.CharField(max_length=2048) proj4text = models.CharField(max_length=2048) class Meta: app_label = 'gis' db_table = 'spatial_ref_sys' managed = False @property def wkt(self): return self.srtext @classmethod...
JulyKikuAkita/PythonPrac
cs15211/ValidAnagram.py
Python
apache-2.0
3,340
0.001796
__source__ = 'https://leetcode.com/problems/valid-anagram/description/' # https://github.com/kamyu104/LeetCode/blob/master/Python/valid-anagram.py # Time: O(n) # Space: O(1) # # Description: Leetcode # 242. Valid Anagram # # Given two strings s and t, write a function to # determine if t is an anagram of s. # # For ex...
ilar Questions # Group Anagrams Palindrome Permutation Find All Anagrams in a String # import unittest class Solution: # @param {string} s # @param {string} t # @return {b
oolean} def isAnagram(self, s, t): if len(s) != len(t): return False count = {} for c in s: if c.lower() in count: count[c.lower()] += 1 else: count[c.lower()] = 1 for c in t: if c.lower() in count: ...
mblayman/lcp
conductor/accounts/tests/test_forms.py
Python
bsd-2-clause
5,205
0.000192
from typing import Dict from unittest import mock from conductor.accounts.forms import DeactivateForm, SignupForm from conductor.tests import TestCase class TestSignupForm(TestCase): def test_valid(self) -> None: product_plan = self.ProductPlanFactory.create() data = { "username": "ma...
form = SignupForm(product_plan, data=data) self.assertFalse(form.is_valid()) self.assertIn("password", form.errors) def test_unique_email(self) -> None: product_plan = self.ProductPlanFactory.create() self.UserFactory.create(email="matt@test.com") data = { ...
"stripe_token": "tok_1234", "postal_code": "12345", } form = SignupForm(product_plan, data=data) self.assertFalse(form.is_valid()) self.assertIn("email", form.errors) def test_unique_username(self) -> None: product_plan = self.ProductPlanFactory.creat...
LaPingvino/pasportaservo
pasportaservo/settings/dev_etenil.py
Python
agpl-3.0
652
0
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'pasportaservo', 'USER': 'guillaume', } } LANGUAGE_CODE = 'en' INSTALLED_APPS = ( 'grappelli', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'dja...
'django.contrib.messages', 'django.contrib.staticfiles', 'django_extensions', 'django_countries', 'phonenumber_field', 'bootstrapform', 'leaflet', 'postm
an', 'hosting', 'pages', 'debug_toolbar', ) EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
garyjs/Newfiesautodialer
newfies/context_processors.py
Python
mpl-2.0
564
0.001773
# # Newfies-Dialer License # http://www.newfies-dialer.org # # 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 di
stributed with this file, # You can obtain one at http://mozilla.org/MPL/2.0/. # # Copyright (C) 2011-2013 Star2Billin
g S.L. # # The Initial Developer of the Original Code is # Arezqui Belaid <info@star2billing.com> # import newfies from django.conf import settings def newfies_version(request): return {'newfies_version': newfies.__version__, 'SURVEYDEV': settings.SURVEYDEV}
ianmiell/shutit-openshift-vm
airflow.py
Python
mit
4,398
0.012051
from shutit_module import ShutItModule import base64 class openshift_airflow(ShutItModule): def build(self, shutit): shutit.send('cd /tmp/openshift_vm') shutit.login(command='vagrant ssh') shutit.login(command='sudo su -',password='vagrant',note='Become root (there is a problem logging in as admin with the vag...
}, "spec": { "strategy": { "type": "Rolling", "rollingParams": { "updatePeriodSeconds": 1, "intervalSeconds": 1, "timeoutSeconds": 120 }, "resources": {} }, "triggers": [
{ "type": "ImageChange", "imageChangeParams": { "automatic": true, "containerNames": [ "nodejs-helloworld" ], "from": { "kind": "ImageStreamTag", "name": "airflow:latest" } ...
vonivgol/pyreminder
src/main.py
Python
gpl-2.0
1,723
0.002902
from tkinter import * from gui import GUI from reminder import Reminder import argparse import time if __name__ == '__main__': print(""" Copyright (C) 2016 Logvinov Dima. This program comes with ABSOLUTELY NO WARRANTY. This is free software, and you are welcome to redistribute it under certain cond...
event_id ", type=int) parser.add_argument('--gui', help="Run gui program.", action="store_true") args = parser.parse_args() reminder = Reminder() if args.gui: root = Tk() root.geometry("500x200+350+500") app = GUI(root, reminder) root.mainloop() if args.add: ...
reminder.update_db() if args.list: tasks = reminder.get_tasks_list() if len(tasks) > 0: for task_id in range(0, len(tasks)): task_id = str(task_id) print("id:{0} time:{1} text:{2}". format(task_id, tasks[task_id][0], tasks[...
kowey/attelo
attelo/io.py
Python
gpl-3.0
11,402
0
""" Saving and loading data or models """ from __future__ import print_function from itertools import chain import codecs import copy import csv import json import sys import time import traceback import joblib from sklearn.datasets import load_svmlight_file from .edu import (EDU, FAKE_ROOT_ID, FAKE_ROOT) from .tabl...
e, num=len(row), row=row)) return tuple(row[:2]) with open(edu_file, 'rb') as instream: reader = csv.reader(instream, dialect=csv.excel_tab) return [read_pair(r) for r in reader if r] def load_labels(featu...
return the sequence of labels, else return None :rtype: [string] or None """ with codecs.open(feature_file, 'r', 'utf-8') as stream: line = stream.readline() if line.startswith('#'): seq = line[1:].split() if seq[0] == 'labels:': return seq[1:] #...
perlygatekeeper/glowing-robot
google_test/bunny_escape/bunnyEscape_fixed.py
Python
artistic-2.0
3,411
0.013193
def printMap(the_map,note): print(note) for row in the_map: row_str = "" for cell in row: row_str += " {0:3d}".format(cell) print(row_str) def pathFinder(x, y, the_map, steps, lastX, lastY, wall): # count possible moves debug = False options ...
for option in options: # new x and y newX = x + option[0] # print("x({0:2d}) + option[0]({1:2d}) -> newX({2:2d})".format(x,option[0],newX) ) newY = y + option[1] # print("y({0:2d}) + option[1]({1:2d}) -> newY({2:2d})".format(y,option[1],newY) ) if debug: ...
if the_map[newY][newX] == 0: the_map[newY][newX] = steps if newX != 0 or newY != 0: pathFinder(newX, newY, the_map, steps, lastX, lastY, wall) elif the_map[newY][newX] > 1 and steps <= the_map[newY][newX]: the_map[newY][newX] = steps if ...
robocomp/robocomp
tools/rcmonitor/examples/pyramidRoiRGB.py
Python
gpl-3.0
2,369
0.01984
# -*- coding: utf-8 -*- # Copyright (C) 2010 by RoboLab - University of Extremadura # # This file is part of RoboComp # # RoboComp 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...
prx) self.leftPyrList = [] self.rightPyrList = [] for level in ran
ge(4): self.leftPyrList.append(None) self.rightPyrList.append(None) self.wdth = self.proxy.getRoiParams().width self.hght = self.proxy.getRoiParams().height self.job() def job(self): output = self.proxy.getBothPyramidsRGBAndLeftROIList() pos=0 size=self.wdth*self.hght*3 for level in range(4): se...
observerss/yamo
yamo/document.py
Python
mit
10,377
0.000096
#!/usr/bin/env python # -*- coding: utf-8 -*- import logging from functools import partialmethod from pymongo.operations import UpdateOne, InsertOne from .cache import CachedModel from .errors import ConfigError, ArgumentError from .metatype import DocumentType, EmbeddedDocumentType from .fields import EmbeddedField...
te_one({'_id': self._data['_id']}, update) def upsert(self, null=False): """ Insert or Update Document :param null: whether update null values Wisely select unique field values as filter, Update with upsert=True """ self._pre_save() ...
r = self._coll.find_one_and_update(filter_, update, upsert=True, new=True) self._data['_id'] = r['_id'] else: r = self._coll.insert_one(self._data) self._data['_id'] = r.inserted_id def save(self): ...
sasha-gitg/python-aiplatform
samples/snippets/job_service/cancel_data_labeling_job_sample.py
Python
apache-2.0
1,485
0.001347
# Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
rvices require regional API endpoints. client_options = {"api_endpoint": api_endpoint} # Initialize client that will be used to create and send requests. # This client only needs to be created once, and can be reused for multiple requests. client = aiplatform.gapic.JobServiceClient(client_options=client...
project=project, location=location, data_labeling_job=data_labeling_job_id ) response = client.cancel_data_labeling_job(name=name) print("response:", response) # [END aiplatform_cancel_data_labeling_job_sample]
agentOfChaos/brainPizza
brainpizza.py
Python
gpl-2.0
3,474
0.004893
from pybrain.tools.shortcuts import buildNetwork from pybrain.datasets import SupervisedDataSet from pybrain.supervised.trainers import BackpropTrainer import copy from PIL import Image import os import random import time import math imagesize = (120, 120) peak = 100 gusti = ["margherita", "crudo", "funghi", "salame"...
0.3, 0.3)), processImg(pizza)) print("done") return ds def outimage(outtuple, name): img = Image.new('RGB', imagesize, "white") pixels = img.load() for i in range(img.size[0]): for j in range(img.size[1]): tup_index = (i*img.size[0] + j) * 3 pixels[i,j] = (in
t(outtuple[tup_index]), int(outtuple[tup_index + 1]), int(outtuple[tup_index + 2])) img.save(name) #img.show() def calcETA(timestep, remaining): totsec = timestep * remaining totmin = math.floor(totsec / 60) remsec = totsec - (totmin * 60) return totmin, remsec def letsrock(rounds=25): min...
lukeburden/django-allauth
allauth/socialaccount/providers/ynab/provider.py
Python
mit
852
0
from allauth.socialaccount.providers.base import AuthAction, ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class Scope(object): ACCESS = 'read-only' class YNABAccount(ProviderAccount): pass class YNABProvider(OAuth2Provider): id = 'ynab' name = 'YNAB' ...
_params(self, request, action): ret = super(YNABProvider, self).get_auth_params(request, action) if action == AuthAction.REAUTHENTICATE: ret['prompt'] = 'select_account consent' return ret def extract_uid(self, data): ...
der_classes = [YNABProvider]
HealthCatalystSLC/healthcareai-py
healthcareai/common/database_library_validators.py
Python
mit
626
0.00639
import sys from healthcareai.common.healthcareai_error import HealthcareAIError def validate_pyodbc_is_loaded(): """ Si
mple check that alerts user if they are do not have pyodbc installed, which is not a requirement. """ if 'pyodbc' not in s
ys.modules: raise HealthcareAIError('Using this function requires installation of pyodbc.') def validate_sqlite3_is_loaded(): """ Simple check that alerts user if they are do not have sqlite installed, which is not a requirement. """ if 'sqlite3' not in sys.modules: raise HealthcareAIError('Us...
weld-project/weld
weld-python/tests/grizzly/core/test_frame.py
Python
bsd-3-clause
3,167
0.005052
""" Test basic DataFrame functionality. """ import pandas as pd import pytest import weld.grizzly as gr def get_frames(cls, strings): """ Returns two DataFrames for testing binary operators. The DataFrames have columns of overlapping/different names, types, etc. """ df1 = pd.DataFrame({ ...
age': [20, 30, 35, 20, 50, 35], 'score': [20.0, 30.0, 35.0, 50.0, 35.0, 25.0] }) df2 = gr.GrizzlyDataFrame({
'age': [20, 30, 35, 20, 50, 35], 'scores': [20.0, 30.0, 35.0, 50.0, 35.0, 25.0] }) df3 = (df1 + df2) * df2 + df1 / df2 assert not df3.is_value df3.evaluate() assert df3.is_value weld_value = df3.weld_value df3.evaluate() # The same weld_value should be returned. a...
jgillis/casadi
test/python/sdp.py
Python
lgpl-3.0
12,021
0.049746
# # This file is part of CasADi. # # CasADi -- A symbolic framework for dynamic optimization. # Copyright (C) 2010 by Joel Andersson, Moritz Diehl, K.U.Leuven. All rights reserved. # # CasADi is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Pub...
1*n2/n3),digits=5) self.checkarray(dsp.output("primal"),DMatrix(n2/n3),digits=5) self.checkarray(dsp.output("p"),DMatrix.zeros(2,2),digits=5) self.checkarray(dsp.output("dual")[0,0]-dsp.output("dual")[1,1],DMatrix(n1/n3),digits=5) @requires("DSDPSolver") def test_linear_interpolation1(self): s...
x0+x1>=1 # x0 >=0 # x1 >=0 # # solution: x0=1, x1=0 b = DMatrix([2,3]) Ai = [ blkdiag([1,1,0]), blkdiag([1,0,1])] C = blkdiag([1,0,0]) A = vertcat(Ai) dsp = DSDPSolver(C.sparsity(),A.sparsity()) dsp.init() dsp.input("c").se...
pedrogideon7/spy_quest
parser.py
Python
mit
1,938
0.004128
#! /usr/bin/env python class ParserError(Exception): pass class Sentence(object): def __init__(self, subject, verb, object): # remember we take ('noun', 'princess') tuples and convert them self.subject = subject[1] self.verb = verb[1] self.object = object[1] def get_sente...
match(word_list, 'verb') else: raise ParserError("Expected a verb next.") def parse_object(word_list): skip(word_list, 'stop') next = peek(word_list) if next == 'noun': return match(word_list, 'noun') elif next == 'di
rection': return match(word_list, 'direction') else: raise ParserError("Expected a noun or direction next.") def parse_subject(word_list, subj): verb = parse_verb(word_list) obj = parse_object(word_list) return Sentence(subj, verb, obj) def parse_sentence(word_list): skip(word_l...
clemenshage/grslra
experiments/6_grslra/system_identification_lti/system_identification.py
Python
mit
2,175
0.004138
from grslra import testdata from grslra.grslra_batch import grslra_batch, slra_by_factorization from grslra.structures import Hankel from grslra.scaling import Scaling import numpy as np import t
ime # The goal of this experiment is to identify an LTI system from a noisy outlier-contaminated and subsampled observation of its impulse response PROFILE = 0 if PROFILE: import cProfile N = 80 m = 20 k = 5 sigma=0.05 outlier_rate = 0.05 outlier_amplitude = 1 rate_Omega=0.5 N_f = 20 scaling = Scaling(center...
+ N_f, m, k, rho=outlier_rate, amplitude=outlier_amplitude, sigma=sigma) # determine scaling factor scaling.scale_reference(x) mu = (1-p) * (3 * sigma / scaling.factor) ** 2 # draw sampling set card_Omega = np.int(np.round(rate_Omega * N)) Omega = np.random.choice(N, card_Omega, replace=False) # create binary support...
nitin-cherian/LifeLongLearning
Python/PythonProgrammingLanguage/Encapsulation/encap_env/lib/python3.5/site-packages/nbconvert/exporters/latex.py
Python
mit
3,419
0.005557
"""LaTeX Exporter class""" # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. import os f
rom traitlets import Unicode, default from traitlets.config import Config from nbconvert.filters.highlight import Highlight2Latex from nbconvert.filters.filter_links import resolve_references from .templateexporter import TemplateExporter class LatexExporter(TemplateExporter): """ Exports to a Latex template....
you need custom tranformers/filters. Inherit from it if you are writing your own HTML template and need custom tranformers/filters. If you don't need custom tranformers/filters, just change the 'template_file' config option. Place your template in the special "/latex" subfolder of the "../templat...
wolverineav/neutron
neutron/tests/unit/services/bgp/driver/ryu/test_driver.py
Python
apache-2.0
12,381
0.000888
# Copyright 2016 Huawei Technologies India Pvt. Ltd. # # 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...
th an invalid asnum data-type self.ryu_bgp_driver.add_bgp_speaker(FAKE_LOCAL_AS1) self.assertRaises(bgp_driver_exc.InvalidParamType, self.ryu_bgp_driver.add_bgp_peer, FAKE_LOCAL_AS1, FAKE_PEER_IP, '12345') # Test with an invalid auth-type and a...
_bgp_driver.add_bgp_peer, FAKE_LOCAL_AS1, FAKE_PEER_IP, FAKE_PEER_AS, 'sha-1', 1234) # Test with an invalid auth-type and a valid password self.assertRaises(bgp_driver_exc.InvaildAuthType, self.ryu_bgp_driver.add_bgp_peer, ...
upconsulting/IsisCB
isiscb/curation/actions.py
Python
mit
13,091
0.004278
""" Asynchronous functions for bulk changes to the database. """ from __future__ import absolute_import from __future__ import unicode_literals from builtins import zip from builtins import object from curation.tasks import update_instance, bulk_change_tracking_state, bulk_prepend_record_history, save_creation_to_cita...
ion.taskslib.citation_tasks as ctasks import curation.taskslib.authority_tasks as atasks from isisdata.filters import CitationFilter import js
on # TODO: refactor these actions to use bulk apply methods and then explicitly # trigger search indexing (or whatever other post-save actions are needed). class BaseAction(object): def __init__(self): if hasattr(self, 'default_value_field'): self.value_field = self.default_value_field ...
jkandasa/integration_tests
fixtures/parallelizer/__init__.py
Python
gpl-2.0
27,463
0.002185
"""Parallel testing, supporting arbitrary collection ordering The Workflow ------------ - Master py.test process starts up, inspects config to decide how many slave to start, if at all - env['parallel_base_urls'] is inspected first - py.test config.option.appliances and the related --appliance cmdline flag are u...
msg = '{} killed due to error, respawning'.format(slave.id) else: msg = '{} terminated unexpectedly with status {}, respawning'.format( slave.id, returncode) if slave.tests: failed_tests, slave.tests = slave....
sts = len(failed_tests) self.sent_tests -= num_failed_tests msg += ' and redistributing {} tests'.format(num_failed_tests) self.failed_slave_test_groups.append(failed_tests) self.print_message(msg, purple=True) # If a slave was termina...
deapplegate/wtgpipeline
quality_studies_psf.py
Python
mit
15,321
0.024672
import numpy, sys, os, pylab, astropy, astropy.io.fits as pyfits, ldac, math def open_and_get_shearcat(filename, tablename): # # for opening and retrieving shear cat. # return ldac.openObjectFile(filename, tablename) #class ello def avg_shear(g1array, g2array): avg1 = numpy.mean(g1array)...
ray(starcat['x']) star_yarr = numpy.array(starcat['y']) star_e1corr = numpy.array(starcat['e1corrpol']) star_e2corr = numpy.array(starcat['e2corrpol'
]) star_e1 = numpy.array(starcat['e1']) star_e2 = numpy.array(starcat['e2']) pylab.rc('text', usetex=True) pylab.figure(figsize=(15,10) ,facecolor='w') pylab.subplots_adjust(wspace=0.3,hspace=0.3) pylab.subplot(231,axisbg='w') pylab.cool() # Qualtest 1 : Average shear: avg...
floodlight/ivs
build/oftest.py
Python
epl-1.0
13,000
0.006692
#!/usr/bin/python ################################################################ # # Copyright 2013, Big Switch Networks, Inc. # # Licensed under the Eclipse Public License, Version 1.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at...
########################################### def dirlist(d): if d == None: return [ "." ] if type(d) == str: return [ d ] if type(d) != list: raise Exception("'%s' is a bad dirlist" % d) return d def fselect(name, tops, subs, p=False): tops = dirlist(tops) subs = dirlis...
p: print "%s: not found" % f if p == False: fselect(name, tops, subs, p=True) raise Exception("Could not find the '%s' binary. Search paths were %s:%s" % (name, tops, subs)) def system(command, die=False): logging.debug("Running %s ", command) rv = os.system(command) if...
JBonsink/GSOC-2013
tools/ns-allinone-3.14.1/ns-3.14.1/src/config-store/bindings/modulegen__gcc_LP64.py
Python
gpl-3.0
54,535
0.013588
from pybindgen import Module, FileCodeSink, param, retval, cppclass, typehandlers import pybindgen.settings import warnings class ErrorHandler(pybindgen.settings.ErrorHandler): def handle_error(self, wrapper, exception, traceback_): warnings.warn("exception %r in wrapper %s" % (exception, wrapper)) ...
import sys def module_init(): root_module = Module('ns.config_store', cpp_namespace='::ns3') return root_module def register_types(module): root_module = module.get_root() ## callback.h (module 'core'): ns3::CallbackBase [class] module.add_class('CallbackBase', import_from_module='ns.core'...
module.add_class('FileConfig', allow_subclassing=True) ## gtk-config-store.h (module 'config-store'): ns3::GtkConfigStore [class] module.add_class('GtkConfigStore') ## file-config.h (module 'config-store'): ns3::NoneFileConfig [class] module.add_class('NoneFileConfig', parent=root_module['ns3::File...
gcushen/mezzanine-api
tests/test_post.py
Python
mit
10,996
0.003365
from __future__ import unicode_literals, print_function from django.urls import reverse from rest_framework import status from mezzanine.blog.models import BlogPost as Post from tests.utils import TestCase class TestPostViewSet(TestCase): """ Test the API resources for blog posts (read and write) """ ...
) self.post_draft.delete() self.post_published.delete() def test_list_published_posts(self): """ Test API list all published blog posts """ url = reverse('blogpost-list') response = self.client.get(url, format='json') self.assertEqual(respon
se.status_code, status.HTTP_200_OK) self.assertEqual(response['Content-type'], 'application/json') self.assertEqual(response.data['count'], 1) self.assertEqual(response.data['results'][0]['title'], self.post_published.title) def test_retrieve_published_post(self): """ Test A...
tomjelinek/pcs
pcs/cli/routing/resource_stonith_common.py
Python
gpl-2.0
2,770
0
from typing import ( Any, List, ) from pcs import resource from pcs.cli.common.parse_args import InputModifiers from pcs.cli.common.routing import ( CliCmdInterface, create_router, ) def resource_defaults_cmd(parent_cmd: List[str]) -> CliCmdInterface: def
_get_router( lib: Any, argv: List[str], modifiers: InputModifiers ) -> None: """ Options: * -f - CIB file * --force - allow unknown options """ if argv and "=" in argv[0]: # DEPRECATED legacy command return resource.resource_default...
, deprecated_syntax_used=True ) router = create_router( { "config": resource.resource_defaults_config_cmd, "set": create_router( { "create": resource.resource_defaults_set_create_cmd, "de...
decebel/dataAtom_alpha
bin/plug/py/external/pattern/text/en/__init__.py
Python
apache-2.0
3,292
0.008202
#### PATTERN | EN ################################################################################## # Copyright (c) 2010 University of Antwerp, Belgium # Author: Tom De Smedt <tom@organisms.be> # License: BSD (see LICENSE.txt for details). # http://www.clips.ua.ac.be/pages/pattern ####################################...
n) def ngrams(string, n=3, continuous=False): """ Returns a list of n-grams (tuples of n successive words) from the given string. Alternatively, you can supply a Text or Sentence object. With continuous=False, n-grams will not run over sentence markers (i.e., .!?). """ def strip_per...
sinstance(w, Word) and w.string or w) not in punctuation] if n <= 0: return [] if isinstance(string, basestring): s = [strip_period(s.split(" ")) for s in tokenize(string)] if isinstance(string, Sentence): s = [strip_period(string)] if isinstance(string, Text): s = [strip...
beepee14/scikit-learn
examples/ensemble/plot_ensemble_oob.py
Python
bsd-3-clause
3,265
0
""" ============================= OOB Errors for Random Forests ============================= The ``RandomForestClassifier`` is trained using *bootstrap aggregation*, where each new tree is fit from a bootstrap sample of the training observations :math:`z_i = (x_i, y_i)`. The *out-of-bag* (OOB) error is the average er...
tree during training. The resulting plot allows a practitioner to approximate a suitable value of ``n_estimators`` at which the error stabilizes. .. [1] T. Hastie, R. Tibshirani and J. Friedman, "Ele
ments of Statistical Learning Ed. 2", p592-593, Springer, 2009. """ import matplotlib.pyplot as plt from collections import OrderedDict from sklearn.datasets import make_classification from sklearn.ensemble import RandomForestClassifier, ExtraTreesClassifier # Author: Kian Ho <hui.kian.ho@gmail.com> # ...
trolldbois/python-haystack-reverse
test/haystack/reverse/test_pointerfinder.py
Python
gpl-3.0
12,279
0.003339
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function import logging import timeit import unittest from haystack.mappings import folder from haystack.mappings.base import AMemoryMapping from haystack.mappings.base import MemoryHandler from haystack.mappings.file import LocalMemoryMapping...
def test_pointer_enumerators(self): """ Search pointers values in one HEAP :return: """ # prep the workers dumpfilename = self._memory_handler.get_name() word_size = self._memory_handler.get_target_platform().get_word_size() feedback = searchers.NoFeedbac...
merator(self._memory_handler) finder = self._memory_handler.get_heap_finder() walkers = finder.list_heap_walkers() walker = walkers[0] heap_addr = walker.get_heap_address() heap = walker.get_heap_mapping() # create the enumerator on the whole mapping enumerator1 =...
Bedrock02/General-Coding
Search/Dijkstra/hheap.py
Python
mit
3,638
0.053051
class hheap(dict): @staticmethod def _parent(i): # please use bit operation (same below)! return (i-1)>>1 @staticmethod def _left(i): return (i<<1) + 1 @staticmethod def _right(i): return (i<<1) + 2 ''' Structure is the following inside the heap we have a list [position,value] which means the dicti...
): ''' Maintains the property of a heap by checking its children ''' leftChild = self._left(index) rightChild = self._right(index) last = len(self.heap)-1 if leftChild > last: return elif rightChild > last: if self.heap[leftChild][1] < self.heap[index][1]: self._swap(index,leftChild) retu...
: if self.heap[rightChild][1] < self.heap[leftChild][1]: min = rightChild else: min = leftChild if self.heap[index][1] > self.heap[min][1]: self._swap(index,min) if self.heap[index][1] == self.heap[min][1]: if self.heap[index][2] > self.heap[min][2]: self._swap(index,min) return self...
abersheeran/a2wsgi
script/version.py
Python
apache-2.0
509
0
import im
portlib import os import sys here = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) def get_version() -> str: """ Return version. """ sys.path.insert(0, here) return importlib.import_module("a2wsgi").__version__ os.chdir(here) os.system(f"poetry version {get_version()}") os.system("...
ags")