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
mstriemer/olympia
src/olympia/zadmin/management/commands/removeuserfromgroup.py
Python
bsd-3-clause
1,740
0
from django.core.management.base import BaseCommand, CommandError import commonware.log from olympia.access.models import Group, GroupUser from olympia.users.models import UserProfile class Command(BaseCommand): help = ('Remove a user from a group. Syntax: \n' ' ./manage.py removeuserfromgroup <u...
or('Group ({group}) does not exist.'
.format(group=group))
jsargiot/restman
tests/steps/share.py
Python
mit
2,709
0.004799
#!/usr/bin/env python # -*- coding: utf-8 -*- import base64 import json from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions from behave import * @step
('I share first element i
n the history list') def step_impl(context): context.execute_steps(u''' given I open History dialog ''') history = context.browser.find_element_by_id("HistoryPopup") entries = history.find_elements_by_xpath('.//li[not(@data-clone-template)]') assert len(entries) > 0, "There are no entries in...
tensorflow/autograph
reference_tests/assertion_test.py
Python
apache-2.0
1,233
0.004055
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
greed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ================
============================================================== """Basic assertions.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import reference_test_base import tensorflow.compat.v1 as tf def simple_assertion(x): assert x > 0 return x class ...
claneys/shinken
shinken/dispatcher.py
Python
agpl-3.0
31,411
0.00347
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2009-2014: # Gabes Jean, naparuba@gmail.com # Gerhard Lausser, Gerhard.Lausser@consol.de # Gregory Starck, g.starck@gmail.com # Hartmut Goebel, h.goebel@goebel-consult.de # # This file is part of Shinken. # # Shinken is free software: you ca...
tched, need dispatch :) # and if dispatch on a failed node, remove the association, and need
a new dispatch for r in self.realms: for cfg_id in r.confs: push_flavor = r.confs[cfg_id].push_flavor sched = r.confs[cfg_id].assigned_to if sched is None: if self.first_dispatch_done: logger.info("Scheduler ...
RioDream/learning-data-structure
python stuff/rent.py
Python
gpl-2.0
950
0.009281
# -*- coding: utf-8 -*- import requests from lxml import etree #使用requests库的get方法发起请求 headers = {"X-Requested-With" : "XMLHttpRequest"} url =
'http://www.newsmth.net/nForum/board/HouseRent' r = requests.get(url,headers=headers) #网页文本内容 htmlContent = r.text #建立HTML DOM tree page = etree.HTML(htmlContent) #用于解析的一些东西,解析title和href baseUrl = "http://www.newsmth.net" hrefRule = "//div[@class='b-content']/table/tbody/tr/td[2]/a/@href" titleRule = "//div[@class
='b-content']/table/tbody/tr/td[2]/a" parseResults_href = page.xpath(hrefRule.decode('utf-8')) parseResults_title = page.xpath(titleRule.decode('utf-8')) #暴力查找,然后输出title和href for i in range(len(parseResults_title)): if parseResults_title[i].text.encode("utf-8").find("西二旗") != -1: print "---------" ...
OICR/PGMLab
www/pgmbio/reactome_utils.py
Python
gpl-2.0
1,229
0.006509
import os import json import subprocess
def system_call(command): p = subprocess.Popen([command], stdout=
subprocess.PIPE, shell=True) p.wait() return p.stdout.read() # return str(p.returncode) cwd = os.getcwd() # hosted_data = cwd+"/../../data/reactome_template" hosted_data = "{}/../../data/reactome_template".format(cwd) # Returns an array of [{id,name}] def get_pathways_list(): pathways_json = None ...
pyta-uoft/pyta
examples/pylint/e1135_unsupported_membership_test.py
Python
gpl-3.0
92
0
lst = 1132424 if 'a' in lst: # Error on this line print('unsuppor
ted membership t
est')
ihmeuw/vivarium
docs/source/conf.py
Python
bsd-3-clause
7,710
0.000259
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # 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 # autoge
nerated file. # # All configuration values have a default; values that are commented out # serve
to show the default. import sys # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. from pathlib import Path from docutils.nodes i...
AEDA-Solutions/matweb
backend/Database/Models/RegistroLogin.py
Python
mit
777
0.060489
class RegistroLogin(object): def __init__ (self,dados=N
one):
if dados is not None: self.id = dados['id'] self.token = dados['token'] self.id_usuario = dados['id_usuario'] self.ip = dados['ip'] self.entrada = dados['entrada'] def getId(self): return self.id def setToken(self,token): self.token = token def getToken(self): return self.token def setI...
airodactyl/qutebrowser
qutebrowser/browser/webkit/webview.py
Python
gpl-3.0
9,195
0
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et: # Copyright 2014-2018 Florian Bruhin (The Compiler) <mail@qutebrowser.org> # # This file is part of qutebrowser. # # qutebrowser 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 S...
# FIXME:qtwebengine this is only used to set the zoom factor from # the QWebPage - we should get rid of it somehow (signals?) self.tab = tab self._tabdata = tab.data self.win_id = win_id self.scroll_pos = (-1, -1) self._old_scroll_pos = (-1, -1)
self._set_bg_color() self._tab_id = tab_id page = webpage.BrowserPage(win_id=self.win_id, tab_id=self._tab_id, tabdata=tab.data, private=private, parent=self) page.setVisibilityState( QWebPage.VisibilityS...
google/grr
grr/core/grr_response_core/lib/queues.py
Python
apache-2.0
822
0
#!/usr/bin/env python """Queue definitions. This module defines the queues where a worker may look for work.
""" from grr_response_core.lib import rdfvalue # Queues that a standard worker should work from, highest priority first. # # "W" and "CA" are deprecated, but included until we are sure that they are # empty. WORKER_LIST = list(map(rdfvalue.RDFURN, ["CA", "W", "E", "F", "H", "S"])) # The normal queue for enrollment...
t be kept synchronized with the default value # of FlowRunnerArgs.queue. FLOWS = rdfvalue.RDFURN("F") # The normal queue for hunts. Must be kept synchronized with the default value # of HuntRunnerArgs.queue. HUNTS = rdfvalue.RDFURN("H") # The normal queue for statistics processing. STATS = rdfvalue.RDFURN("S")
TempleBishop/guake
src/guake/main.py
Python
gpl-2.0
8,822
0.001814
#!/usr/bin/env python2 # -*- coding: utf-8; -*- """ Copyright (C) 2007-2012 Lincoln de Sousa <lincoln@minaslivre.org> Copyright (C) 2007 Gabriel Falcão <gabrielteratos@gmail.com> 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 th...
action='store', default='', help=_('Select a tab (SELECT_TAB is the index of the tab)')) parser.add_option('-g', '--selected-tab', dest='selected_tab', action='store_true', default=False, help=_('Return the selected tab index.')) parser.add_op...
st='command', action='store', default='', help=_('Execute an arbitrary command in the selected tab.')) parser.add_option('-i', '--tab-index', dest='tab_index', action='store', default='0', help=_('Specify the tab to rename. Def...
kived/py-cnotify
cnotify/__init__.py
Python
lgpl-2.1
8,208
0.00563
# -*- coding: utf-8 -*- #--------------------------------------------------------------------# # This file is part of Py-cnotify. # # # # Copyright (C) 2007, 2008 Paul Pogonyshev. # # ...
ar, C{fuel.predicate (lambda amount: amount > 0)} creates a condition that is true if C{fuel}’s value is greater than zero. Predicate conditions will recompute their state each time variable’s value changes and that’s the point in using them. Finally, two just constructed conditions are combined into a third conditio...
‘and’ operator (C{&}). This third condition will be true if and only if I{both} its term conditions are true. Conditions support four logic operations: negation, conjunction, disjunction and xoring (with these operators: C{~}, C{&}, C{|} and C{^}.) In addition, each condition has C{L{if_else <condition.AbstractCond...
ImmobilienScout24/succubus
src/integrationtest/python/logging_daemon.py
Python
apache-2.0
490
0
#!/usr/bin/env python """A daemon that relies on self.logger to be usabl
e""" from __future__ import print_function, absolute_import, division import os import sys import time from succubus import Daemon class MyDaemon(Daemon): def run(self): while True: self.logger.error("succubus test running") time.sleep(1) def m
ain(): daemon = MyDaemon(pid_file=os.environ['PID_FILE']) sys.exit(daemon.action()) if __name__ == '__main__': main()
alphagov/backdropsend
backdropsend/argumentsparser.py
Python
mit
1,401
0.004283
import argparse import select def no_piped_input(arguments): inputs_ready, _, _ = select.select([arguments.file], [], [], 0) return not bool(inputs_ready) def parse_args(args, input): parser = argparse.ArgumentParser() parser.add_argument('--url', help="URL of the target data-set", ...
required=False, default=5, type=float) parser.add_argument('--attempts', help="Number of times to attempt sending data. Default: 3", required=False, default=3, type=int) parser.add_argument('--failfast', help="Don't retry sending data", required=False, default=...
gparse.SUPPRESS, required=False, default=3, type=int) parser.add_argument('file', help="File containing JSON to send", nargs='?', type=argparse.FileType('r'), default=input) arguments = parser.parse_args(args) if arguments.failfast: ...
danielvdende/incubator-airflow
tests/contrib/sensors/test_aws_redshift_cluster_sensor.py
Python
apache-2.0
3,415
0.002343
# -*- coding: utf-8 -*- # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the #...
onn_id='aws_default',
cluster_identifier='test_cluster_not_found', target_status='cluster_not_found') self.assertTrue(op.poke(None)) if __name__ == '__main__': unittest.main()
xkmato/tracpro
tracpro/__init__.py
Python
bsd-3-clause
948
0.001055
from __future__ import absolute_import, unicode_literals # This will make sure the app is always
imported when # Django starts so that shared_task will use this app. from .celery import app as celery_app # noqa # NOTE: Version must be updated in docs/source/conf.py as
well. VERSION = (1, 4, 2, "final") def get_version(version): assert len(version) == 4, "Version must be formatted as (major, minor, micro, state)" major, minor, micro, state = version assert isinstance(major, int), "Major version must be an integer." assert isinstance(minor, int), "Minor version mu...
wikimedia/operations-software-deployment-trebuchet-trigger
trigger/config.py
Python
apache-2.0
5,847
0
# # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # ...
'required': True, 'default': 'trebuchet.local.LockDriver' }, 'deploy.service-driver': { 'required': True, 'default': 'trebuchet.local.ServiceDriver' }, 'deploy.report-driver': { 'required': True, ...
': True, 'default': 'trebuchet.local.CleanupDriver' }, } self._register_config(driver_config) for driver in driver_config: driver_config = self.config[driver] driver_name = driver.split('.')[1] LOG.debug('Getting config for driver: ...
modulus-sa/abcmd
tests/test_abcmd.py
Python
mit
5,599
0.000179
from abcmd import Command, Process import pytest @pytest.fixture() def run_cmd(mocker): return mocker.Mock(return_value=(0, "out", "err")) def test_Command_init_arguments(): class MyCommand(Command): def run(self): pass with pytest.raises(TypeError) as err: MyCommand() ...
def run(self): pass class SecondRunner(FirstRunner): command_second = "second" command_override = "second override" command = SecondRunner({}) attrs = ("command_first", "command_second
", "command_override") for attr in attrs: assert callable(getattr(command, attr)) def test_Command_instantiated_more_times(run_cmd): class MyCommand(Command): attribute = "command attribute {-o OPT}" def run(self, *args, **kwargs): self.attribute() command0 = MyComman...
GrahamDigital/django-scheduler
tests/test_calendar.py
Python
bsd-3-clause
4,809
0.00104
import datetime from django.test import TestCase from django.utils import timezone from schedule.models import Event, Rule, Calendar, CalendarRelation class TestCalendar(TestCase): def setup(self): pass def __create_event(self, start, end): data = { 'title': 'Recent Event', ...
t(start_after, end_after) calendar.events.add(event) occurrences = list(calendar.occurrences_after(timezone.now())) self.assertEqual(len(occurrences), 1) self.assertEqual(occurrences[0].start, start_after) self.assertEqual(occurrences[0].end, end_after) def test_occurrences_...
ndar() calendar.save() start_after = timezone.now() + datetime.timedelta(days=-1) end_after = start_after + datetime.timedelta(hours=1) event = self.__create_event(start_after, end_after) calendar.events.add(event) occurrences = list(calendar.occurrences_after(timezone.no...
matt-gardner/deep_qa
tests/layers/bigru_index_selector_test.py
Python
apache-2.0
1,944
0.002572
# pylint: disable=no-self-use import numpy from numpy.testing import assert_almost_equal from keras.layers import Input from keras.models import Model from deep_qa.layers import BiGRUIndexSelector class TestBiGRUIndexSelector(): def test_batched_case(self): document_length = 5 gru_hidden_dim = 2...
4, 0.7]]]) gru_b_input = numpy.array([[[0.7, 0.2], [0.9, 0.1], [0.3, 0.8], [0.2, 0.6], [0.7, 0.2]], [[0.2, 0.1], [0.3, 0.6], [0.2, 0.8], [0.3, 0.6], [0.4, 0.4]]]) expected_output = numpy.array([[0.9, 0.2, 0.2, 0.6], [0.7, 0.1, 0.3, 0.6]]) # Testing th
e general single-batch case. result = model.predict([document_indices, gru_f_input, gru_b_input]) assert_almost_equal(result, expected_output)
phildini/cards-against-django
cah/settings/prod.py
Python
mit
923
0.002167
from .base import * import dj_database_url try: from urlparse import urlparse except ImportError: from urllib.parse import urlparse DEBUG = False TEMPLATE_DEBUG = DEB
UG DATABASES['default'] = dj_database_url.config() REDIS_URL = urlparse(get_env_variable('REDISCLOUD_URL')) SOCKETIO_URL = get_env_variable("SOCKETIO_URL") # Honor the 'X-Forwarded-Proto' header for request.is_secure() SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') ALLOWED_HOSTS = ['.thisisnotthatga...
7.0.0.1'] TINTG_SERVER = 'http://thisisnotthatgame.com' STATIC_URL = 'http://philipjohnjames.com/applesanon/static/' TEMPLATE_DIRS = ( PROJECT_ROOT.child('templates'), ) INSTALLED_APPS += ( 'gunicorn', ) CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', ...
apophys/freeipa
ipaserver/advise/plugins/legacy_clients.py
Python
gpl-3.0
15,674
0
# Authors: Ana Krivokapic <akrivoka@redhat.com> # # Copyright (C) 2013 Red Hat # see file 'COPYING' for use and warranty information # # 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 ver...
n RHEL5.2 will not be ' 'able to interoperate with IPA server 3.x.') super(config_redhat_sssd_before_1_9, self).configure_ca_cert() @register() class config_generic
_linux_sssd_before_1_9(config_base_legacy_client): """ Legacy client configuration for non Red Hat based linux systems, using SSSD. """ description = ('Instructions for configuring a system with an old version ' 'of SSSD (1.5-1.8) as a FreeIPA client. This set of ' ...
amalshehu/exercism-python
etl/etl.py
Python
mit
382
0
# File: etl.py # Purpose: To do the `Transform` step of an Extract-Transform-Load. # Programmer: Amal Shehu # Course: Exercism # Date:
Thursday 22 September 2016, 03:40 PM def transform(words): new_words = dict() for point, letters in words.items(): for letter in l
etters: new_words[letter.lower()] = point return new_words
eduNEXT/edx-platform
cms/lib/xblock/tagging/migrations/0002_auto_20170116_1541.py
Python
agpl-3.0
545
0.00367
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('tagging', '00
01_initial'), ] operations = [ migrations.AlterModelOptions( name='tagavailablevalues', options={'ordering': ('id',), 'verbose_name': 'available tag value'}, ), migrations.AlterModelOptions( name='tagcategories', options={'ordering': ('tit...
), ]
remram44/api_stats
api_stats/list.py
Python
bsd-3-clause
1,785
0
from __future__ import absolute_import, division, unicode_literals import argparse import json import locale import sys from api_stats import setup_logging, logger from api_stats.utils import PY3, iteritems def print_tree(keys, level=0): """Print keys in a nested dictionary structure. """ for k, v in so...
logger.info("Read %d lines", nb_l
ines) finally: fp.close() print_tree(keys) if __name__ == '__main__': main()
Axik/django-coverage-py3
setup.py
Python
apache-2.0
1,632
0.010417
#!/usr/bin/env python from distutils.core import setup from django_coverage import __version__ setup( name='django-coverage', version=__version__, author='George Song', author_email='george@55minutes.com', maintainer = 'Mikhail Korobov', maintainer_email = 'kmike84@gmail.com', ...
" "much of your code is exercised with your tests.", license = 'Apache License 2.0', packages=['django_coverage', 'django_coverage.management', 'django_coverage.management.commands', 'django_coverage.utils', 'django_co...
e_report.templates'], requires = ['django (>=1.2)', 'coverage (>= 2.85)'], classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Softwa...
biosustain/cameo
tests/test_strain_design_heuristics.py
Python
apache-2.0
55,803
0.00276
# Copyright 2014 Novo Nordisk Foundation Center for Biosustainability, DTU. # # 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 requi...
ic_difference(sol1)) assert l == 1, "Difference between Solution 2 and 1 is (%s)" % sol2.symmetric_difference(sol1) l = len(sol3.symmetric_difference(sol2)) assert l == 1, "Difference between Solution 3 and 1 is (%s)" % sol3.symmetric_difference(sol2) l = len(sol3.symmetric_difference(so...
etric_difference(sol1) assert sol1.improves(sol2), "Solution 1 is better than Solution 2" assert sol3.improves(sol2), "Solution 3 is better than Solution 2" assert not sol3.improves(sol1), "Solution 3 does not improve Solution
census-instrumentation/opencensus-python
contrib/opencensus-ext-threading/opencensus/ext/threading/trace.py
Python
apache-2.0
4,939
0
# Copyright 2018, OpenCensus Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in w...
_kwargs["propagator"] = _tracer.propagator return submit_func(self, wrapped_func, *args, **wrapped_kwargs) return call class wrap_task_func(object): """Wrap the function given to apply_async to get the tracer from context, execute the function then clear t
he context.""" def __init__(self, func): self.func = func def __call__(self, *args, **kwargs): kwds = kwargs.pop("kwds") span_context_binary = kwargs.pop("span_context_binary") propagator = binary_format.BinaryFormatPropagator() kwargs["span_context"] = propagator.from...
odedlaz/passgen
passgen/api.py
Python
mit
289
0
from flask import render_template, send_from_directory from passgen
import app, static_dir @app.route('/assets/<path:path>') def send_assets(path): return send_from_directory(static_dir, path) @app.route('/', methods=['GET']) def index(): return render_template('i
ndex.html')
mrunge/openstack_horizon
openstack_horizon/dashboards/project/data_processing/job_binaries/urls.py
Python
apache-2.0
1,483
0
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance
with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # i...
django.conf.urls import patterns from django.conf.urls import url import openstack_horizon.dashboards.project.data_processing. \ job_binaries.views as views urlpatterns = patterns('', url(r'^$', views.JobBinariesView.as_view(), name='index'), ...
john123951/gold.icbc.watcher
src/util/YamlConfig.py
Python
mit
304
0
import yam
l from core.AbstractConfig import AbstractConfig class YamlConfig(AbstractConfig): def __init__(self, config_path): self.path = config_path with open(config_path) as fr: self.conf = yaml.load(fr) pass def get_dict(self): return self.con
f
Mechazawa/Nimdok
nimdok/models/ignored_domains.py
Python
gpl-2.0
906
0.002208
from sqlalchemy import Column, String from .shared import declarative_base, db class IgnoredDomainModel(declarative_base): __tablename__ = 'ignored_domains' def __init__(self, domain): self.domain = domain domain = Column(String, unique=True, primary_key=True) @staticmethod def is_ignor...
db.session.commit() return True except: return False @staticmethod def remove(domain):
try: IgnoredDomainModel.query.filter_by(domain=domain.upper()).remove() db.session.commit() return True except: return False
mrachinskiy/blender-addon-jewelcraft
op_product_report/report_get.py
Python
mit
5,560
0.001259
# ##### BEGIN GPL LICENSE BLOCK ##### # # JewelCraft jewelry design toolkit for Blender. # Copyright (C) 2015-2019 Mikhail Rachinskiy # # 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, eith...
= "MESH" and ob.parent.instance_type == "NONE" ): df_leftovers = True # Find overlaps # --------------------------- overlaps = False if self.prefs.product_report_use_overlap:
thold = UScale.to_scene(0.1) overlaps = asset.gem_overlap(ob_data, threshold=thold, first_match=True) # Find hidden gems # --------------------------- hidden = False if self.prefs.product_report_use_hidden_gems: for ob in scene.objects: i...
whitehorse-io/encarnia
evennia/evennia/utils/evmore.py
Python
mit
9,455
0.002327
# -*- coding: utf-8 -*- """ EvMore - pager mechanism This is a pager for displaying long texts and allows stepping up and down in the text (the name comes from the traditional 'more' unix command). To use, simply pass the text through the EvMore object: from evennia.utils.evmore import EvMore text = some_lo...
e, session=self._session, **self._kwargs) def page_top(self): """ Display the top page """ self._pos = 0 self.display() def page_end(self): """ Display the bottom page. """ self._pos = self._npages - 1 self.display() def page...
if self._pos >= self._npages - 1: # exit if we are already at the end self.page_quit() else: self._pos += 1 self.display() if self.exit_on_lastpage and self._pos == self._pos >= self._npages - 1: self.page_quit() def page_back(se...
ic-labs/django-icekit
icekit/plugins/map/tests.py
Python
mit
2,961
0.002702
from mock import patch from django.contrib.contenttypes.models import ContentType from django.contrib.sites.models import Site from django.contrib.auth import get_user_model from django.core import exceptions from django_dynamic_fixture import G from django_webtest import WebTest from icekit.models import Layout from...
self.page_1.status = LayoutPage.PUBLISHED self.page_1.save() self.map_1 = fluent_contents.create_content_instance( models.MapItem, self.page_1,
_embed_code=self.embed_code, ) self.map_item = models.MapItem( parent_type=ContentType.objects.get_for_model(type(self.page_1)), parent_id=self.page_1.id, placeholder=self.page_1.get_placeholder_by_slot('main')[0], _embed_code=self.embed_code...
okin/doit
tests/test_doit_cmd.py
Python
mit
2,331
0.001287
import pytest from mock import Mock from doit import get_var from doit.exceptions import InvalidCommand from doit.doit_cmd import DoitMain from doit.cmd_run import Run from doit.cmd_list import List def cmd_main(args): return DoitMain().run(args) class TestRun(object): def test_version(self, capsys): ...
) monkeypatch.setattr(List, "execute", mock_list) cmd_main(["list"]) assert 1 == mock_list.call_count def test_cmdline_vars(self, monkeypatch): mock_run = Mock() monkeypatch.setattr(Run, "execute", mock_run) cmd_main(['x=1', 'y=abc']) assert '1' == get_var('x...
r('y') def test_cmdline_vars_not_opts(self, monkeypatch): mock_run = Mock() monkeypatch.setattr(Run, "execute", mock_run) cmd_main(['--z=5']) assert None == get_var('--z') class TestErrors(object): def test_interrupt(self, monkeypatch): def my_raise(*args): ...
vikkyrk/incubator-beam
sdks/python/apache_beam/examples/wordcount_debugging_test.py
Python
apache-2.0
2,013
0.004968
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not us...
cense for the specific language governing permissions and # limitations under the License. # """Test for the debugging wordcount example.""" import logging import re import tempfile import unittest from apache_beam.examples import wordcount_debugging class WordCountTest(unittest.TestCase): SAMPLE_TEXT = 'xx yy ...
File(delete=False) as f: f.write(contents) return f.name def get_results(self, temp_path): results = [] with open(temp_path + '.result-00000-of-00001') as result_file: for line in result_file: match = re.search(r'([A-Za-z]+): ([0-9]+)', line) if match is not None: ...
Gimnasist/reagentterminal
interface/finishedDlg.py
Python
mit
2,080
0.005288
#!-*-coding:utf-8-*- import sys # import PyQt4 QtCore and QtGui modules from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * from PyQt5.QtSerialPort import * import finishedDialog_ui class finishedDlg(QDialog, finishedDialog_ui.Ui_finishedDialog): """MainWindow inherits QMainWindow"...
ed.emit() self.hide() def prepareUiFinishDlg(self, barcodedialogpointer): self.seconds_remain=20 self.timertoactivatebutton.start(1000) self.ui.storagePlaceLabel.setText(barcodedialogpointer.weightingDLGPointer.reag_storage)
self.ui.restartPushButton.setEnabled(False) self.show() # def on_weightLineEdit_returnPressed(self): # print("Weitings are optained") #-----------------------------------------------------# if __name__ == '__main__': # create application app = QApplication(sys.argv) app.setApp...
onepercentclub/onepercentclub-site
onepercentclub/settings/base.py
Python
bsd-3-clause
20,342
0.001032
# coding=utf-8 # Django settings for bluebottle project. import os, datetime # Import global settings for overriding without throwing away defaults from django.conf import global_settings from django.utils.translation import ugettext as _ from admin_dashboard import * from .payments import * # Set PROJECT_ROOT to th...
available in templates. 'django.core.context_processors.request',
'django.core.context_processors.i18n', 'bluebottle.utils.context_processors.installed_apps_context_processor', 'bluebottle.utils.context_processors.git_commit', 'bluebottle.utils.context_processors.conf_settings', 'bluebottle.utils.context_processors.google_maps_api_key', 'bluebottle.utils.conte...
Nachtfeuer/concept-py
examples/hfractal.py
Python
mit
4,958
0.002824
#!/usr/bin/python """ Visualizing H fractal with tkinter. ======= License ======= Copyright (c) 2017 Thomas Lehmann 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 ...
self.scale -= 0.05 self.repaint(self.canvas.winfo_width(), self.canvas.winfo_height()) def on_key_plus(self, event): """Increase hfractal depth.""" if self.depth < 7: self.depth += 1 self.repaint(self.canvas.winfo_width(), self.canva...
on_key_minus(self, event): """Decrease hfractal depth.""" if self.depth > 0: self.depth -= 1 self.repaint(self.canvas.winfo_width(), self.canvas.winfo_height()) def on_configure(self, event): """Called to react on changes to width and height."...
ge0rgi/cinder
cinder/volume/drivers/hitachi/vsp_iscsi.py
Python
apache-2.0
6,591
0
# Copyright (C) 2016, Hitachi, 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...
ration.append_config_values(common.common_opts) self.configuration.append_config_values(iscsi_opts) self.common = utils.import_object( self.configuration, _DRIVER_INFO, kwargs.get('db')) def check_for_setup_error(self):
"""Error are checked in do_setup() instead of this method.""" pass @utils.output_start_end_log def create_volume(self, volume): """Create a volume and return its properties.""" return self.common.create_volume(volume) @utils.output_start_end_log def create_volume_from_snapshot(...
dob71/x2swn
skeinforge/fabmetheus_utilities/miscellaneous/fabricate/extrude.py
Python
gpl-3.0
14,234
0.024519
""" Extrude is a script to display and extrude a gcode file. It controls the extruder and movement. It can read linear and helical move commands. It saves a log file with the suffix _log. To run extrude, install python 2.x on your machine, which is avaliable from http://www.python.org/download/ Then in the folder w...
erial # Imp
ort the pySerial modules. except: print('You do not have pySerial installed, which is needed to control the serial port.') print('Information on pySerial is at:\nhttp://pyserial.wiki.sourceforge.net/pySerial') from skeinforge_tools.skeinforge_utilities.vector3 import Vector3 from skeinforge_tools.skeinforge_utilitie...
morefigs/py-ic-imaging-control
pyicic/IC_Exception.py
Python
mit
1,565
0.005112
#!/usr/bin/env python # -*- coding: utf-8 -*- class IC_Exception(Exception): """ An exception for the IC imaging control software. It contains a message property which is a string indicating what went wrong. error code -3 has multiple possible interpretations, sometimes from the same function! ...
@property def error_code(self): return self._error_code _error_codes = { # IC errors 1: 'IC SUCCESS', 0: 'IC ERROR', -1: 'IC NO HANDLE', -2: 'IC NO DEVICE', -3: 'IC NOT AVAILABLE / IC NO PROPERTYSET / IC DEFAULT WINDOW SIZE SET / IC ...
ITEM NOT AVAILABLE', -5: 'IC PROPERTY ELEMENT NOT AVAILABLE', -6: 'IC PROPERTY ELEMENT WRONG INTERFACE', # other errors -100: 'UNKNOWN ERROR', -101: 'UNKNOWN DEVICE FEATURE', -102: 'VIDEO NORM INDEX OUT OF RANGE', -103: 'VIDEO FORMAT INDEX OUT OF RANGE', ...
c4fcm/CivilServant
alembic/versions/a0f4fda7588f_add_model_for_snapshots_of_.py
Python
mit
4,337
0.011759
"""Add model for snapshots of ExperimentThings Revision ID: a0f4fda7588f Revises: ae72c799d321 Create Date: 2016-11-26 22:05:26.728790 """ # revision identifiers, used by Alembic. revision = 'a0f4fda7588f' down_revision = 'ae72c799d321' branch_labels = None depends_on = None from alembic import op import sqlalchemy...
], unique=False) ### end Alembic commands ### def downgrade_production(): ### commands auto generated by Alembic - please adjust! ### op.drop_index(op.f('ix_experiment_thing_snapshots_experiment_thing_id'), table_name='experiment_thing_snapshots') op.drop_index(op.f('ix_experiment_thing_s
napshots_experiment_id'), table_name='experiment_thing_snapshots') op.drop_table('experiment_thing_snapshots') ### end Alembic commands ###
DONIKAN/django
tests/staticfiles_tests/settings.py
Python
bsd-3-clause
1,039
0
from __future__ import unicode_literals import os.path fro
m django.utils._os import upath TEST_ROOT = os.path.dirname(upath(__file__)) TESTFILES_PATH = os.path.join(TEST_ROOT, 'apps', 'test', 'static', 'test') TEST_SETTINGS = { 'DEBUG': True, 'MEDIA_URL': '/media/', 'STATIC_URL': '/static/', 'MEDIA_ROOT': os.path.join(TEST_ROOT, 'project', 'site_m
edia', 'media'), 'STATIC_ROOT': os.path.join(TEST_ROOT, 'project', 'site_media', 'static'), 'STATICFILES_DIRS': [ os.path.join(TEST_ROOT, 'project', 'documents'), ('prefix', os.path.join(TEST_ROOT, 'project', 'prefixed')), ], 'STATICFILES_FINDERS': [ 'django.contrib.staticfiles.f...
espressopp/espressopp
src/integrator/AssociationReaction.py
Python
gpl-3.0
938
0.013859
r""" ***************************************** espressopp.integ
rator.AssociationReaction ***************************************** """ from espressopp.esutil import cxxinit from espressopp import pmi from espressopp.integrator.Extension import * from _espressopp import integrator_AssociationReaction class AssociationReactionLocal(ExtensionLoc
al, integrator_AssociationReaction): def __init__(self, system, vl, fpl, domdec): if not (pmi._PMIComm and pmi._PMIComm.isActive()) or pmi._MPIcomm.rank in pmi._PMIComm.getMPIcpugroup(): cxxinit(self, integrator_AssociationReaction, system, vl, fpl, domdec) if pmi.isController : class Asso...
superstack/nova
nova/api/ec2/admin.py
Python
apache-2.0
13,151
0.000608
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compli...
%(project)s") % locals() LOG.audit(msg, context=context) else: msg = _("Removing sitewide role %(role)s" " from user %(user)s") % locals() LOG.audit(msg, context=context) manager.AuthManager().remove_role(user, role, project...
"""Generates and returns an x509 certificate for a single user. Is usually called from a client that will wrap this with access and secret key info, and return a zip file. """ if project is None: project = name project = manager.AuthManager().get_projec...
montilab/Hydra
hydra_pkg/__init__.py
Python
apache-2.0
65
0.015385
imp
ort os.path RNASEQ_PIPELINE_DIR = os.path.dirname(__file__)
MaximilianKindshofer/webeats
webeats/webeats/wsgi.py
Python
gpl-3.0
392
0
""" WSGI config for webeats project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("D
JANGO_SETT
INGS_MODULE", "webeats.settings") application = get_wsgi_application()
google-research/google-research
smu/geometry/smu_molecule.py
Python
apache-2.0
12,148
0.006503
# coding=utf-8 # Copyright 2022 The Google Research Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicab...
ot_bonded @consider_not_bonded.setter def consider_not_bonded(self, value): self._consider_not_bonded = value @property def ring_atom_count_cannot_decrease(self): return self._ring_atom_count_cannot_decrease @ring_atom_count_cannot_decrease.setter def ring_atom_count_cannot_decrease(self, value):...
_atom_count_cannot_decrease = value def add_bond(a1, a2, btype, destination): """Add a new Bond to `destination`. Args: a1: atom a2: atom btype: bond type. destination: """ destination.bonds.append( dataset_pb2.BondTopology.Bond( atom_a=a1, atom_b=a2, bond_...
clustervision/trinityX
doc/conf.py
Python
gpl-2.0
9,991
0.0005
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # TrinityX documentation build configuration file, created by # sphinx-quickstart on Tue Oct 25 14:04:29 2016. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # a...
ones. extensions = [ # 'rinoh.frontend.sphinx', # 'sphinx.ext.githubpages', ] # Add any paths that contain templates here, relative to this directory. t
emplates_path = ['_templates'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # # source_suffix = ['.rst', '.md'] source_suffix = '.rst' # The encoding of source files. # # source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General infor...
mbeckersys/gnatprove_unitstats
gnatprove_unitstats.py
Python
mit
22,049
0.01093
#!/usr/bin/python # This script parses GNATprove's JSON output and gives per-unit verification # statistics, as well as overall statistics. Supersedes gnatprove_filestats.py # # (C) 2017 TU Muenchen, RCS, Martin Becker <becker@rcs.ei.tum.de> from __future__ import print_function import sys, getopt, os, inspect, time,...
"col": .., "rule": .., "severity": .., "entity": {"name": .., "sloc": [{}]}, "tracefile": .., "msg_id": .., "how_proved": ..} # # 3) "proof" : prover results. list of dicts
# each item has the same as flow, but additionally {"cntexmp":{}, "suppressed" : <string>}. Here, rule=<VC_PRECONDITION|VC_DISCRIMINANT_CHECK|...> # # 4) "assumptions" : not interesting here. we remove it. # # Thus, coverage comes from "spark", succ...
Drvanon/Game
venv/lib/python3.3/site-packages/tornado/test/websocket_test.py
Python
apache-2.0
2,935
0.000681
from tornado.concurrent import Future from tornado import gen from tornado.httpclient import HTTPError from tornado.log import gen_log from tornado.testing import AsyncHTTPTestCase, gen_test, bind_unused_port, ExpectLog from tornado.web import Application, RequestHandler from tornado.websocket import WebSocketHandler, ...
ion.code, 404) @gen_test def test_websocket_http_success(self): with self.assertRaises(WebSocketError): yield websocket_connect( 'ws://localhost:%d
/non_ws' % self.get_http_port(), io_loop=self.io_loop) @gen_test def test_websocket_network_fail(self): sock, port = bind_unused_port() sock.close() with self.assertRaises(HTTPError) as cm: with ExpectLog(gen_log, ".*"): yield websocket_connec...
amperser/proselint
tests/__init__.py
Python
bsd-3-clause
27
0
"""Tests fo
r proselint.
"""
GaretJax/pop-utils
poputils/conf.py
Python
mit
373
0.005362
import os from lxml import etree def schema(name): """ Retrieves a schema by name from the 'schemata' directory and wraps it in an lxm
l.etree.XMLSchema object. """ schema = os.path.join(os.path.dirname(__file__), 'schemata', name + '.xsd') document = etree.parse(schema) # Will raise if schema does not exist retur
n etree.XMLSchema(document)
maloep/xbmc-s04tv
default.py
Python
gpl-2.0
10,118
0.008599
# -*- coding: utf-8 -*- # Copyright (C) 2015 Malte Loepmann (maloep@googlemail.com) # # 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 la...
e: addLink(title, url, mode, im
ageUrl, '', extraInfo) def getVideoUrl(url, doc): xbmc.log('getVideoUrl: url=' +url) is_logged_in, has_schalke_tv = login() if not is_logged_in: return isPayedContent = xbmc.getInfoLabel( "ListItem.Property(isPayedContent)" ) == 'True' #payedContent requires payed Schalke TV subscription...
ProfessorX/Config
.PyCharm30/system/python_stubs/-1247972723/PyKDE4/kio/KBookmarkExporterBase.py
Python
gpl-2.0
652
0.007669
# encoding: utf-8 # module PyKDE4.kio # from /usr/lib/python2.7/dist-packages/PyKDE4/kio.so # by generator 1.135 # no doc # imports import PyKDE4.kdeui as __PyKDE4_kdeui import PyQt4.QtCore as __PyQt4_QtCore import PyQt4.
QtGui as __PyQt4_QtGui class KBookmarkExporterBase(): # skipped bases: <type 'sip.wrapper'> # no doc def write(self, *args, **kwargs): # real signature unknown pass def __init__(self, *args, **k
wargs): # real signature unknown pass __weakref__ = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """list of weak references to the object (if defined)"""
glassesfactory/Shimehari
shimehari/session.py
Python
bsd-3-clause
8,917
0.001541
#!/usr/bin/env python # -*- coding: utf-8 -*- u""" =============================== Shimehari.session ~~~~~~~~~~~~~~~~~ セッション管理 =============================== """ from datetime import datetime from werkzeug.contrib.securecookie import SecureCookie from werkzeug.contrib.sessions import SessionStore as Sessi...
======================= """ class NullSession(SecureCookieSession): def _fail(self, *args, **kwargs): raise RuntimeError('Null Session!!!')
__setitem__ = __delitem__ = clear = pop = popitem = setdefault = update = _fail del _fail u""" =============================== ::pkg:: Shimehari.sessions _SessionStore ~~~~~~~~~~~~~ werkzeug のセッションストアに多少機能を追加します。 =============================== """ class _SessionStore(SessionStoreBase): nu...
erikdejonge/pyprofiler
pyprofiler/__init__.py
Python
gpl-2.0
2,901
0.003102
# coding=utf-8 """ Profiler utility for python Erik de Jonge erik@a8.nl license: gpl2 """ from __future__ import print_function from __future__ import unicode_literals from __future__ import division from __future__ import absolute_import from future import standard_library standard_library.install_aliases() import os...
, cglobals, clocals): """ @type method: str, unicode @type cglobals: dict @type clocals: dict @return: None """ cProfile.runctx(method + "()", globals=cglobals, locals=clocals, filename=method + ".profile") os.system("pyth
on /usr/local/lib/python2.7/site-packages/runsnakerun/runsnake.py " + method + ".profile") os.system("rm " + method + ".profile") def graph_profile_program(sourcefile): """ @type sourcefile: str, unicode @return: None """ if 0 != os.system("python -m cProfile -o output.pstats ./" + sourcefile)...
shafeeqr2/python
Snake Game Redevelopment/Source/Food.py
Python
gpl-3.0
1,067
0.013121
import pygame import random class Food: """ Food class to encapsulate position of food particle state variables:
position: pygame.Rect object """ def __init__(self): """ constructor for Food.py Transition: initializes a food object with random position input:none output:none """ #width of block blockWidth = 10 #lengt...
scaleFactor = 10 #offset to skip the header (which contains score) offset = 20 #randomly generate the a x position on the screen to display the food xVal = random.randrange(55) #randomly generate the an y position on the screen to display the food yVal =...
renatoGarcia/tangram
test/manual/input_surface.py
Python
lgpl-3.0
1,951
0.002563
# Copyright 2017 The Tangram Developers. See the AUTHORS file at the # top-level directory of this distribution and at # https://github.com/renatoGarcia/tangram/blob/master/AUTHORS. # # This file is part of Tangram. # # Tangram is free software: you can redistribute it and/or modify # it under the terms of the GNU Less...
] ) ) ) @mw.input_surface.drawn() def selects(sketch, button, modifiers): envelope = mw.input_surface.envelope mask = sketch.asarray(shape=envelope.shape, dtype=np.bool, fill=True) mw.selection.mask[:] = mask mw.show() mw.destroy.wait()
if __name__ == '__main__': main()
stackforge/xstatic-angular-lrdragndrop
xstatic/pkg/angular_lrdragndrop/__init__.py
Python
mit
1,969
0.007618
""" XStatic resource package See package 'XStatic' for documentation and basic tools. """ # official name, upper/lowercase allowed, no spaces DISPLAY_NAME = 'Angular-lrdragndrop' # name used for PyPi PACKAGE_NAME = 'XStatic-%s' % DISPLAY_NAME NAME = __name__.split('.')[-1] # package name (e.g. 'foo' or 'foo_bar') ...
e upstream # version number BUILD = '4' # our package build number, so we can release new builds # with fixes for xstatic stuff. PACKAGE_VERSION = VERSION + '.' + BUILD # version used for PyPi DESCRIPTION = "%s %s (XStatic packaging standard)" % (DISPLAY_NAME, VERSION) PLATFORMS = 'any'...
= 'drag-n-drop angular table lrdragndrop xstatic' # XStatic-* package maintainer: MAINTAINER = 'Thai Tran' MAINTAINER_EMAIL = 'tqtran@us.ibm.com' # this refers to the project homepage of the stuff we packaged: HOMEPAGE = 'https://github.com/lorenzofox3/lrDragNDrop' # this refers to all files: LICENSE = 'MIT' from o...
ebmdatalab/openprescribing
openprescribing/frontend/management/commands/preview_measure.py
Python
mit
4,017
0.001494
import re import sys import requests from django.conf import settings from django.core.management import BaseCommand from requests.exceptions import InvalidJSONError, RequestException from .import_measures import BadRequest from .import_measures import Command as ImportMeasuresCommand from .import_measures import Imp...
re_definitions/" r"(?P<measure_id>[^/\.]+)" r"\.json" r"$", github_url, ) if not match: raise BadRequest( "Expecting a URL in the format:\n" "https
://github.com/ebmdatalab/openprescribing/blob/<GIT_REF>/" "openprescribing/measure_definitions/<MEASURE_ID>.json\n" "\n" "You can get this URL by finding the measure file in your branch on " "Github:\n" "https://github.com/ebmdatalab/openprescribing/branches\n...
lpramuk/robottelo
tests/foreman/cli/test_rhcloud_insights.py
Python
gpl-3.0
1,546
0.002587
"""CLI tests for Insights part of RH Cloud - Inventory plugin. :Requirement: RH Cloud - Inventory :CaseAutomation: Automated :CaseLevel: System :CaseComponent: RHCloud-Inventory :Assignee: jpathan :TestType: Functional :CaseImportance: High :Upstream: No """ import pytest from broker.broker import VMBroker fro...
ure_rhai_client(default_sat, activation_key.name, org.label, distro) result = vm.run('insights-client --test-connection') assert result.status == 0, ( 'insights-client --test-connection failed.\n' f'status: {result.status}\n' f'stdout: {result.stdout}\n'
f'stderr: {result.stderr}' )
mediafactory/yats
modules/yats/fields.py
Python
mit
2,574
0.001943
# -*- coding: utf-8 -*- from django.utils.translation import ugettext_lazy as _ from django import forms from django.conf import settings from django.forms.utils import ValidationError from os import chmod import hashlib from io import BytesIO try: import pyclamd except Exception: pass class yatsFileField(form...
chmod(data.temporary_file_path(), 0o664) result = cd.scan_file(data.temporary_file_path()) else:
if hasattr(data, 'read'): result = cd.scan_stream(data.read()) else: result = cd.scan_stream(data['content']) except: from socket import gethostname raise ValidationError(self.error_messages['viru...
ioram7/keystone-federado-pgid2013
build/sqlalchemy/test/sql/test_quote.py
Python
apache-2.0
9,788
0.017981
from sqlalchemy import * from sqlalchemy import sql, schema from sqlalchemy.sql import compiler from test.lib import * class QuoteTest(fixtures.TestBase, AssertsCompiledSQL): __dialect__ = 'default' @classmethod def setup_class(cls): # TODO: figure out which databases/which identifiers allow speci...
# *are* quoted? ) a = t1.select().alias('anon') b = select([1], a.c.ColumnOne==2, from_obj=a) self.assert_compile(b, "SELECT 1 FR
OM (SELECT FooBar.TableOne.ColumnOne AS "\ "ColumnOne FROM FooBar.TableOne) AS anon WHERE anon.ColumnOne = :ColumnOne_1" ) def test_table_quote_flag(self): metadata = MetaData() t1 = Table('TableOne', metadata, Column('id', Integer), quote...
gforcada/zest.releaser
zest/releaser/fullrelease.py
Python
gpl-2.0
847
0
"""Do the prerelease, actual release and post release in one fell swoop! """ import logging import os from zest.releaser im
port prerelease from zest.releaser import release from zest.releaser import postrelease from zest.releaser import utils logger = logging.getLogger(__name__) def main(): logging.basicConfig(level=utils.loglevel(), format="%(le
velname)s: %(message)s") logger.info('Starting prerelease.') original_dir = os.getcwd() prerelease.main() os.chdir(original_dir) logger.info('Starting release.') tagdir = release.main(return_tagdir=True) os.chdir(original_dir) logger.info('Starting postrelease.') postrelease.main() ...
zlorb/mitmproxy
mitmproxy/proxy/__init__.py
Python
mit
201
0
from .config import ProxyConfig from .root_context import RootCon
text from .server import ProxyServer, DummyServer __all__ = [ "ProxyServer", "DummyServer", "ProxyConfig",
"RootContext" ]
job/pdns
regression-tests.api/runtests.py
Python
gpl-2.0
4,913
0.001425
#!/usr/bin/env python # # Shell-script style. import os import requests import shutil import subprocess import sys import tempfile import time SQLITE_DB = 'pdns.sqlite3' WEBPORT = '5556' APIKEY = '1234567890abcdefghijklmnopq-key' PDNSUTIL_CMD = ["../pdns/pdnsutil", "--config-dir=."] NAMED_CONF_TPL = """ # Generated ...
ti
me.sleep(0.5) if not available: print "Webserver port not reachable after 10 tries, giving up." pdns.terminate() pdns.wait() sys.exit(2) print "Running tests..." rc = 0 test_env = {} test_env.update(os.environ) test_env.update({ 'WEBPORT': WEBPORT, 'APIKEY': APIKEY, 'DAEMON': daemon, '...
scheib/chromium
third_party/blink/web_tests/external/wpt/xhr/resources/access-control-allow-with-body.py
Python
bsd-3-clause
476
0
def main(request, response): headers = {
b"Cache-Control": b"no-store", b"Access-Control-Allow-Headers": b"X-Requested-With", b"Access-Control-Max-Age": 0, b"Access-Control-Allow-Origin": b"*", b"Access-Control-Allow-Methods": b"*", b"Vary": b"Accept-Encoding", b"Content-Type": b"text/plain" }
for (name, value) in headers.items(): response.headers.set(name, value) response.content = b"PASS"
MKTCloud/MKTCloud
openstack_dashboard/usage/tables.py
Python
apache-2.0
2,531
0.000395
from django.core import urlresolvers from django.utils.translation import ugettext_lazy as _ from django.template.defaultfilters import timesince, floatformat from horizon import tables from horizon.templatetags.sizeformat import mbformat class CSVSummary(tables.LinkAction): name = "csv_summary" verbose_name...
erbose_name=_("Project Name")) disk_hours = tables.Column('disk_gb_hours',
verbose_name=_("Disk GB Hours"), filters=(lambda v: floatformat(v, 2),)) def get_object_id(self, datum): return datum.tenant_id class Meta: name = "global_usage" verbose_name = _("Usage Summary") columns = ("tenant", "vcp...
dlintott/gns3
src/GNS3/Ui/Form_NewProject.py
Python
gpl-2.0
5,837
0.004283
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'Form_NewProject.ui' # # Created: Mon Sep 9 21:29:21 2013 # by: PyQt4 UI code generator 4.8.6 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except...
Box) self.label_2.setText(QtGui.QApplication.translate("NewProject", "Project name:", None, QtGui.QApplication.UnicodeUTF8)) self.label_2.setObjectName(_fromUtf8("label_2")) self.gridLayout.addWidget(self.label_2, 0, 0, 1, 1) self.ProjectName = QtGui.QLineEdit(self.groupBox) self...
bel = QtGui.QLabel(self.groupBox) self.label.setText(QtGui.QApplication.translate("NewProject", "Project directory:", None, QtGui.QApplication.UnicodeUTF8)) self.label.setObjectName(_fromUtf8("label")) self.gridLayout.addWidget(self.label, 1, 0, 1, 1) self.ProjectPath = QtGui.QLineEdit(s...
jumoconnect/openjumo
jumodjango/settings.py
Python
mit
8,951
0.002905
from celery.schedules import crontab import djcelery from django.conf.global_settings import EMAIL_BACKEND import os, sys, logging import subprocess ############################### # MISC # ############################## ROOT_PATH = os.path.dirname(__file__) def to_absolute_path(path): re...
TING_KEY = "task.default" CELERY_ROUTES = {"mailer.rea
der_tasks.send_jumo_reader_email": {"queue": "deferred", "routing_key": "deferred.reader" }, "donation.tasks.process_donation": {"queue": "billing", "routing_key": "billing.process_donation"} ...
phantomii/restalchemy
restalchemy/tests/functional/restapi/sa_based/microservice/contexts.py
Python
apache-2.0
1,388
0
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright 2016 Eugene Frolov <eugene@frolov.net.ru> # # 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 # # ...
icense for the specific language governing permissions and limitations # under the License. from restalchemy.common import context from restalchemy.tests.functional.restapi.sa_based.microservice import db class Context(context.Context):
_Session = None _session = None def get_session(self): if self._Session is None: self._Session = db.get_session() return self._Session() @property def session(self): if self._session is None: self._session = self.get_session() return self._...
damnfine/mezzanine
mezzanine/project_template/test_settings.py
Python
bsd-2-clause
1,926
0
import settings globals().update(i for i in settings.__dict__.items() if i[0].isupper()) # Require the mezzanine.accounts app. We use settings.INSTALLED_APPS here so # the syntax test doesn't complain about an undefined name. if "mezzanine.accounts" not in settings.INSTALLED_APPS: INSTALLED_APPS = list(settings.I...
"hg", or "rsync" # "SSH_USER": "", # VPS SSH username # "HOSTS": [""], # The IP address of your VPS # "DOMAINS": ALLOWED_HOSTS, # Edit domains in ALLOWED_HOSTS # "REQUIREME
NTS_PATH": "requirements.txt", # Project's pip requirements # "LOCALE": "en_US.UTF-8", # Should end with ".UTF-8" # "DB_PASS": "", # Live database password # "ADMIN_PASS": "", # Live admin user password # "SECRET_KEY": SECRET_KEY, # "NEVERCACHE_KEY": NEVERCACHE_KEY, # }
ayushgoel/FixGoogleContacts
phonenumbers/data/region_BG.py
Python
mit
3,204
0.009363
"""Auto-generated file, do not edit by hand. BG metadata""" from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata PHONE_METADATA_BG = PhoneMetadata(id='BG', country_code=359, international_prefix='00', general_desc=PhoneNumberDesc(national_number_pattern='[23567]\\d{5,7}|[489]\\d{6,8}', possible...
3}', example_number='112'), voicemail=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'), short_code=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'), standard_rate=PhoneNum
berDesc(national_number_pattern='NA', possible_number_pattern='NA'), no_international_dialling=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'), national_prefix='0', national_prefix_for_parsing='0', number_format=[NumberFormat(pattern='(2)(\\d{5})', format='\\1 \\2', leading_d...
quang-ha/lammps
tools/i-pi/ipi/inputs/forces.py
Python
gpl-2.0
6,191
0.017768
"""Deals with creating the forcefield class. Copyright (C) 2013, Joshua More and Michele Ceriotti 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)...
A ForceBeads object with the correct socket parameters. """ return ForceBeads(model=FFSocket( interface=InputInterfaceSocket.fetch(self) ),nbeads=self.nbeads.fetch(),weight=self.weight.fetch() ) def check(self):
"""Deals with optional parameters.""" InputInterfaceSocket.check(self) InputForceBeads.check(self) class InputForces(Input): """Deals with creating all the forcefield objects required in the simulation. Dynamic fields: socket: Socket object to create the server socket. """ #At ...
openstenoproject/plover
plover/system/english_stenotype.py
Python
gpl-2.0
9,221
0.016484
KEYS = ( '#', 'S-', 'T-', 'K-', 'P-', 'W-', 'H-', 'R-', 'A-', 'O-', '*', '-E', '-U', '-F', '-R', '-P', '-B', '-L', '-G', '-T', '-S', '-D', '-Z', ) IMPLICIT_HYPHEN_KEYS = ('A-', 'O-', '-E', '-U', '*') SUFFIX_KEYS = ('-Z', '-D', '-S', '-G') NUMBER_KEY = '#' NUMBERS = { 'S-': '1-', 'T-...
= criminalogist (*criminallologist) (r'^(.+)al \^ olog(y|ist|ists|ical|ically)$', r'\1olog\2'), # == +ish == # similar +ish = similarish (*similarrish) (r'^(.+)(ar|er|or) \^ ish$', r'\1\2ish'), # free + ed = freed (r'^(.+e)e \^ (e.+)$', r'\1\2'), # narrate + ing = narrating (silent e) ...
].*)$', r'\1\2'), # == misc == # defer + ed = deferred (consonant doubling) XXX monitor(stress not on last syllable) (r'^(.*(?:[bcdfghjklmnprstvwxyz]|qu)[aeiou])([bcdfgklmnprtvz]) \^ ([aeiouy].*)$', r'\1\2\2\3'), ] ORTHOGRAPHY_RULES_ALIASES = { 'able': 'ible', 'ability': 'ibility', } ORTHOGRAPH...
YunoHost/moulinette
test/test_serialize.py
Python
agpl-3.0
434
0
from datetime import datetime as dt from moulinette.interfaces import JSONExtendedEncoder def test_j
son_extended_encoder(caplog): encoder = JSONExtendedEncoder() assert encoder.default({1, 2, 3}) == [1, 2, 3] assert encoder.default(dt(1917, 3, 8)) == "1917-03-08T00:00:00+00:00" assert encoder.default(None) == "None" for message in caplog.messa
ges: assert "cannot properly encode in JSON" in message
dmaccarthy/sc8pr
sc8pr/gui/dialog.py
Python
gpl-3.0
6,552
0.006563
# Copyright 2015-2020 D.G. MacCarthy <https://dmaccarthy.github.io/sc8pr> # # This file is part of "sc8pr". # # "sc8pr" 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...
for b in btns: t = b[-1] pos = t.pos[0] + (w - b.width) / 2, t.pos[1] t.config(pos=pos) b._size = w, self[0].height # Calculate dialog dimensions w = len(btns) * (w + padding) - padding w = max(w, text.width, ti.width if ti else 0) + 2 * padd...
self._size = max(w, self._size[0]), y # Position text label and text input x = self.center[0] text.config(pos=(x, padding)) if ti: ti.config(pos=(x, text.height + 2 * padding)) # Position buttons if len(btns) > 1: x -= (btns[0].width + padding) / 2 y -=...
brendan-ward/rasterio
tests/conftest.py
Python
bsd-3-clause
6,197
0
import functools import operator import os import shutil import sys import zipfile from click.testing import CliRunner import py import pytest import numpy as np from rasterio.crs import CRS import rasterio DEFAULT_SHAPE = (10, 10) if sys.version_info > (3,): reduce = functools.reduce test_files = [os.path.j...
tains a squ
are feature 2x2 (size 4). Equivalent to results of rasterizing basic_geometry with all_touched=False. Returns ------- np ndarray """ image = np.zeros(DEFAULT_SHAPE, dtype=np.uint8) image[2:4, 2:4] = 1 return image @pytest.fixture def pixelated_image(basic_image): """ A basi...
olasitarska/django
django/template/base.py
Python
bsd-3-clause
50,676
0.001026
from __future__ import unicode_literals import re from functools import partial from importlib import import_module from inspect import getargspec, getcallargs import warnings from django.apps import apps from django.conf import settings from django.template.context import (BaseContext, Context, RequestContext, # NO...
ption): def __init__(self, msg, params=()): self.msg = msg self.params = params def __str__(self):
return self.msg % tuple(force_text(p, errors='replace') for p in self.params) class InvalidTemplateLibrary(Exception): pass class Origin(object): def __init__(self, name): self.name = name def reload(self): raise NotImplementedError('subclasses of Origin must provide a reload()...
schleichdi2/openpli-e2
lib/python/Plugins/SystemPlugins/SkinSelector/plugin.py
Python
gpl-2.0
4,272
0.026685
# -*- coding: iso-8859-1 -*- # (c) 2006 Stephan Reichholf # This Software is Free, use it where you want, when you want for whatever you want and modify it if you want but don't remove my copyright! from Screens.Screen import Screen from Screens.Standby import TryQuitMainloop from Screens.MessageBox import MessageBox f...
nfig.skin.primary_skin.value.find("/"+SKINXML) if tmp != -1
: tmp = config.skin.primary_skin.value[:tmp] idx = 0 for skin in self.skinlist: if skin == tmp: break idx += 1 if idx < len(self.skinlist): self["SkinList"].moveToIndex(idx) self.loadPreview() def up(self): self["SkinList"].up() self.loadPreview() def down(self): self["SkinList"...
roopali8/tempest
tempest/services/compute/json/images_client.py
Python
apache-2.0
5,390
0
# Copyright 2012 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...
post_body = json.dumps({'metadata': meta}) resp, body = self.put('images/%s/metadata' % image_id, post_body) body = json.loads(body) self.validate_response(schema.image_metadata, resp, body) return service_c
lient.ResponseBody(resp, body['metadata']) def update_image_metadata(self, image_id, meta): """Updates the metadata for an image.""" post_body = json.dumps({'metadata': meta}) resp, body = self.post('images/%s/metadata' % image_id, post_body) body = json.loads(body) self.val...
the0rem/traductor
traductor/translators/expose.py
Python
apache-2.0
311
0.006431
from traductor.transl
ators.base import BaseTranslator class Expose(BaseT
ranslator): """ """ def translate(self, value): """ :param value: :return: """ if type(value) is not list: return "" return "--expose=%s" % " --expose=".join(value)
kinow-io/kinow-python-sdk
test/test_add_product_to_cart_request.py
Python
apache-2.0
841
0.003567
# coding: utf-8 """ Server API Reference for Server API (REST/Json) OpenAPI spec version: 2.0.6 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import os import sys import unittest
import kinow_client from ki
now_client.rest import ApiException from kinow_client.models.add_product_to_cart_request import AddProductToCartRequest class TestAddProductToCartRequest(unittest.TestCase): """ AddProductToCartRequest unit test stubs """ def setUp(self): pass def tearDown(self): pass def testAddPro...
valeth/apex-sigma
sigma/plugins/moderation/punish/unban.py
Python
gpl-3.0
1,449
0.002082
from sigma.core.permission import check_ban import discord async def unban(cmd, message, args): channel = message.channel if args: user_q = args[0] if message.author is not user_q: if check_ban(message.author, channel): ban_list = await message.guild.bans() ...
d.Embed(type='rich', color=0xDB0000,
title='⛔ Insufficient Permissions. Ban Permission Required.') await message.channel.send(None, embed=out_content) else: await message.channel.send(cmd.help())
agolo/mongo-connector
tests/test_mongo.py
Python
apache-2.0
8,734
0.001145
# Copyright 2013-2014 MongoDB, 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 writin...
"""Test update operations.""" # Insert self.conn.test.test.insert_one({"a": 0}) assert_soon(lambda: sum(1 for _ in self._search()) == 1) def check_update(update_spec): updated = self.conn.test.command( SON([('findAndModify', 'test'), ...
# Allow some time for update to propagate time.sleep(2) replicated = self.mongo_doc.mongo.test.test.find_one({"a": 0}) self.assertEqual(replicated, updated) # Update by adding a field check_update({"$set": {"b": [{"c": 10}, {"d": 11}]}}) # Update by setting ...
mikrosimage/OpenRenderManagement
scripts/archive_migration.py
Python
bsd-3-clause
13,337
0.037415
#!/usr/bin/env python2.7 #! -*- encoding: utf-8 -*- import simplejson as json import threading from sqlobject import SQLObject, connectionForURI from sqlobject.sqlbuilder import Insert, Select, Delete from octopus.dispatcher.model.node import FolderNode, TaskNode from octopus.dispatcher.model.task import Task, Tas...
kNodesDependencies(node.id) archiveTaskNodesRules(node.id) def archiveCommands(): Commands._connection = mainConn print "Starting to archive Commands" commandsToArchive = Commands.select(Commands.q.archived==True) processedItems = 0 totalItems = commandsToArchive.count() print "Found " + str(totalItems) + " Com...
commandsToArchive.limit(BUFFER_SIZE): duplicateCommandIntoStatDB(commands) deleteElementFromMainDB(Commands, commands.id) processedItems+=1 print str(totalItems - processedItems) + " Commands remaining" print "Finished to archive Commands" def archiveTaskGroups(): TaskGroups._connection = mainConn print...
Conorh97/CA117---Python3
week_11/file_111.py
Python
lgpl-3.0
1,448
0.013122
class File(object): FILE_PERMISSIONS = "rwx" def __init__(self , name , owner , size = 0 , permissions = ""): self.name = name self.owner = owner self.size = size self.permissions = permissions def enable_permission(self , user , mode): if mode not in self.FILE_PER...
rn self.permissions += mode def disable_permission(self , user , mode): if mode not in self.FILE_PERMISSIONS: return if self.owner != user: print("Access denied") return if mode not in self.permissions: return self.permissi...
f , user , mode): if mode not in self.FILE_PERMISSIONS: return if self.owner != user and mode not in self.permissions: return("Access denied") return("Access granted") def get_permissions(self): k = sorted(self.permissions) return "".join(k) de...
levilucio/SyVOLT
GM2AUTOSAR_MM/Properties/positive/models/M6ThenClausePart2Complete_MDL.py
Python
mit
17,941
0.007636
""" __M6ThenClausePart2Complete_MDL.py_____________________________________________________ Automatically generated AToM3 Model File (Do not modify directly) Author: gehan Modified: Thu Oct 24 14:51:32 2013 _______________________________________________________________________________________ """ from stickylink impo...
lue of the curren
t node\'s attribute value by: attr_value.\n# You can access any attribute x of this node by: this[\'x\'].\n# If the constraint relies on attribute values from other nodes,\n# use the LHS/NAC constraint instead.\n# The given constraint must evaluate to a boolean expression.\n#============================================...
Distrotech/notify-python
tests/test-replace-widget.py
Python
lgpl-2.1
1,189
0.004205
#!/usr/bin/env python import pygtk pygtk.require('2.0') import gtk import pynotify import sys exposed_signal_id = 0 count = 0 def exposed_cb(button, event, n): global exposed_signal_id button.disconnect(exposed_signal_id) if not n.show(): print "Failed to send notification" gtk.main_quit(...
n.update("Widget Attachment Test", "You clicked the button %s times" % count) if not n.show(): print "Failed to send notificatio
n" gtk.main_quit() if __name__ == '__main__': if not pynotify.init("Replace Test"): sys.exit(1) win = gtk.Window(gtk.WINDOW_TOPLEVEL) win.show() win.connect('delete_event', gtk.main_quit) button = gtk.Button("Click here to change notification") button.show() win.add(butto...
gajim/python-nbxmpp
nbxmpp/modules/base.py
Python
gpl-3.0
1,469
0
# Copyright (C) 2018 Philipp Hörist <philipp AT hoerist.com> # # This file is part of nbxmpp. # # 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 opt...
T ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Publ
ic License # along with this program; If not, see <http://www.gnu.org/licenses/>. from __future__ import annotations from typing import TYPE_CHECKING from typing import Any import logging from nbxmpp.util import LogAdapter if TYPE_CHECKING: from nbxmpp.client import Client class BaseModule: _depends: di...
miurahr/seahub
seahub/api2/endpoints/admin/libraries.py
Python
apache-2.0
20,715
0.001545
# Copyright (c) 2012-2016 Seafile Ltd. import logging from rest_framework.authentication import SessionAuthentication from rest_framework.permissions import IsAdminUser from rest_framework.response import Response from rest_framework.views import APIView from rest_framework import status from django.template.defaultfi...
s_all = seafile_api.get_repo_list(start, limit, order_by) else: repos_all = seafile_api.get_repo_list(start, limit) if len(repos_all) > per_page: repos_all = repos_all[:per_page] has_next
_page = True else: has_next_page = False default_repo_id = get_system_default_repo_id() repos_all = [r for r in repos_all if not r.is_virtual] repos_all = [r for r in repos_all if r.repo_id != default_repo_id] return_results = [] for repo in repos_all: ...
guorendong/iridium-browser-ubuntu
tools/perf/benchmarks/skpicture_printer.py
Python
bsd-3-clause
1,750
0.009714
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from telemetry import benchmark from telemetry.core import discover from telemetry.page import page_set from measurements import skpicture_printer def _Ma...
e-dir', action='store', type='string') parser.add_op
tion('-s', '--skp-outdir', help='Output directory for the SKP files') @classmethod def ProcessCommandLineArgs(cls, parser, args): if not args.page_set_name: parser.error('Please specify --page-set-name') if not args.page_set_base_dir: parser.error('Please specify --page-set...
tristanfisher/yams
multidb/env.py
Python
gpl-3.0
2,875
0.002087
from __future__ import with_statement import os import sys from alembic import context from sqlalchemy import engine_from_config, pool from logging.config import fileConfig # We need to go back a dir to get the config. _this_dir = os.path.dirname((os.path.abspath(__file__))) _parent_dir = os.path.join(_this_dir, '../'...
n(config.config_ini_section) if hasattr(API, 'SQLALCHEMY_DATABASE_URI'): conf['sqlalchemy.url'] = API.SQLALCHEMY_DATABASE_URI return conf def run_migrations_offline(): """Run migrations in 'offline' mode. This configures the context with just a URL and not an Engine, though an Engine is ...
output. """ context.configure( url=merged_ini_py_conf().get('sqlalchemy.url'), target_metadata=target_metadata, literal_binds=True ) with context.begin_transaction(): context.run_migrations() def run_migrations_online(): """Run migrations in 'online' mode. I...
razzius/PyClassLessons
instructors/lessons/numbers/examples/ex1_floatvdec.py
Python
mit
381
0.002625
# Our real numbers will defa
ult to float. x = 1.1 y = 2.2 print("x, %s, %.17f") % (type(x), x) print("y, %s, %.17f") % (type(y), y) #Ok, everything looks
good... now add them together to get 3.3 z = x + y print("z, %s: %.15f at 15 decimals") % (type(z), z) print("z, %s: %.17f at 17 decimals") % (type(z), z) print("z, %s: %.33f at 33 decimals") % (type(z), z) print("Oh no!")
caedesvvv/pynoded
pynoded/evh/graph.py
Python
gpl-3.0
2,168
0.021218
""" Simple base event handlers. """ from base import * class GraphEvH(EvHandler): """ Example graph event handler. It can zoom with mouse and keyboard, create new nodes... """ def __init__(self,maingraph): self.maingraph=maingraph def scroll_up(self): x,y=self.maingraph.RawPoi...
ove(self) return True def mouserelease_right(self): self.maingraph.evstack.remove(self) return True
irtnog/SATOSA
tests/util.py
Python
apache-2.0
16,995
0.001294
""" Contains help methods and classes to perform tests. """ import base64 import tempfile from datetime import datetime from urllib.parse import parse_qsl, urlparse from Cryptodome.PublicKey import RSA from bs4 import BeautifulSoup from saml2 import server, BINDING_HTTP_POST, BINDING_HTTP_REDIRECT from saml2.authn_con...
nameid_format=nameid_format) ht_args = self.apply_binding(_bin
ding, '%s' % req, destination, relay_state=relay_state) if _binding == BINDING_HTTP_POST: form_post_html = "\n".join(ht_args["data"]) doctree = BeautifulSoup(form_post_html, "html.parser") saml_request = doctree.find("input", {"name": "SA...