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
mkasa/taw
taw/sshlike.py
Python
mit
5,073
0.006308
#!/usr/bin/env python3 from __future__ import print_function from __future__ import absolute_import import os, click import subprocess from taw.util import * from taw.taw import * # commands/subcommands # ============== # SSH COMMAND # ============== @taw.command("ssh") @click.argument('hostname', metavar='<host n...
convert_host_name_to_instance(des
t_host) if instance.public_ip_address is None: error_exit("The instance has no public IP address") dest_host = instance.public_ip_address if dest_user == '_': dest_user = os.environ['USER'] if dest_user is None: dest_user = get_root_like_user_from_instance(instance) if key_file_p...
bailey-ann/diamanda-fork
diamandas/myghtyboard/views.py
Python
bsd-3-clause
6,485
0.039938
#!/usr/bin/python # Diamanda Application Set # myghtyboard forum from django.shortcuts import render_to_response from django.http import HttpResponseRedirect from django.template import RequestContext from django.utils.translation import ugettext as _ from django.views.generic.list_detail import object_list from django...
ry_list(request): """ show all categories and their topics """ categories = Category.objects.all().order_by('order') for c in categories: #{% if forum.mods %}<u>{% trans "Moderators" %}</u>: # {% for i in forum.mods %} # {{ i.username }}{% if not forloop.last %},{% endif %} # {...
d(f) c.forums = c.forum_set.all().order_by('order') return render_to_response( 'myghtyboard/category_list.html', {'categories': categories}, context_instance=RequestContext(request, forumContext(request))) def topic_list(request, forum_id, pagination_id=1): """ list of topics in a forum * forum_id - id ...
drincruz/luigi
test/task_test.py
Python
apache-2.0
4,097
0.000976
# -*- coding: utf-8 -*- # # Copyright 2012-2015 Spotify AB # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law...
list_param=['in', 'flames'], insignificant_param='test') original = DummyTask(**params) other = DummyTask.from_str_params(original.to_str_params()) self.assertE
qual(original, other) def test_task_from_str_insignificant(self): params = {'necessary_param': 'needed'} original = DefaultInsignificantParamTask(**params) other = DefaultInsignificantParamTask.from_str_params(params) self.assertEqual(original, other) def test_task_missing_nece...
mozillazg/bookmarks
bookmarks/extensions.py
Python
mit
363
0
# -*- coding: utf-8 -*- from flask_bcrypt import Bcrypt from flask_admin import Admin from flask_cache import Cache from flask_login import LoginManager from flask_migrate import Migrate from flask_sqlalchemy import SQLAlchemy admin = Admin(name='Bookmarks') bcrypt = Bcrypt() cache = Cache() db = SQLAlchemy() migrat
e = Migrate() login_manager = LoginManager()
jabesq/home-assistant
homeassistant/components/emulated_roku/__init__.py
Python
apache-2.0
2,359
0
"""Support for Roku API emulation.""" import voluptuous as vol from homeassistant import config_entries, util from homeassistant.const import CONF_NAME import homeassistant.helpers.config_validation as cv from .binding import EmulatedRoku from .config_flow import configured_servers from .const import ( CONF_ADVER...
BIND_MULTICAST) server = EmulatedRoku(hass, name, host_ip, listen_port, advertise_ip, advertise_port, upnp_bind_multicast) hass.data[DOMAIN][name] = server
return await server.setup() async def async_unload_entry(hass, entry): """Unload a config entry.""" name = entry.data[CONF_NAME] server = hass.data[DOMAIN].pop(name) return await server.unload()
isudox/leetcode-solution
python-algorithm/leetcode/problem_538.py
Python
mit
1,776
0
"""538. Convert BST to Greater Tree https://leetcode.com/problems/convert-bst-to-greater-tree/ Given a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus sum of all keys greater than the original key in BST. Example: Input: The root of a...
p = node.right for i in range(len(seq_val) - 1): seq_node[i].val = sum(seq_val[i:]) return root def convert_bst_1(self, root: TreeNode) -> TreeNode: p = root stack, node_seq = [], [] # reversed in-order traversal. while p or sta
ck: if p: stack.append(p) p = p.right else: node = stack.pop() node_seq.append(node) p = node.left pre_sum = 0 for node in node_seq: pre_sum += node.val node.val = pre_sum ...
msegado/edx-platform
common/djangoapps/student/tests/test_recent_enrollments.py
Python
agpl-3.0
8,149
0.003436
""" Tests for the recently enrolled messaging within the Dashboard. """ import datetime import unittest import ddt from django.conf import settings from django.urls import reverse from django.utils.timezone import now from opaque_keys.edx import locator from pytz import UTC from six.moves import range, zip from com...
courses = [] for idx, seconds_past in zip(list(range(2, 6)), [5, 10, 15, 20]): course_location = locator.CourseLocator( 'Org{num}'.format(num=idx), 'Course{num}'.format(num=idx),
'Run{num}'.format(num=idx) ) course, enrollment = self._create_course_and_enrollment(course_location) enrollment.created = now() - datetime.timedelta(seconds=seconds_past) enrollment.save() courses.append(course) courses_list = list(get...
andymckay/addons-server
src/olympia/translations/query.py
Python
bsd-3-clause
5,271
0
import itertools from django.conf import settings from django.db import models from django.utils import translation as translation_utils from olympia.addons.query import IndexCompiler, IndexQuery def order_by_translation(qs, fieldname): """ Order the QuerySet by the translated field, honoring the current a...
n a string or a Field. """ if fieldname.startswith('-'): desc = True fieldname = fieldname[1:] else: desc = False qs = qs.all()
model = qs.model field = model._meta.get_field(fieldname) # connection is a tuple (lhs, table, join_cols) connection = (model._meta.db_table, field.rel.to._meta.db_table, field.rel.field_name) # Doing the manual joins is flying under Django's radar, so we need to make # sure...
honahursey/pyFDA
work/min_order_common.py
Python
apache-2.0
1,902
0.028917
# -*- coding: utf-8 -*- """ Common design parameters for minimum order design methods @author: Christian Muenker """ from __future__ import print_function, division, unicode_literals #from importlib import import_module #import filterbroker as fb class min_order_common(object): def __init__(self): ...
nimum filter order # ENABLED widgets for all man. / min. filter order response types: enb_min = ['fo','fspecs','aspecs'] # minimum filter order # common parameters for all man. / min. filter order response types: par_min = ['f_S', 'A_PB', 'A_SB'] # enabled widget for min. filt...
esponse types: # This data is merged with the entries for individual response types # (common data comes first): self.com = {"min":{"enb":enb_min, "msg":msg_min, "par": par_min}} self.rt = { "LP": {"min":{"par":['f_S','A_PB','A_SB','F_PB','F_SB']}}, "HP": {"min":...
Wiredcraft/maestro-ng
maestro/__main__.py
Python
lgpl-3.0
7,128
0.000281
#!/usr/bin/env python # Copyright (C) 2013-2014 SignalFuse, Inc. # # Docker container orchestration utility. from __future__ import print_function import argparse import jinja2 import logging import os import sys import traceback import yaml from . import exceptions, maestro from . import name, version DEFAULT_MAE...
return parser def main(args=None, config=None): options = create_parser().parse_args(args) # Only helps with Python3 if not options.command: options.command = 'status' if config is None: config = load_config_from_file(options.file) # Shutup urllib3, wherever it comes from. ...
b3.connectionpool') .setLevel(logging.WARN)) (logging.getLogger('urllib3.connectionpool') .setLevel(logging.WARN)) try: c = maestro.Conductor(config) if options.command != 'complete' and not options.things: options.things = c.services.keys() optio...
Remolten/galena
tests/conftest.py
Python
bsd-3-clause
290
0
import pytest import gal
ena @pytest.fixture def game(): return galena.Game() @pytest.fixture def entity(game): return game.c
reate_entity() @pytest.fixture def entity2(game): return game.create_entity() @pytest.fixture def entity3(game): return game.create_entity()
glaserti/LibraryTwitter
Python/4 - BaseStats.py
Python
mit
16,267
0.011437
# # Basic Statistics on the Twitter Accounts # # In this section, some basic statistics for the Twitter Accounts of the given groups of libraries (i.e. National libraries, University libraries, Public libraries) will be collected. # # The functions will return a list of dictionaries and save it as a CSV to the cwd. ...
", "Twitter" output = list of dictionaries ''' f = open(input_file, 'r
') d = csv.DictReader(f) LoD = [] # list of dictionaries for row in d: LoD.append(row) f.close() return LoD def exp2CSV(listOfDict, filename): ''' arguments = list of dictionaries, filename output = saves file to cwd (current working directory) ''' #creating the filena...
we-inc/mms-snow-white-and-the-seven-pandas
webserver/config/settings.py
Python
mit
4,453
0.001347
""" Django settings for webserver project. Generated by 'django-admin startproject' using Django 1.11.5. For more information on this file, see https://docs.djangoproject.com/en/1.11/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.11/ref/settings/ """ import ...
RS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.co...
nfig.wsgi.application' # Database # https://docs.djangoproject.com/en/1.11/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'HOST': 'db', 'PORT': 5432, } } # REST framework REST_FRAME...
sserkez/ocelot
utils/sim_plot.py
Python
gpl-3.0
4,107
0.015827
import sys from ocelot.adaptors.genesis import * from ocelot.cpbd.elements import Element, Quadrupole, RBend, Drift, Undulator from ocelot import MagneticLattice from ocelot.cpbd.beam import Beam from ocelot.cpbd.optics import * import numpy.fft as fft from sim_info import SimInfo, RunInfo #params = {'backend': 'ps...
= P / len(runs) p1, = ax1.plot(t, P, color='black',alpha=0.4) if spec_av == None: spec_av = y / len(runs) else: spec_av += y / len(runs) p2, = ax2.plot(x, y, color='black', alpha = 0.4) ax2.set_xlim(x[0],x[-1]) ax3.set_xlim(x[0],x[-1]) x_ticks = ax2.get_xticks()[1:] ...
) * 1.e9 # coordinates in nm ax3.set_xticks(x_ticks) ax3.set_xticklabels(["%.4f" % z for z in x2]) ax1.plot(t, power_av, 'b') ax2.plot(x, spec_av, 'b') plt.show()
dpdani/csu
src/core/user.py
Python
gpl-3.0
7,518
0.029662
# -*- coding: utf-8 -*- """ This module implements users. """ import os from persistent import Persistent import src.core.db as db import src.core.exc as exc import src.core.utils as utils import src.core.security as security import random import time class User(object): def __init__(self): self.__set_to_none()...
se. Regardless of database closing, if set_to_none is True, internal variables will be erased. """ closed = False if db.user_db is not None: if self.verify_password(password): db.user_db.close(save_plugins=save_plugins, encrypt=True, key=password) closed = True else: raise exc.USR_ClosingUnv...
db and deletes its database files. User has to be logged in first. User database will be closed in the process. This function does not explicitly handle user closing (__set_to_none). """ if self.app_db is None: self.connect_to_appdb() if self.id is None: raise exc.USR_DeletingUninitilizedUser() if n...
icomms/wqmanager
apps/aquatest_reports/urls.py
Python
bsd-3-clause
416
0.007212
from django.conf.urls.defaults import * ## reports view urlpatterns = patterns('aquatest_reports.views', (r'^reports$', 'reports'), (r'^sampling_points$', 'sampling_points'), (r'^report_testers$', 'testers'), (r'^date_range$', 'date_range'), (r'^create_report$', 'create_report'), (r'^export_csv...
(r'^export_pdf$', 'pdf_view'), (r'^parameters$', 'paramete
rs'), )
melinath/django-kiki
kiki/models.py
Python
bsd-2-clause
8,088
0.039194
import base64 import cPickle as pickle import datetime from email import message_from_string from email.utils import getaddresses from django import forms from django.contrib.auth.models import User, Group from django.contrib.contenttypes.models import ContentType from django.contrib.sites.models import Site from dja...
True, through = ListUserMetadata ) messages = models.ManyToManyField( 'Message', related_name = 'mailinglists', blank = True, null = True, through = 'ListMessage' ) @property def address(self): return "%s@%s" % (self.local_part, self.domain.domain)
def _list_id_header(self): # Does this need to be a byte string? return smart_str(u"%s <%s.%s>" % (self.name, self.local_part, self.domain.domain)) def __unicode__(self): return self.name def clean(self): validate_email(self.address) # As per RFC 2919, the list_id_header has a max length of 255 oc...
chippey/gaffer
python/GafferAppleseedUI/AppleseedShaderBallUI.py
Python
bsd-3-clause
2,787
0.013994
########################################################################## # # Copyright (c) 2016, Image Engine Design Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistrib...
rendering shader balls with Appleseed. """, plugs = { "environment" : [ "description", """ An environment map used for lighting. Should be in latlong format. """, "plugValueWidget:type", "GafferUI.FileSystemPathPlugValueWidget", "pathPlugValueWidget:leaf", True, "pathPlugValueWidget:vali...
. A value of 0 disables the limit. """ ], "threads" : [ "description", """ The number of threads used by appleseed to render the shader ball. A value of 0 uses all cores, and negative values reserve cores for other uses - to be used by the rest of the UI for instance. """ ], } )
malkavi/lutris
lutris/runners/mupen64plus.py
Python
gpl-3.0
1,602
0
# -*- coding: utf-8 -*- import os from lutris import settings from lutris.runners.ru
nner
import Runner class mupen64plus(Runner): """Nintendo 64 emulator""" human_name = "Mupen64Plus" platform = "Nintendo 64" game_options = [{ 'option': 'main_file', 'type': 'file', 'label': 'ROM file', 'help': ("The game data, commonly called a ROM image.") }] runne...
fake-name/ReadableWebProxy
runScheduler.py
Python
bsd-3-clause
5,913
0.033824
#!flask/bin/python import sys import os.path import logging os.environ['NDSCHEDULER_SETTINGS_MODULE'] = 'settings_sched' addpath = os.path.abspath("./ndscheduler") if addpath not in sys.path: sys.path.append(os.path.abspath("./ndscheduler")) import traceback import datetime import threading import time import apsch...
minute = params.get('minute', None), ) self.scheduler_manager.add_trigger_job( job_class_string = job_name, name = params['name'],
trigger = trig, ) self.scheduler_manager.sched.add_listener(job_evt_listener, apscheduler.events.EVENT_JOB_EXECUTED | apscheduler.events.EVENT_JOB_ERROR | apscheduler.events.EVENT_JOB_MISSED | apscheduler.events.EVENT_JOB_MAX_INSTANCES ) def run_scheduler(): # common.stuck...
chennan47/osf.io
addons/wiki/views.py
Python
apache-2.0
19,789
0.001213
# -*- coding: utf-8 -*- import httplib as http import logging from flask import request from framework.exceptions import HTTPError from framework.auth.utils import privacy_info_handle from framework.auth.decorators import must_be_logged_in from framework.flask import redirect from addons.wiki.utils import to_mongo_...
{ 'version': version.version, 'user_fullname': privacy_info_handle(version.user.fullname, anonymous, name=True), 'date': '{} UTC'.format(v
ersion.date.replace(microsecond=0).isoformat().replace('T', ' ')), } for version in reversed(versions) ] def _get_wiki_pages_current(node): return [ { 'name': sorted_page.page_name, 'url': node.web_url_for('project_wiki_view', wname=sorted_page.page_name, _guid=...
afraser/CellProfiler-Analyst
cpa/sortbin.py
Python
gpl-2.0
12,471
0.006976
from dbconnect import DBConnect import tilecollection from imagetile import ImageTile from imagetilesizer import ImageTileSizer from imagecontrolpanel import ImageControlPanel from properties import Properties import imagetools import cPickle import wx p = Properties.getInstance() db = DBConnect.getInstance() # The...
self.cp = wx.CollapsiblePane(self, label='Show controls', style=wx.CP_DEFAULT_STYLE|wx.CP_NO_TLW_RESIZE) self.icp = ImageC
ontrolPanel(self.cp.GetPane(), self) self.Sizer = wx.BoxSizer(wx.VERTICAL) self.Sizer.Add(self.sb, 1, wx.EXPAND) self.Sizer.Add(self.cp, 0, wx.EXPAND) self.cp.Bind(wx.EVT_COLLAPSIBLEPANE_CHANGED, self._on_control_pane_change) def _on_control_pane_change(sel...
amraboelela/swift
utils/gyb_syntax_support/NodeSerializationCodes.py
Python
apache-2.0
7,221
0
from Node import error SYNTAX_NODE_SERIALIZATION_CODES = { # 0 is 'Token'. Needs to be defined manually # 1 is 'Unknown'. Needs to be defined manually 'UnknownDecl': 2, 'TypealiasDecl': 3, 'AssociatedtypeDecl': 4, 'IfConfigDecl': 5, 'PoundErrorDecl': 6, 'PoundWarningDecl': 7, 'Poun...
': 165, '
ArrayElementList': 166, 'DictionaryElementList': 167, 'StringInterpolationSegments': 168, 'DeclNameArgumentList': 169, 'ExprList': 170, 'ClosureCaptureItemList': 171, 'ClosureParamList': 172, 'ObjcName': 173, 'FunctionParameterList': 174, 'IfConfigClauseList': 175, 'InheritedType...
pokidovea/immobilus
tests/test_async.py
Python
apache-2.0
780
0
import asyncio from immobilus import immobilus
from datetime import datetime import pytest @pytest.mark.asyncio @immobilus('2000-02-01 13:23') async def test_decorated_async_function(): assert datetime.utcnow() == datetime(2000, 2, 1, 13, 23) @pytest.mark.asyncio async def test_async_function_under_context(): dt = datetime(2016, 1, 1, 13, 54) ass...
assert datetime.utcnow() != dt @immobilus('2017-10-20') async def some_coroutine(): return datetime.now() def test_coroutine(): loop = asyncio.new_event_loop() result = loop.run_until_complete(some_coroutine()) assert result.strftime('%Y-%m-%d %H:%M:%S') == '2017-10-20 00:00:00'
thepiper/standoff
vpy/lib/python2.7/site-packages/werkzeug/debug/tbtools.py
Python
gpl-3.0
16,913
0.000473
# -*- coding: utf-8 -*- """ werkzeug.debug.tbtools ~~~~~~~~~~~~~~~~~~~~~~ This module provides various traceback related utility functions. :copyright: (c) 2014 by the Werkzeug Team, see AUTHORS for more details. :license: BSD. """ import re import os import sys import json import inspect import ...
'''\ <h1>Interactive Console</h1> <div class="explanat
ion"> In this console you can execute Python expressions in the context of the application. The initial namespace was created by the debugger automatically. </div> <div class="console"><div class="inner">The Console requires JavaScript.</div></div> ''' + FOOTER SUMMARY_HTML = u'''\ <div class="%(classes)s"> %(title...
ebroder/anygit
anygit/config/middleware.py
Python
mit
2,432
0.000411
"""Pylons middleware initialization""" from beaker.middleware import CacheMiddleware, SessionMiddleware from paste.cascade import Cascade from paste.registry import RegistryManager from paste.urlparser import StaticURLParser from paste.deploy.converters import asbool from pylons import config from pylons.middleware imp...
import RoutesMiddleware from anygit.config.environment import load_environment def make_app(global_conf, full_stack=True, static_files=True, **app_conf): """Create a Pylons WSGI application and return it ``g
lobal_conf`` The inherited configuration for this application. Normally from the [DEFAULT] section of the Paste ini file. ``full_stack`` Whether this application provides a full WSGI stack (by default, meaning it handles its own exceptions and errors). Disable full_stack whe...
sergeneren/anima
anima/ui/scripts/maya.py
Python
bsd-2-clause
1,800
0.000556
# -*- coding: utf-8 -*- # Copyright (c) 2012-2015, Anima Istanbul # # This module is part of anima-tools and is released under the BSD 2 # License: http://www.opensource.org/licenses/BSD-2-Clause import logging from anima import logger from anima.env.mayaEnv import Maya from anima.utils import do_db_setup def set_qt_...
updater UI for Maya """ # connect to db do_db_setup() # set Qt lib set_qt_l
ib() from anima.ui import version_updater, models from anima.env import mayaEnv reload(mayaEnv) reload(version_updater) reload(models) m = Maya() import pymel m.name = "Maya" + str(pymel.versions.current())[0:4] logger.setLevel(logging_level) # generate a reference_resolution ...
mlperf/training_results_v0.7
Google/benchmarks/bert/implementations/bert-cloud-TF2.0-tpu-v3-32/tf2_common/modeling/model_training_utils.py
Python
apache-2.0
24,871
0.006594
# Copyright 2019 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...
'wb') as f: logging.info('Training Summary: \n%s', str(training_summary)) f.write(json.dumps(training_summary, indent=4)) def run_customized_training_loop( # pylint: disable=invalid-name _sentinel=None, # pylint: enable=invalid-name strategy=None, model_fn=None, loss_fn=None, mode...
steps_per_loop=1, epochs=1, eval_input_fn=None, eval_steps=None, steps_between_eval=None, steps_before_eval_start=None, stop_threshold=None, metric_fn=None, init_checkpoint=None, custom_callbacks=None, run_eagerly=False, sub_model_export_name=None, explicit_allreduce...
manojpandey/simple-blog
blog/views.py
Python
mit
1,490
0.004027
from django.shortcuts import render from django.utils import timezone from .models import Post from django.shortcuts import render, get_object_or_404 from .forms import PostForm from django.shortcuts import redirect def post_list(request): posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('-...
alid(): post = form.save(commit=False) post.author = request.user post.published_date = timezone.now() post.save() return redirect('post_detail', pk=post.pk)
else: form = PostForm() return render(request, 'blog/post_edit.html', {'form': form}) def post_edit(request, pk): post = get_object_or_404(Post, pk=pk) if request.method == "POST": form = PostForm(request.POST, instance=post) if form.is_valid(): post = form.save(commit=F...
prometheanfire/cloud-init
cloudinit/sources/DataSourceAzure.py
Python
gpl-3.0
21,832
0
# vi: ts=4 expandtab # # Copyright (C) 2013 Canonical Ltd. # # Author: Scott Moser <scott.moser@canonical.com> # # 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. # # ...
perform_hostname_bounce(hostname=temp_hostname, cfg=cfg, prev_hostname=previous_hostname) except Exception as e: LOG.warn("Failed publishing
hostname: %s", e) util.logexc(LOG, "handling set_hostname failed") try: invoke_agent(self.ds_cfg['agent_command']) except util.ProcessExecutionError: # claim the datasource even if the command failed util.logexc(LOG, "agent com...
byung-u/ProjectEuler
Problem_200_299/euler_211_artVark.py
Python
mit
16,299
0.003927
#!/usr/bin/env python2 # -*- coding: utf-8 -*- ################################################################################ # # Project Euler -- Problem 211 # ################################################################################ # # Divisor sum squares # #################################################...
ies by combining them iteratively, creating new entries (that are not prime), and removing previously combined entries. When done, self.solutions should contain empty entries only for numbers that solve this problem. """ templist = [] wh
ile len(self.hist) > 0: minval = self.limit for j in self.hist: if self.hist[j] == minval: lvec = self.getSame(j,self.hist[j]) ok = True for k in lvec: if k in templist: ...
duyet-website/api.duyet.net
lib/limits/strategies.py
Python
mit
5,640
0.001418
""" rate limiting strategies """ from abc import ABCMeta, abstractmethod import weakref import six import time @six.add_metaclass(ABCMeta) class RateLimiter(object): def __init__(self, storage): self.storage = weakref.ref(storage) @abstractmethod def hit(self, item, *identifiers): """ ...
riable list of strings to uniquely identify the limit :return: True/False
""" return self.storage().get_moving_window( item.key_for(*identifiers), item.amount, item.get_expiry(), )[1] < item.amount def get_window_stats(self, item, *identifiers): """ returns the number of requests remaining within this limit. :param i...
ewandor/home-assistant
homeassistant/components/sensor/tellduslive.py
Python
apache-2.0
3,707
0
""" Support for Tellstick Net/Telstick Live. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/sensor.tellduslive/ """ import logging from homeassistant.components.tellduslive import TelldusLiveEntity from homeassistant.const import TEMP_CELSIUS _LOGGER =...
def _value_as_humidity(self): """Return the value as humidity.""" return int(round(float(self._value))) @property def name(self): """Return the name of the sensor.""" return '{} {}'.format( super().name, self.quantity_name or '') @property de...
.available: return None elif self._type == SENSOR_TYPE_TEMPERATURE: return self._value_as_temperature elif self._type == SENSOR_TYPE_HUMIDITY: return self._value_as_humidity elif self._type == SENSOR_TYPE_LUMINANCE: return self._value_as_luminance ...
Orav/kbengine
kbe/src/lib/python/Tools/scripts/suff.py
Python
lgpl-3.0
536
0
#! /usr/bin/env python3 # suff # # show different suffixes amongst arguments import sys def main(): files = sys.argv[1:] suffixes = {} for filename in files: suff = getsuffix(filename) suffixes.setdefault(suff, []).append(filename) for suff, filenames in sorted(suffixe...
lenames)) def getsuffix(filename): name, sep, suff = filename.rpartition('.') return sep + suff if sep else ''
if __name__ == '__main__': main()
csparpa/check
fluentcheck/assertions_is/geo.py
Python
mit
520
0
from fluentcheck.assertions_is.base_is import IsBase class __IsGeo(IsBase): @property def latitude(self) -> "Is": self.check.is_latitude() return self @property def longitude(self)
-> "Is": self.check.i
s_longitude() return self @property def azimuth(self) -> "Is": self.check.is_azimuth() return self # noinspection SpellCheckingInspection @property def geopoint(self) -> "Is": self.check.is_geopoint() return self
anhstudios/swganh
data/scripts/templates/object/tangible/wearables/armor/mandalorian/shared_armor_mandalorian_belt.py
Python
mit
490
0.044898
#### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kern
el): result = Tangible() result.template = "object/tangible/wearables/armor/mandalorian/shared_armor_mandalorian_belt.iff" result.attribute_template_id = 0 result.stfName("wearables_name","armor_mandalorian_belt") #### BEGIN MODIFICATIONS #### ####
END MODIFICATIONS #### return result
arunkgupta/gramps
gramps/gui/views/treemodels/citationbasemodel.py
Python
gpl-2.0
6,368
0.006281
# # Gramps - a GTK+/GNOME based genealogy program # # Copyright (C) 2000-2006 Donald N. Allingham # Copyright (C) 2011 Tim G L Lyons, Nick Hall # # 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 Found...
LUMN_DATE = 2 COLUMN_PAGE = 3 COLUMN_CONFIDENCE = 4 COLUMN_SOURCE = 5 COLUMN_CHANGE = 9 # Data for the Source object COLUMN2_HANDLE = 0 COLUMN2_ID = 1 COLUMN2_TITLE = 2 COLUMN2_AUTHOR = 3 COLUMN2_PUBINFO = 4 COLUMN2_ABBREV = 7 COLUMN2_CHANGE = 8 INVALID_DATE_FO...
---------------------------------------------------------------- class CitationBaseModel(object): # Fields access when 'data' is a Citation def citation_date(self, data): if data[COLUMN_DATE]: citation = Citation() citation.unserialize(data) date_str = get_date(citatio...
DaniAkash/hackerrank-solutions
Algorithms/Strings/Alternating Characters/Alternating Characters.py
Python
apache-2.0
822
0.015815
''' Copyright 2017-Present Dani Akash 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 implied. See the License for the specific language governing permissions and limitations under the License. ''' def solution(): s=list(input().strip()) i,count=1,0 while i<len(s): if s[i]==s[i-1]: count+=1 i+=1 return ...
hebaishi/TC2014hackathon
flaskapp/app/routes.py
Python
gpl-2.0
1,217
0.027116
# -*- coding: utf-8 -*- import random from flask import Flask, render_template,request, flash from forms import Params from crawler_amazon import amazoncrawl from crawler_asos import asoscrawl app = Flask(__name__) app.secret_key = 'development key' @app.route('/',methods = ['GET', 'POST']) def params(): form...
return render_template('params.html', form=form) else: par = dict()
par['height'] = form.height.data par['weight'] = form.weight.data par['gender'] = form.gender.data par['keywords'] = form.keywords.data outlist = amazoncrawl(par) outlist = outlist + asoscrawl(par) random.shuffle(outlist) return render_template('output.html', outlist=outlist...
totalvoice/totalvoice-python
totalvoice/cliente/api/totalvoice.py
Python
mit
1,052
0.013308
from __future__ import absolute_import import requests from .helper import utils class Totalvoice(object): def __init__(self, cliente): self.cliente
= cliente def enviar(self, *args): raise NotImplemented
Error def get_by_id(self, id): raise NotImplementedError def editar(self, *args): raise NotImplementedError def get_relatorio(self, *args): raise NotImplementedError def deletar(self, id): raise NotImplementedError def get_request(self, host, ...
scopely-devops/skew
skew/resources/aws/lambda.py
Python
apache-2.0
1,965
0
# Copyright (c) 2014 Scopely, Inc. # Copyright (c) 2015 Mitch Garnaat # # Licensed under the Apache License, Version 2.0 (the "License"). You # may not use this file except in compliance with the License. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompanyin...
ging.getLogger(__name__) class Function(AWSResource): @classmethod def enumerate(cls, arn, region, account, resource_id=None, **kwargs): resources = super(Function, cls).enumerate(arn, region, account,
resource_id, **kwargs) for r in resources: r.data['EventSources'] = [] kwargs = {'FunctionName': r.data['FunctionName']} response = r._client.call('list_event_source_mappings', **kwargs) for esm in response['EventSourceMappings']: r.data['E...
drpngx/tensorflow
tensorflow/contrib/periodic_resample/__init__.py
Python
apache-2.0
1,176
0.00085
# ============================================================================= # 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 #...
ENSE-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 implied. # See the License for the s
pecific language governing permissions and # limitations under the License. # ============================================================================= """Custom op used by periodic_resample.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tenso...
Azure/azure-sdk-for-python
sdk/graphrbac/azure-graphrbac/azure/graphrbac/models/check_group_membership_result_py3.py
Python
mit
1,366
0.002196
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
zed this collection :type additional_properties: dict[str, object] :param value: True
if the specified user, group, contact, or service principal has either direct or transitive membership in the specified group; otherwise, false. :type value: bool """ _attribute_map = { 'additional_properties': {'key': '', 'type': '{object}'}, 'value': {'key': 'value', 'type': 'bo...
gobstones/PyGobstones-Lang
pygobstoneslang/lang/ast.py
Python
gpl-3.0
24,838
0.002657
# -*- coding: utf-8 -*- # # Copyright (C) 2011, 2012 Pablo Barenbaum <foones@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 # the Free Software Foundation, either version 3 of the License, or # (at your option) a...
) return ret def _concat_internal_list_generators(expr_list): return expr_list def _infixl(subtr
ees, action): "Expands an action corresponding to an INFIXL declaration." # arg1 opr1 (arg2 opr2 arg3) ---> (arg1 opr1 arg2) opr2 arg3 # |---- right ---| |---- left ----| operator_type = action[1] arg1 = subtrees[1] opr1_args = subtrees[2] if opr1_args is None: ret...
rajegannathan/grasp-lift-eeg-cat-dog-solution-updated
python-packages/mne-python-0.10/mne/decoding/transformer.py
Python
bsd-3-clause
19,949
0.000201
# Authors: Mainak Jas <mainak@neuro.hut.fi> # Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr> # Romain Trachel <trachelr@gmail.com> # # License: BSD (3-clause) import numpy as np from .mixin import TransformerMixin from .. import pick_types from ..filter import (low_pass_filter, high_p...
picks_list_ = picks_list for key, this_pick in picks_list.items(): if self.with_mean: ch_mean = X[:, thi
s_pick, :].mean(axis=1)[:, None, :] self.ch_mean_[key] = ch_mean # TODO rename attribute if self.with_std: ch_std = X[:, this_pick, :].mean(axis=1)[:, None, :] self.std_[key] = ch_std # TODO rename attribute return self def transform(self, epoc...
Safuya/python_3_essential_training
07 Loops/loop_control.py
Python
gpl-3.0
223
0.004484
def main(): s = 'this is a string' for c in s: print(c, end='') else: print(' else')
print() for i in range(10, 0, -1): print(i, end=' ') if __name__ == "__main__": main(
)
3dfxsoftware/cbss-addons
account_partner_ledger_report/__openerp__.py
Python
gpl-2.0
1,670
0.001796
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Addons modules by CLEARCORP S.A. # Copyright (C) 2
009-TODAY CLEARCORP S.A. (<http://clearcorp.co.cr>). # # 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 opti
on) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a ...
washbz250/LearnPythonTheHardWay
Python3/Projects/hi_lo.py
Python
unlicense
1,616
0.001238
import random is_alive = True while is_alive is True: guess_right = False num = random.randrange(1, 100) guess = 0 guess_num = 0 print("Hi-Lo guessing game") print("I came up with a number between 1 and 100") print("You have to guess the number. If your guess is higher, I will tell you so. ...
if restart is 1: print("Playing again...") elif restart is 2:
print("Quitting. Thanks for playing") is_alive = False except ValueError: print("Press 1 to restart, 2 to quit.")
21strun/django-coverage
assets/badges/drone.io/badge_maker.py
Python
apache-2.0
1,424
0.00632
""" Drone.io badge generator. Currently set up to work on Mac. Requires Pillow. """ import os fro
m PIL import Image, ImageDraw, ImageFont SIZE = (95, 18) def hex_colour(hex): if hex[0] == '#': hex = hex[1:] return ( int(hex[:2], 16), int(hex[2:4], 16), int(hex[4:6], 16), ) BACKGROUND = hex_colour('#4A4A4A') SUCCESS = hex_colour('#94B944') WARNING = hex_colour('#E4A83C...
Font.truetype(size=10, filename="/Library/Fonts/Arial.ttf") FONT_SHADOW = hex_colour('#525252') PADDING_TOP = 3 def build_image(percentage, colour): image = Image.new('RGB', SIZE, color=BACKGROUND) drawing = ImageDraw.Draw(image) drawing.rectangle([(55, 0), SIZE], colour, colour) drawing.text((8,...
baigk/compass-core
compass/deployment/utils/__init__.py
Python
apache-2.0
638
0
# Copyright 2
014 Huawei Technologies Co. 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 agreed to in writin...
he specific language governing permissions and # limitations under the License. __author__ = "Grace Yu (grace.yu@huawei.com)"
nimadini/Teammate
handlers/home/upload_url.py
Python
apache-2.0
600
0.003333
__author__ = 'stanley' from domain.user import * from google.appengine.api import users from google.appengine.ext import blobstore import webapp2 import json class Upl
oadURLHandler(webapp2.RequestHandler): def post(self): usr = user_key(users.get_current_user().email()).get() if usr is None: return # TODO cover_upload_url = blobstore.create_upload_url('/upload') self.response.headers['Content-Type'] = 'application/json' resu...
ver_upload_url}) self.response.write(result)
PagueVeloz/ClientAPI
python/pagueveloz/api/v3.py
Python
mit
295
0.006849
#!/usr/bin/env python # -*- coding: utf-8 -*- from base import PagueVelozCl
ient VERSAO = 'v3' class Boleto(PagueVelozClient): '''Serviço de emissão e consulta de Boletos Bancários.''' def __init__(self, chave=None): PagueVelozClient.__init__(self, VERSAO, 'Boleto', chave
)
jsha/letsencrypt
certbot/plugins/common.py
Python
apache-2.0
16,182
0.001051
"""Plugin common functions.""" import logging import os import re import shutil import tempfile import OpenSSL import pkg_resources import zope.interface from acme.jose import util as jose_util from certbot import constants from certbot import crypto_util from certbot import errors from certbot import interfaces fro...
er.view_config_changes() except errors.ReverterError as err: raise errors.PluginError(str(err)) @property def ssl_dhparams(self): """Full absolute path to ssl_dhparams file.""" return os.path.join(self.config.config_dir, constants.SSL_DHPARAMS_DEST) @property def up...
s file.""" return os.path.join(self.config.config_dir, constants.UPDATED_SSL_DHPARAMS_DIGEST) def install_ssl_dhparams(self): """Copy Certbot's ssl_dhparams file into the system's config dir if required.""" return install_version_controlled_file( self.ssl_dhparams, s...
HiSPARC/publicdb
publicdb/inforecords/migrations/0011_remove_pulseheightthresholds.py
Python
gpl-3.0
507
0
# -*- coding: utf-8 -*- # Generated by Django 1.10.8 on 2018-07-22 10:50 from __future__ import unicode_literals from django.db import migrations
class Migration(migrations.Migration): dependencies = [ ('inforecords', '0010_related_names'), ] operations = [ migrations.RemoveField(
model_name='monitorpulseheightthresholds', name='station', ), migrations.DeleteModel( name='MonitorPulseheightThresholds', ), ]
beni55/sentry
src/sentry/migrations/0068_auto__add_field_projectkey_user_added__add_field_projectkey_date_added.py
Python
bsd-3-clause
20,383
0.008242
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'ProjectKey.user_added' db.add_column('sentry_projectkey', 'user_added', ...
sentry.filterkey': { 'Meta': {'uniq
ue_together': "(('project', 'key'),)", 'object_name': 'FilterKey'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'key': ('django.db.models.fields.CharField', [], {'max_length': '32'}), 'project': ('django.db.models.fields.related.ForeignKey', [], {'to': "...
Qirky/PyKinectTk
PyKinectTk/utils/3D.py
Python
gpl-3.0
2,821
0.008862
""" 3D.py is the interface for plotting Skeleton Wireframes in a 3D perspective using matplotlib """ # 3D Plotting tool from matplotlib import pyplot as plt from matplotlib import animation from mpl_toolkits.mplot3d import Axes3D # PyKinect XEF modules import Colour #: 3D View Obj class View: def __ini...
try: self.draw_body(body, frame) except: pass if blitting: self.fig.canvas.blit() else: self.display()
return @staticmethod def display(): plt.show() def draw_body(self, body, frame): """ Draws one body at frame """ bone = 0 for joint in self.bodies[body]: for start, end in joint.bones_3D(frame): self.draw_bone(body, start, end, bone) ...
eske/seq2seq
scripts/post_editing/select-by-ter.py
Python
apache-2.0
1,303
0.00307
#!/usr/bin/env python3 import argparse import numpy as np import random import sys parser = argparse.ArgumentParser() parser.add_argument('ref_vectors') parser.add_argument('vectors') parser.add_argument('-n', type=int, default=500000) parser.add_argument('-k', type=int, default=1) parser.add_argument('-m', type=int...
(l), k=args.m) if args.k > 1: indices = sorted(indices, key=key)[:args.k] else: indices = [min(indices, key=key)] for i in indices: sys.stdout.write(str(vectors[i][0]) + '\n') #sys.stdout.flush() for i in indices: vectors[i], ve...
rs[l - 1] = vectors[l - 1], vectors[i] l -= 1
mthipparthi/parliament-search
parliamentsearch/pipelines.py
Python
mit
1,789
0.001118
# -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html from scrapy.conf import settings import pymongo from datetime import datetime from .models import PQDataModel class Parliamen...
record.question_url = q['question_url'] record.question_date = datetime.strptime(q['question_date'], '%d.%m.%Y') records.append(record) for record in records: batch.save(record)
henryneu/Python
sample/mydict2.py
Python
apache-2.0
836
0.024155
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # 文档测试 class Dict(dict): ''' Simple dict but also support access as x.y style >>> d1 = Dict() >>> d1['x'] = 100 >>> d1.x 100 >>> d1.y = 200 >>
> d1['y']
200 >>> d2 = Dict(a=1, b=2, c='3') >>> d2.c '3' >>> d2['empty'] Traceback (most recent call last): ... KeyError: 'empty' >>> d2.empty Traceback (most recent call last): ... AttributeError: 'Dict' object has no attribute 'empty' ''' def __init__(self, **kw): sup...
edeposit/edeposit.amqp.ltp
src/edeposit/amqp/ltp/amqp_structures/responses.py
Python
mit
725
0
#! /usr/bin/env python # -*- coding: utf-8 -*- # # Interpreter version: python 2.7 # # Imports ===================================================================== from collections import namedtuple # Functions & classes ==================================
======================= class TrackingResponse(namedtuple("TrackingResponse", ["book_id", "exported", "error"])): """ Result of the :class:`.TrackingRequest`. Attributes: book_id (str): ID ...
y exported. error (str): Type of error if the export failed. """
openstack/designate
designate/tests/unit/test_context.py
Python
apache-2.0
3,468
0
# Copyright 2012 Managed I.T. # # Author: Kiall Mac Innes <kiall@managedit.ie> # # 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 r...
) ctxt.sudo('new_projec
t') self.assertTrue(mock_policy_check.called) self.assertEqual('new_project', ctxt.project_id) self.assertEqual('old_project', ctxt.original_project_id)
Quantika14/pygtkcodebuffer
examples/simple-edit.py
Python
lgpl-3.0
2,136
0.015449
#!/usr/bin/python import gtk import gtk.glade import os import glob import os.path import re # not needed if you have codebuffer installed: import sys sys.path.insert(0, "..") from gtkcodebuffer import CodeBuffer, SyntaxLoader, add_syntax_path # also not needed if installed: add_syntax_path("../syntax/") class ...
r(self.__buffer) def on_lang_changed(self, widget, lang): lspec = SyntaxLoader(lang) self.__buffer.reset_language(lspec) def on_open(self, widget): dlg = gtk.FileSelection("Open...") if not dlg.run() == gtk.RESPONSE_OK: dlg.des...
.read()) def on_show_info(self, widget): dlg = gtk.glade.XML(self.__gladefile, "aboutdialog").get_widget("aboutdialog") dlg.run() dlg.destroy() def on_destroy(self, widget): gtk.main_quit() if __name_...
jimmyDunne/perimysium
perimysium/modeling.py
Python
bsd-3-clause
34,048
0.001909
# ----------------------------------------------------------------------- # # The OpenSim API is a toolkit for musculoskeletal modeling and # # simulation. See http://opensim.stanford.edu and the NOTICE file # # for more information. OpenSim is developed at Stanford University # # and supported ...
# # 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 # # distrib...
WARRANTIES OR CONDITIONS OF ANY KIND, either express or # # implied. See the License for the specific language governing # # permissions and limitations under the License. # # ----------------------------------------------------------------------- # # # Authors: Christopher D...
chubbymaggie/claripy
tests/test_balancer.py
Python
bsd-2-clause
4,706
0.009137
import claripy def test_complex_guy(): guy_wide = claripy.widen( claripy.union( claripy.union( claripy.union(claripy.BVV(0L, 32), claripy.BVV(1, 32)), claripy.union(claripy.BVV(0L, 32), claripy.BVV(1, 32)) + claripy.BVV(1, 32) ), claripy.u...
64)).compat_ret assert r[0][0] is guy_wide assert claripy.backends.vsa.min(r[0][1]) == 0 assert set(claripy.backends.vsa.eval(r[0][1], 1000)) == set([4294967295] + range(39)) def test_simple_guy(): x = claripy.BVS('x', 32) s,r = claripy.balancer.Balancer(claripy.backends.vsa, x <= claripy.BVV(39, 3...
is x assert claripy.backends.vsa.min(r[0][1]) == 0 assert claripy.backends.vsa.max(r[0][1]) == 39 s,r = claripy.balancer.Balancer(claripy.backends.vsa, x + 1 <= claripy.BVV(39, 32)).compat_ret assert s assert r[0][0] is x all_vals = r[0][1]._model_vsa.eval(1000) assert len(all_vals) as...
edent/BMW-i-Remote
python/bmw.py
Python
mit
4,929
0.009333
#! /usr/bin/env python # # Use the BMW ConnectedDrive API using credentials from credentials.json # You can see what should be in there by looking at credentials.json.sample. # # 'auth_basic' is the base64-encoded version of API key:API secret # You can capture it if you can intercept the traffic from the app at # the ...
l(self, path, post_data=None): """ Call the API at the given path. Argument should be relative to the API base
URL, e.g: print c.call('/user/vehicles/') If a dictionary 'post_data' is specified, the request will be a POST, otherwise a GET. """ # if (time.time() > self.token_expiry): self.generateCredentials() headers = {"Authorization": "Bearer ...
emollient/WITRapp
witrapp/witrapp/__init__.py
Python
gpl-2.0
654
0
from pyramid.config import Configurator from sqlalchemy import engine_from_config from .models import ( DBSession, Base, ) def main(global_config, **settings): """ This function returns a Pyramid WSGI application. """ engine = engine_f
rom_config(settings, '
sqlalchemy.') DBSession.configure(bind=engine) Base.metadata.bind = engine config = Configurator(settings=settings) config.include('pyramid_mako') config.add_static_view('static', 'static', cache_max_age=3600) config.add_route('home', '/') config.add_route('all_songs_play', '/allsongs') ...
jmazon/libanki
anki/importing/anki10.py
Python
gpl-3.0
3,247
0.000616
# -*- coding: utf-8 -*- # Copyright: Damien Elmes <anki@ichi2.net> # License: GNU GPL, version 3 or later; http://www.gnu.org/copyleft/gpl.html """\ Importing Anki 0.9+ decks ========================== """ __docformat__ = 'restructuredtext' from anki import DeckStorage from anki.importing import Importer from anki.sy...
in %s" % ids2str([x[0] for x in res['added-facts']['facts']]), t=time.time()) self.deck.s.statement( "update models set modified = :t where id in %s" % ids2str([x['id'] for x in res['added-models']]), t=time.time()) # update total and refresh self.total = len...
# randomize? if random: self.deck.updateProgress() self.deck.randomizeNewCards([x[0] for x in res['added-cards']]) self.deck.flushMod() self.deck.finishProgress() def _clearDeleted(self, sum): sum['delcards'] = [] sum['delfacts'] = [] sum['del...
sdpython/ensae_teaching_cs
src/ensae_teaching_cs/data/gutenberg.py
Python
mit
1,949
0.000513
# -*- coding: utf-8 -*- """ @file @brief Link to data from `Gutenberg <http://www.gutenberg.org/>`_, provides an automated way to get the data from this website. Some data may be replicated here to unit test notebooks. """ import os import urllib.request from urllib.error import URLError def gutenberg_name(name="cond...
text = u.read() u.close() except URLError: # we switch to local text = None if text is not None: text = text.decode("utf8") return text if not os.path.exists(loc): ...
or(loc) with open(loc, "r", encoding="utf8") as f: text = f.read() return text else: if local: if not os.path.exists(loc): raise FileNotFoundError(loc) return loc else: return url ...
ongame-entretenimento/cadastro
usuario/migrations/0004_usuario_hash.py
Python
mit
446
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration):
dependencies = [ ('usuario', '000
3_auto_20140909_1051'), ] operations = [ migrations.AddField( model_name='usuario', name='hash', field=models.CharField(default=0, max_length=32), preserve_default=False, ), ]
sandvine/horizon
openstack_dashboard/urls.py
Python
apache-2.0
1,914
0
# Copyright 2012 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Copyright 2012 Nebula, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file excep
t 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 l
aw 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 implied. See the # License for the specific language governing permissions and limitations # under the License. """ URL patterns for the...
asedunov/intellij-community
python/testData/copyPaste/EmptyFunctionCaretAtNoneIndent.src.py
Python
apache-2.0
153
0.052288
class C: def empty(s
elf): def another(self): <selection> """ line 1 line 2 """ pass </selection>
victorwestmann/wttd
eventex/subscriptions/tests.py
Python
lgpl-2.1
1,211
0.024773
# coding: utf-8 from django.test import TestCase from eventex.subscriptions.forms import SubscriptionForm class SubscribeTest(TestCase): def setUp(self): self.resp = self.client.get('/inscricao/') def test_get(self): 'GET /inscricao/ must return status code 200.' self.assertEqual(200, self.resp.status_code) ...
plateUsed(self.resp, 'subscriptions/subscription_form.html') def test_html(self): 'Html must contain input controls.' self.assertContains(self.resp, '<form') self.assertContains(self.resp, '<input', 6) self.assertContains(self.resp, 'type="text"', 3) self.
assertContains(self.resp, 'type="email"') self.assertContains(self.resp, 'type="submit"') def test_csrf(self): 'Html must contain csrf token.' self.assertContains(self.resp, 'csrfmiddlewaretoken') def test_has_form(self): 'Context must have the subscription form.' form = self.resp.context['form'] self.a...
LumaPictures/rez
src/rez/serialise.py
Python
lgpl-3.0
11,794
0.000933
""" Read and write data from file. File caching via a memcached server is supported. """ from rez.package_resources_ import package_rex_keys from rez.utils.scope import ScopeContext from rez.utils.sourcecode import SourceCode, early, late, include from rez.utils.logging_ i
mport print_debug from rez.utils.fil
esystem import TempDirs from rez.exceptions import ResourceError, InvalidPackageError from rez.utils.memcached import memcached from rez.utils.syspath import add_sys_paths from rez.config import config from rez.vendor.enum import Enum from rez.vendor import yaml from contextlib import contextmanager from inspect import...
hivesolutions/appier
src/appier/test/model.py
Python
apache-2.0
28,833
0.006903
#!/usr/bin/python # -*- coding: utf-8 -*- # Hive Appier Framework # Copyright (c) 2008-2021 Hive Solutions Lda. # # This file is part of Hive Appier Framework. # # Hive Appier Framework is free software: you can redistribute it and/or modify # it under the terms of the Apache License as published by the Apach...
= 1) self.assertEqual(len(result), 0) person = mock.Person() person.age = 1 person.name = "Name" person.save() result = mock.Person.find(age = 1) self.assertEqual(len(result), 1) self.assertEqual(result[0].age, 1) def test_count(self): ...
ount() self.assertEqual(result, 0) person = mock.Person() person.age = 1 person.name = "Name" person.save() result = mock.Person.count() self.assertEqual(result, 1) def test_delete(self): result = mock.Person.count() self.assert...
Kortemme-Lab/kddg
.test/settings.py
Python
mit
262
0
#!/usr/bin/python2 """ .te
st/settings.py A simple test script for the settings module. Created by Shane O'Connor 2016. """ import kddg.api.settings as settings sys_settings = settings.load() print(s
ys_settings.database) print(sys_settings.database.username)
huqa/pyfibot_modules
module_horo.py
Python
mit
933
0.00431
# -*- coding: utf-8 -*- """ Fetches horoscopes from iltalehti.fi Created on Oct 17, 2012 @author: huqa / pikkuhukka@gmail.com """ import re horo_url = "http://www.iltalehti.fi/horoskooppi" def command_horo(bot, user, channel, args): """Hakee päivittäisen horoskoopin. Käyttö !horo
<horoskooppimerkki>""" nick = getNick(user) if not args: return bot.say(channel, "lähe ny pelle menee %s" % nick) haku = args.decode('iso-8859-1') haku = haku.title() soup = getUrl(horo_url).getBS() merkki = None for m in soup.findAll("div", "valiotsikko"): if m.fi...
break if not merkki: return bot.say(channel, "opettele ny kirjottaan kevyt pelle %s" % nick) tekstit = merkki.next.contents[0] bot.say(channel, "%s %s" % (str(merkki), str(tekstit)))
francisrod01/wrangling_mongodb
lesson 6/name.py
Python
mit
1,880
0.000532
#!~/envs/udacity_python3_mongodb # -*- coding: utf-8 -*- """ In this problem set you work with cities infobox data, audit it, come up with a cleaning idea and then clean it up. In the previous quiz you recognized that the "name" value can be an array (or list in Python terms). It would make it easier to process and qu...
line["name"] = fix_name(line["name"]) data.append(line) return data def test(): data = process_file(CITIES_DATA) print("Printing 20 results:") for n in range(20): pprint.pprint(data[n]["name"
]) assert data[14]["name"] == ['Negtemiut', 'Nightmute'] assert data[9]["name"] == ['Pell City Alabama'] assert data[3]["name"] == ['Kumhari'] if __name__ == "__main__": test()
vlki/spacewalk-xmlrpc-tests
tests/xmlrpc_scripts/frontend/errata.clone.py
Python
bsd-3-clause
1,293
0.003867
#!/usr/bin/env python # Copyright (c) 2011, Jan Vlcek # All rights reserved. # # For further information see enclosed LICENSE file # # Python script calling the XML-RPC errata.clone of local Spacewalk server. # # Usage: # ./errata.clone.py session-key channel-label [adv-name [adv-name [...]]] # # Author: Jan Vlcek <...
lient.errata.clone(sessionKey, channelLabel, advisoryNames) for erratum in errata:
print(erratum['advisory_name']) def usage(): """ Prints the usage information. """ print("Python script calling the XML-RPC errata.clone") print("of Spacewalk frontend API.") print("") print("Cloned erratum advisory names are printed by line") print("") print("Usage:") print...
hastexo/hastexo-xblock
hastexo/provider.py
Python
agpl-3.0
27,375
0
import time import base64 import binascii import hashlib import logging import paramiko import random import string import yaml try: from io import StringIO except ImportError: from StringIO import StringIO from heatclient.exc import HTTPException, HTTPNotFound from keystoneauth1.exceptions.http import HttpEr...
.op
enstack import HeatWrapper, NovaWrapper from .gcloud import GcloudDeploymentManager, GcloudComputeEngine class ProviderException(Exception): pass class Provider(object): """ Base class for provider drivers. """ default_credentials = None credentials = None name = None capacity = Non...
Yordan92/Pac-man-multiplayer
Ghosts.py
Python
gpl-3.0
5,718
0.047919
from MakeGraph import MakeGraph from Moving_pacman import PacMan import pygame class Ghost(MakeGraph): index = 0 def __init__(self,class_graph,x,y): Ghost.index = Ghost.index + 1 self.all_nodes = class_graph.get_nodes() self.paths_to_all_nodes = class_graph.get_shortest_path() self.path = [] self.hunt...
(int(self.cords['y']/23),int(self.cords['x']/23)) if my_cords == pacman_vertex: self.hunting = True if self.hu
nting == True: self.path = self.search_eat(pacman_cords) if not self.path: if self.hunting == True: self.hunting = False if self.find_closest_vertex() != []: self.path = self.find_closest_vertex() else: for i in self.paths_to_all_nodes[my_cords][pacman_vertex]: self.path.ext...
ProfessionalIT/professionalit-webiste
sdk/google_appengine/google/appengine/ext/mapreduce/model.py
Python
lgpl-3.0
38,467
0.006603
#!/usr/bin/env python # # Copyright 2007 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 o...
ef increment(self, counter_name, delta): """Increment counter valu
e. Args: counter_name: counter name as String. delta: increment delta as Integer. Returns: new counter value. """ current_value = self.counters.get(counter_name, 0) new_value = current_value + delta self.counters[counter_name] = new_value return new_value def add_map(s...
fahri314/image-processing
13.py
Python
gpl-3.0
649
0.032407
# 12 nin düzenli hali import matplotlib.pyplot as plt import numpy as np from scipy.misc import imsave def convert(image_1): # rgb to gray level img_1 = plt.imread(image_1) img_2 = np.zeros((img_1.shape[0],i
mg_1.shape[1])) for i in range (img_1.shape[0]): for j in range (img_2.shape[1]): img_2[i,j] = img_1[i,j,0]/3 + img_1[i,j,1]/3 + im
g_1[i,j,2]/3 imsave(r'C:\Users\user\Desktop\gray.png', img_2) plt.subplot(1,2,1) plt.imshow(img_1) plt.subplot(1,2,2) plt.imshow(img_2,cmap = 'gray') plt.show() convert(r'C:\Users\user\Desktop\eleven.png')
bgossele/geminicassandra
geminicassandra/vep.py
Python
mit
11,612
0.004995
#!/usr/bin/env python ############# # CSQ: Consequence|Codons|Amino_acids|Gene|hgnc|Feature|EXON|polyphen|sift|Protein_position|BIOTYPE # missense_variant|gAg/gTg|E/V|ENSG00000188157||ENST00000379370|12/36|probably_damaging(0.932)|deleterious(0.02)|728/2045_protein_coding # nc_transcript_variant|||ENSG00000116254|CHD...
plice_donor', 'stop_gained': 'stop_gain', 'stop_lost': 'stop_loss', 'non_coding_exon_variant': 'nc_exon', 'frameshift_variant': 'frame_shift', 'initiator_codon_variant': 'transcript_codon_change', 'inframe_deletion': '
inframe_codon_loss', 'inframe_insertion': 'inframe_codon_gain', 'missense_variant': 'non_syn_coding', 'splice_region_variant': 'splice_region', 'incomplete_terminal_codon_variant': 'incomplete_terminal_codon', 'stop_retained_variant': 'synonymous_stop', 'synonymous_variant': 'synonymous_coding', 'coding...
hanset/kanban
board/models.py
Python
gpl-3.0
1,141
0.004382
import datetime from django.db import models from django.contrib.auth.models import User
from django.utils import timezone from django.forms import ModelForm class Task(models.Model): creator = models.ForeignKey(User, related_name='Creator') owner = models.ForeignKey(User, related_name='Owner') creation_date = models.DateTimeField('Date created', auto_now=True) work_date = models.DateTime...
ue) description = models.TextField(max_length=500) name = models.CharField(max_length=40) todo = 'To do' inprogress = 'In Progress' finished = 'Finished' state_choices = ( (todo, 'To do'), (inprogress, 'In progress'), (finished, 'Finished'), ) state = models.C...
coffeestats/coffeestats-django
coffeestats/caffeine_oauth2/urls.py
Python
mit
1,723
0
from __future__ import absolute_import from django.conf.urls import url from oauth2_provider import views from .views import CoffeestatsApplicationRegistration, \ CoffeestatsApplicationDetail, \ CoffeestatsApplicationApproval, \ CoffeestatsApplicationRejection, \ CoffeestatsApplicationFullList urlpat...
ate"), url(r'^applications/(?P<pk>\d+)/approve/$', CoffeestatsApplicationApproval.as_view(), name="approve"), url(r'^applications/(?P<pk>\d+)/reject/$', CoffeestatsApplicationRejection.as_view(), name="reject"), url(r'^all-applications/$', CoffeestatsApplicationFullList.as_view()
, name="list_all"), ) urlpatterns += ( url(r'^authorized_tokens/$', views.AuthorizedTokensListView.as_view(), name="authorized-token-list"), url(r'^authorized_tokens/(?P<pk>\d+)/delete/$', views.AuthorizedTokenDeleteView.as_view(), name="authorized-token-delete"), )
i32algae/pruebais
usuario/views.py
Python
gpl-3.0
710
0.023944
from django.contrib.auth.decorators import login_required from django.shortcuts import render from django.contrib.auth.models import User from django.core.urlresolvers import reverse from django.http.response import HttpResponseRedirect from django.shortcuts import render_to_response from django.template.context impor...
rm = SignUpForm(request.POST) if form.is_valid(): user=form.save() user.set_password(u
ser.password) user.save() return HttpResponseRedirect('/') else: form = SignUpForm() context={'form':form} return render(request,'signup.html',context)
grnet/ganetimgr
apply/__init__.py
Python
gpl-3.0
48
0
# default_app
_config = 'apply.apps.ApplyConfig'
cronuspaas/cronusagent
agent/agent/tests/unit/test_cleanup.py
Python
apache-2.0
7,566
0.006609
from agent.tests import * import pylons import os import logging import time import json from pylons import config from subprocess import Popen from agent.controllers.service import ServiceController from agent.lib.utils import rchown from agent.lib.packagemgr import PackageMgr from agent.tests.unit.test_util import ...
NotEquals(process.poll(), None) def test_delete_cronus_package(self): package = "pkgA-1.2.0.unix" package_url = "http://www.stackscaling.com/agentrepo/pkgA-1.2.0.unix.cronus" package_path = os.path.join(PackageMgr.packagePath(), package + '.cronus') # case 1 - package is not presen...
= True) self.assertEqual(response.status_int, 200) # case 2 - package is present mockDownloadPkg(package_url) body = json.dumps({'package': package_url, 'packageloc' : package + '.cronus'}) response = self.app.post(url(controller = 'distribution', action = 'startdownload', serv...
maggotgdv/fofix
src/midi/constants.py
Python
gpl-2.0
6,364
0.008642
# -*- coding: ISO-8859-1 -*- ################################################### ## Definitions of the different midi events ################################################### ## Midi channel events (The most usual events) ## also called "Channel Voice Messages" NOTE_OFF = 0x80 # 1000cccc 0nnnnnnn 0vvvvvvv (chann...
wwww (lo-position, hi-position) SONG_SELECT = 0xF3 # 11110011 0sssssss
(songnumber) #UNDEFINED = 0xF4 ## 11110100 #UNDEFINED = 0xF5 ## 11110101 TUNING_REQUEST = 0xF6 # 11110110 END_OFF_EXCLUSIVE = 0xF7 # terminator # 11110111 # End of system exclusive ################################################### ## Midifile meta-events SEQUENCE_NUMBER = 0x00 # 00 02 ss ss (seq-number) T...
djoproject/pyshell
pyshell/utils/key.py
Python
gpl-3.0
5,081
0
#!/usr/bin/env python -t # -*- coding: utf-8 -*- # Copyright (C) 2015 Jonathan Delvaux <pyshell@djoproject.net> # 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...
.__name__
+") " "__init__, invalid hexa string, start" " with 0x but is not valid: "+str(ve)) self.keyType = CryptographicKey.KEYTYPE_HEXA self.key = key_string[2:] temp_key_size = float(len(key_string) - 2) ...
yuxans/badgirl
src/coin.py
Python
gpl-2.0
1,861
0.020956
#!/usr/bin/env python # Copyright (c) 2003 Phil Gregory # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This p
rogram 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 rece
ived a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # """coin.py - flips a coin on demand""" handler_list=["coin"] from moobot_module import MooBotModule class coin(MooBotModule): ...
ruchee/vimrc
vimfiles/bundle/vim-python/submodules/pylint/tests/input/func_i0012.py
Python
mit
78
0
# pylint:enable=W0404 """check
warning on local enabling """ __revision__ = 1
hgmeyer/BIVAC
sw/image_processing/remapping/Unwarper.py
Python
gpl-3.0
3,590
0.002507
""" Implements a task for unwarping the camera images """ import multiprocessing import cv2 from image_processing.remapping.OCameraModel import OCameraModel class Unwarper(multiprocessing.Process): """ This class implements a task for unwarping the images obtained from a camera with a fisheye lens """ ...
lf._exit.is_set(): # ...get data from input queue self._parse_input() # ...remap image img_remapped = cv2.remap(self._img, self._mapx, self._mapy, cv2.INTER_AREA) # ...flip image if self._flip_image: img_remapped = cv2.flip(img_re...
) img_remapped = cv2.flip(img_remapped, 1) # ...put image in output queue self._output_queue.put(({'remapped_image': img_remapped})) def terminate(self): """ Called when task is terminated. Overwrites multiprocessing.Process.terminate() function """ ...
zachjanicki/osf.io
website/addons/dataverse/tests/test_model.py
Python
apache-2.0
3,530
0.0017
from nose.tools import * # noqa import mock from tests.base import get_default_metaschema from framework.auth.decorators import Auth from website.addons.base.testing import models from website.addons.dataverse.model import AddonDataverseNodeSettings from website.addons.dataverse.tests.factories import ( Dataver...
su
per(TestNodeSettings, self).setUp() self.set_node_settings(self.node_settings) @mock.patch('website.archiver.tasks.archive') def test_does_not_get_copied_to_registrations(self, mock_archive): registration = self.project.register_node( schema=get_default_metaschema(), aut...
klim-iv/phantomjs-qt5
src/webkit/Tools/Scripts/webkitpy/thirdparty/mod_pywebsocket/standalone.py
Python
bsd-3-clause
44,901
0.00029
#!/usr/bin/env python # # Copyright 2012, Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list...
nd run $ python standalone.py -d example to launch pywebsocket with the sample handler and html on port 80. Open http://localhost/console.html, click the connect button, type something into the text box next to the send button and click the send button. If everything is working, you'll see the message you typed ech...
.py with -t, -k, and -c options. Note that when ssl module is used and the key/cert location is incorrect, TLS connection silently fails while pyOpenSSL fails on startup. SUPPORTING CLIENT AUTHENTICATION To support client authentication with TLS, run standalone.py with -t, -k, -c, and --tls-client-auth, and --tls-c...
sch3m4/SerialCrypt
apps/locate.py
Python
bsd-3-clause
724
0.03453
#!/usr/bin/env python # # Written by Chema Garcia (aka sch3m4) # Contact: chema@safetybits.net || http://safetybits.net || @sch3m4 # import
serial.tools.list_ports from SerialCrypt import Devices def locateDevice(devid): ''' Returns the serial port path of the arduino if found, or None if it isn't connected ''' retval = None for port in serial.tools.list_ports.comports(): if port[2][:len(devid)] == devid: retval = port[0] break return retv...
% locateDevice ( Devices.DEVICE_CRYPT_ID ) print "uToken Device: %s" % locateDevice ( Devices.DEVICE_UTOKEN_ID ) print "Debug Device: %s" % locateDevice ( Devices.DEVICE_DEBUG_ID ) if __name__ == "__main__": main()
garmann/playground
python/python_mysql_queue/app.py
Python
mit
2,098
0.035272
#!/usr/bin/env python3 from classes.myqueue import MyQueue import time # time.sleep(0.02) import random # random.randint(1, 100
) im
port socket # socket.gethostname() import sys import argparse CONF_DB = { 'server': 'localhost', 'user': 'root', 'pass': 'x', 'db': 'myqueue' } def worker_create(q, amount): # makes objects in state new hostname = socket.gethostname() while amount > 0: amount -= 1 objectname = "{}_{}_{}".format(...
opethe1st/CompetitiveProgramming
CodeChef/2017/LongChallenge/September/ChefSum.py
Python
gpl-3.0
284
0.007042
def solution(A): mini = A[0]
minindex = 0 for i in xrange(len(A)): if mini > A[i]: mini = A[i] minindex = i return minindex+1 T = input() for _ in xrange(T): N = input() A = m
ap(int, raw_input().split()) print(solution(A))
Zolertia/openthread
tests/scripts/thread-cert/Cert_5_5_01_LeaderReset.py
Python
bsd-3-clause
3,068
0.001304
#!/usr/bin/python # # Copyright (c) 2016, The OpenThread Authors. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright # not...
ucts # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ...
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABI...
tmetsch/graph_stitcher
tests/stitcher_iterative_repair_test.py
Python
mit
7,668
0
""" Unittests for iterative_repair module. """ import json import unittest import networkx as nx from networkx.readwrite import json_graph from stitcher import iterative_repair def _sample_data(): cont = nx.DiGraph() cont.add_node('1', **{'type': 'a', 'group': 'foo', 'rank': 1.0}) cont.add_node('2', *...
rt_for_sanity(self): """ Test for sanity. """ res = iterative_repair.convert_conditions(self.cond) self.assertIn('a', res) self.assertIn('b', res) self.assertIn('x', res) self.assertIn('y', res) self.assertIn('1', res) self.assertIn('2', re...
lt, lg, regex, nshare self.assertTrue(len(res['b']) == 1) # nshare self.assertTrue(len(res['x']) == 1) # share self.assertTrue(len(res['y']) == 1) # share self.assertTrue(len(res['1']) == 2) # same, diff self.assertTrue(len(res['2']) == 1) # same self.assertTrue(len...