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
kkstu/DNStack
model/models.py
Python
mit
3,358
0.014627
#!/usr/bin/python # -*- coding:utf-8 -*- # Powered By KK Studio from sqlalchemy import Column, Integer, SmallInteger, VARCHAR, or_, and_ from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class User(Base): __tablename__ = 'users' id = Column(Integer,primary_key=True,autoincrem...
CHAR(32),nullable=False,unique=True) password = Column(VARCHAR(64),nullable=False) password_key = Column(VARCHAR(12),nullable=False,default='a1b2c3d4e5f6') email = Column(VARCHAR(32),nullable=False,unique=True) phone = Column(VARCHAR(32),nullable=True) nickname = Column(VARCHAR(32),nullable=True) ...
HAR(32),nullable=True) lang = Column(VARCHAR(12),nullable=False,default='zh_CN') login_count = Column(Integer,nullable=False,default=0) login_time = Column(Integer,nullable=True) login_ua = Column(VARCHAR(600),nullable=True) login_ip = Column(VARCHAR(64),nullable=True) login_location = Column(VA...
nfqsolutions/pylm
examples/parallel/worker.py
Python
agpl-3.0
297
0.006734
from pylm.servers import Worker from uuid import uuid4 import sys class MyWorker(Worker): de
f foo(self, message): return self.name.encode('utf-8') + b' processed ' + message server = MyWorker(str(uuid4()), 'tcp://127
.0.0.1:5559') if __name__ == '__main__': server.start()
davidsetiyadi/draft_python
new_edukits/edukits_total_retail_report.py
Python
gpl-3.0
24,578
0.033282
import time from datetime import datetime from pytz import timezone from dateutil.relativedelta import relativedelta import openerp from openerp.report.interface import report_rml from openerp.tools import to_xml from openerp.report import report_sxw from datetime import datetime from openerp.tools.translate import _ f...
art="0,0" stop="-1,-1"/> <lineStyle kind="LINEBELOW" colorName="#000000" start="0,1" stop="0,1"/> <lineStyle kind="LINEABOVE" colorName="#000000" start="0,0" stop="0,0"/> <lineStyle kind="LINEAFTER" colorName="#000000" start="0,0" stop="-1,-1"/> </blockTableStyle> """ if not warehouse.colo...
ockValign value="TOP"/> <blockTopPadding start="0,0" length="0.1cm"/> <lineStyle kind="LINEBEFORE" colorName="#000000" start="0,0" stop="-1,-1"/> <lineStyle kind="LINEBELOW" colorName="#000000" start="0,1" stop="0,1"/> <lineStyle kind="LINEABOVE" colorName="#000000" start="0,0" stop="0,0"/> ...
sinotradition/meridian
meridian/acupoints/yangfu23.py
Python
apache-2.0
242
0.033898
#!/usr/bin/python #coding=utf-8 ''' @aut
hor: sheng @license: ''' SPELL=u'yángfǔ' CN=u'阳辅' NAME=u'yangfu23' CHANNEL='gallbladder' CHANNEL_FULLNAME='GallbladderChannelofFoot-Shaoyang' SEQ='GB38' if __name__ == '__main_
_': pass
Revolution1/ID_generator
generator.py
Python
mit
1,559
0
def is_tl(data): return isinstance(data, tuple) or isinstance(data, list) def get_depth(data): ''' :type data: list or tuple get the depth of nested list 'x' is 0 ['x', 'y'] is 1 ['x', ['y', 'z'] is 2 ''' if is_tl(data): depths = [] for i in data:...
== data: result = _generate_d2(data) return result if __name__ == '__main__': nested = [range(2), [range(3), range(4)]] print(generate(nested)) print(generate([1, [2, 3]])) print(generate([1, 2])) print(generate(1))
python/pythondotorg
sponsors/models/managers.py
Python
apache-2.0
4,837
0.002067
from django.db.models import Count from ordered_model.models import OrderedModelManager from django.db.models import Q, Subquery from django.db.models.query import QuerySet from django.utils import timezone from polymorphic.query import PolymorphicQuerySet class SponsorshipQuerySet(QuerySet): def in_progress(self...
any([primary, administrative, accounting, manager]): return self.none() query = Q() if primary: query |= Q(primary=True) if administrative: query |= Q(administrative=True) if accounting: query |= Q(accounting=True) if manager: ...
: return self.exclude(conflicts__isnull=True) def without_conflicts(self): return self.filter(conflicts__isnull=True) def add_ons(self): return self.annotate(num_packages=Count("packages")).filter(num_packages=0, a_la_carte=False) def a_la_carte(self): return self.filter(a...
Azure/azure-sdk-for-python
sdk/containerservice/azure-mgmt-containerservice/azure/mgmt/containerservice/v2020_06_01/operations/_private_endpoint_connections_operations.py
Python
mit
21,872
0.004618
# coding=utf-8 # ------
-------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavio...
----------------- import functools from typing import Any, Callable, Dict, Generic, Optional, TypeVar, Union import warnings from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pipeline import PipelineResponse from azure....
mtrgroup/django-mtr-utils
tests/app/admin.py
Python
mit
908
0
from django.contrib import admin from modeltranslation.admin import TabbedTranslationAdmin from .models import Person, Office, Tag class PersonAdmin(TabbedTranslationAdmin): list_display = ('name', 'surname', 'security_level', 'gender') list_filter = ('security_level', 'tags', 'office', 'name', 'gender') ...
in): inlines = (PersonStackedInline,) list_display = ('office', 'address') class TagAdmin(admin.ModelAdmin): list_display = ('name',) admin.site.register(Person, PersonAdmin) admin.
site.register(Office, OfficeAdmin) admin.site.register(Tag, TagAdmin)
nwjs/chromium.src
tools/checkteamtags/owners_file_tags.py
Python
bsd-3-clause
7,900
0.010633
# Copyright (c) 2017 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os import posixpath import re from collections import defaultdict def uniform_path_format(native_path): """Alters the path if needed to be se...
iform_path_format(os.path.relpath(rel_dirname, root)) file_depth = 0 if rel_path == '.' else re
l_path.count(posixpath.sep) + 1 num_total += 1 num_total_by_depth[file_depth] += 1 component = owners_data.get('component') team = owners_data.get('team') os_tag = owners_data.get('os') if os_tag and component: component = '%s(%s)' % (component, os_tag) if team: dir_to_team[rel_d...
richrr/coremicro
src/core/process_data.py
Python
gpl-2.0
2,807
0
# Copyright 2016, 2017 Richard Rodrigues, Nyle Rodgers, Mark Williams, # Virginia Tech # # This file is part of Coremic. # # Coremic 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
ation, either version 3 of the License, or # (at your option) any later version. # # Coremic 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. #...
General Public License # along with Coremic. If not, see <http://www.gnu.org/licenses/>. from pval import getpval, correct_pvalues from otu import Otu def process(inputs, cfg): """Finds the core OTUs""" interest_ids = [otu for g in cfg['group'] for otu in inputs['mapping_dict'][g]] i_i...
huyphan/pyyawhois
test/record/parser/test_response_whois_tonic_to_status_available.py
Python
mit
2,350
0.007234
# This file is autogenerated. Do not edit it manually. # If you want change the content of this file, edit # # spec/fixtures/responses/whois.tonic.to/status_available # # and regenerate the tests with the following script # # $ scripts/generate_tests.py # from nose.tools import * from dateutil.parser import parse...
ef test_registered(self): eq_(self.record.registered, False) def test_created_on(self): assert_raises(yawhois.exceptions.AttributeNotSupported, self.record.created_on) def test_registrar(self): assert_raises(yawhois.exceptions.AttributeNotSupported, self.record.registrar) def test...
ts(self): assert_raises(yawhois.exceptions.AttributeNotSupported, self.record.technical_contacts) def test_updated_on(self): assert_raises(yawhois.exceptions.AttributeNotSupported, self.record.updated_on) def test_domain_id(self): assert_raises(yawhois.exceptions.AttributeNotSupported,...
projecthorus/chasetracker
ChaseTrackerNoGUI.py
Python
apache-2.0
6,363
0.006129
#!/usr/bin/env python # # ChaseTracker 2.0 No GUI Version # # Copyright 2015 Mark Jessop <vk5qi@rfhead.net> # # Licensed under the Apache License, Version 2.0 (the "License"); # you ma
y 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 COND...
missions and # limitations under the License. # import urllib2, json, ConfigParser, sys, time, serial from threading import Thread from base64 import b64encode from hashlib import sha256 from datetime import datetime from socket import * # Attempt to read in config file config = ConfigParser.RawConfigParser() config...
jmarcelogimenez/petroSym
petroSym/utils.py
Python
gpl-2.0
11,739
0.007837
# -*- coding: utf-8 -*- """ Created on Wed Aug 19 17:08:36 2015 @author: jgimenez """ from PyQt4 import QtGui, QtCore import os import time import subprocess types = {} types['p'] = 'scalar' types['U'] = 'vector' types['p_rgh'] = 'scalar' types['k'] = 'scalar' types['epsilon'] = 'scalar' types['omega'] = 'scalar' ty...
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Base, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Window, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.S
olidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Shadow, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.AlternateBase, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 220)) bru...
TriumphLLC/FashionProject
modules/operators/tools/detail_tool/detail_tool.py
Python
gpl-3.0
579
0.02403
import bpy from fashion_project.modules.draw.detail_tool.detail_tool import ToolDetail class FP_DetailTool(bpy.types.Operator):
''' Инструмент деталь: создает замкнутый контур ''' bl_idname = "fp.detail_tool" bl_label = "FP_DetailTool" @classmethod def poll(cls, context): return ToolDetail().poll(context) def execute(self, context): ToolDetail().create(context) return {'FINISHED'} def register(): bpy.utils.reg...
ils.unregister_class(FP_DetailTool)
rcbops/nova-buildpackage
nova/tests/rpc/test_carrot.py
Python
apache-2.0
1,534
0
# 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...
ot """ from nova import log as logging from nova.rpc import impl_carrot from nova.tests.rpc import common LOG = logging.getLogger('nova.tests.rpc')
class RpcCarrotTestCase(common._BaseRpcTestCase): def setUp(self): self.rpc = impl_carrot super(RpcCarrotTestCase, self).setUp() def tearDown(self): super(RpcCarrotTestCase, self).tearDown() def test_connectionpool_single(self): """Test that ConnectionPool recycles a sing...
beagles/neutron_hacking
neutron/tests/unit/linuxbridge/test_rpcapi.py
Python
apache-2.0
5,482
0
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012, Red Hat, 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 # ...
a
gent_id='fake_agent_id', host='fake_host') def test_update_device_up(self): rpcapi = agent_rpc.PluginApi(topics.PLUGIN) self._test_lb_api(rpcapi, topics.PLUGIN, 'update_device_up', rpc_method='call', fanout=False, ...
tcalmant/demo-ipopo-qt
android/compass/__init__.py
Python
gpl-2.0
439
0
#!/usr/bin/python # -- Content-Encoding: UTF-8 -- """ Compass demo package :author: Thomas Calmant :copyright: Copyright 2013, isandlaTech :license: GP
Lv2 :version: 0.1 :status: Alpha """ # Module version __version_info__ = (0, 1, 0) __version__ = ".".join(map(str, __version_info__)) # Documentation strings format __docformat__ = "restruc
turedtext en" # ------------------------------------------------------------------------------
ZloVechno/dummy-agent
functial/__init__.py
Python
gpl-3.0
621
0.030596
#! /usr/bin/python # Module: # Author: Maxim Borisyak, 2014 import functools partial = functools.partial from pattern import MatchError fr
om pattern import case from pattern import to_pattern # Type patterns from pattern import a_class from pattern import a_str from pattern import a_float from pattern import an_int # General patterns from pattern import some from pattern import otherwise from pattern import constant from match import match from matc
h import match_f from match import case_f from match import match_method from match import case_method from match import merge_matches from match import to_match
futurepr0n/Books-solutions
Python-For-Everyone-Horstmann/Chapter6-Lists/R6.1A.py
Python
mit
203
0.009852
# Given the list va
lues = [] , write code that fills the list with each set of numbers below. # a.1 2 3 4 5 6 7 8 9 10 list = [] for i in range(1
1): list.append(i) print(list)
peterFran/LanguageListCreator
langtools/translator/EPUBTranslation.py
Python
mit
1,136
0.001761
from ebooklib import epub from bs4 import BeautifulSoup from nltk.tokenize import RegexpTokenizer from langtools.translator.TextTranslation import TextTranslation class EPUB(object): """docstring for EPUB""" def __init__(self, book_location): book = epub.read_epub(book_location) # Filter out...
and return it xml_chapter = self.chapters[
number].get_content().decode('utf-8') chapter = BeautifulSoup(xml_chapter).get_text() # Tokenize the text tokenizer = RegexpTokenizer(r'\w+') return tokenizer.tokenize(chapter) class EPUBTranslation(EPUB): """docstring for EpubTranslation""" def get_chapter(self, number): ...
ErwinRieger/ddprint
host/ddtool.py
Python
gpl-2.0
2,998
0.004671
#!/usr/bin/python # -*- coding: utf-8 -*- #/* # This file is part of ddprint - a 3D printer firmware. # # Copyright 2020 erwin.rieger@ibrieger.de # # ddprint 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, e...
tokens = l.split() ti = 1 while ti < len(tokens): token = tokens[ti].lower() valtokens = token.split(",") if len(valtokens) >= 2: v = valtokens[1:]
while ti+1 < len(tokens): v.append(tokens[ti]) ti += 1 settings.__setattr__(valtokens[0].lower(), v) break if token == "generated": settings.generator = l break ...
sdague/home-assistant
tests/components/plex/helpers.py
Python
apache-2.0
248
0
"""Helper
methods for Plex tests.""" from plexwebsocket import SIGNAL_DATA def trigg
er_plex_update(mock_websocket): """Call the websocket callback method.""" callback = mock_websocket.call_args[0][1] callback(SIGNAL_DATA, None, None)
todddeluca/reciprocal_smallest_distance
rsd/rsd.py
Python
mit
32,578
0.005556
#!/usr/bin/env python2.7 ''' RSD: The reciprocal smallest distance algorithm. Wall, D.P., Fraser, H.B. and Hirsh, A.E. (2003) Detecting putative orthologs, Bioinformatics, 19, 1710-1711. Original author: Dennis P. Wall, Department of Biological Sciences, Stanford University. Contributors: I-Hsien Wu, Computational B...
file # def f
ormatForBlast(fastaPath): # os.chdir(os.path.dirname(fastaPath)) # cmd = 'formatdb -p -o -i'+os.path.basename(fastaPath) # cmd = 'formatdb -p -o -i'+fastaPath # redirect stdout to /dev/null to make the command quiter. cmd = ['makeblastdb', '-in', fastaPath, '-dbtype', 'prot', '-parse_seqids'] wi...
USC-ACTLab/pyCreate2
pyCreate2/visualization/__init__.py
Python
mit
59
0
from
.virtual_create import * __all__ = ["Virtua
lCreate"]
carzil/bowman
bowman/utils.py
Python
gpl-2.0
1,151
0.004344
# Copyright 2012 Andreev Alexander <carzil@yandex.ru> # # This software may be used and distributed according to the terms of the # GNU General Public License version 2 or any later version. import struct from .server.exceptions import Disconnect import math PACK_HEADER = ">l" # pack_size PACK_HEADER_SIZE = struct.ca...
et.recv(pack_size) data = data.decode("utf-8") return data def send_pack(self, data): if not isinstance(data, bytes): data = bytes(data, "utf-8") l = len(data) pack_size = struct.pack(PACK_HEADER, l) self.socket.send(pack_size) self.s...
y) ** 2 ) )
diogocs1/comps
web/openerp/report/common.py
Python
apache-2.0
3,337
0.013785
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the...
document:xmlns:dr3d:1.0}", "math":"{http://www.w3.org/1998/Math/MathML}", "form":"{urn:oasis:names:tc:opendocument:xmlns:form:1.0}", "script":"{urn:oasis:names:tc:opendocument:xmlns:script:1.0}", "ooo":"{http://openoffice.org/2004/office}", "ooow":"{http://openoffice.org/2004/
writer}", "oooc":"{http://openoffice.org/2004/calc}", "dom":"{http://www.w3.org/2001/xml-events}" } sxw_namespace = { "office":"{http://openoffice.org/2000/office}", "style":"{http://openoffice.org/2000/style}", "text":"{http://openoffice.org/2000/text}", "table":"{http://openoffice.org/2000/ta...
reuk/wayverb
.ycm_extra_conf.py
Python
gpl-2.0
5,675
0.021498
# This file is NOT licensed under the GPLv3, which is the license for the rest # of YouCompleteMe. # # Here's the license text for this file: # # This is free and unencumbered software released into the public domain. # # Anyone is free to copy, modify, publish, use, compile, sell, or # distribute this software, either...
lude', '-Isrc/frequency_domain/include', '-Isrc/waveguide/compensation_signal/lib/include', '-Isrc/raytracer/include', '-Isrc/core/include', '-Isrc/
hrtf/lib/include', '-Isrc/combined/include', '-Ibin/box/include', '-Ibuild/include', '-Ibuild/dependencies/include', '-Ibuild/src/core', '-Ibuild/src/waveguide', '-Iwayverb/Source', '-Iwayverb/JuceLibraryCode/modules', ] # Set this to the absolute path to the folder (NOT the file!) containing the # compile_commands.j...
eviljeff/olympia
src/olympia/activity/tests/test_serializers.py
Python
bsd-3-clause
4,454
0
# -*- coding: utf-8 -*- from rest_framework.test import APIRequestFactory from olympia import amo from olympia.activity.models import ActivityLog from olympia.activity.serializers import ActivityLogSerializer from olympia.amo.tests import TestCase, addon_factory, user_factory class LogMixin(object): def log(self...
d text rather than the actual content. assert result['comments'] == amo.LOG.REQUEST_ADMIN_REVIEW_CODE.sanitize assert result['comments'].startswith( 'The addon has been flagged for Admin Review.') def test_log_entry_without_details(self): # Create a log but without a details pro...
_NOTES_CHANGED, self.addon, self.addon.find_latest_version(channel=amo.RELEASE_CHANNEL_LISTED), user=self.user) result = self.serialize() # Should output an empty string. assert result['comments'] == ''
mganeva/mantid
scripts/PyChop/PyChop2.py
Python
gpl-3.0
10,393
0.003464
# Mantid Repository : https://github.com/mantidproject/mantid # # Copyright &copy; 2018 ISIS Rutherford Appleton Laboratory UKRI, # NScD Oak Ridge National Laboratory, European Spallation Source # & Institut Laue - Langevin # SPDX
- License - Identifier: GPL - 3.0 + # pylint: disable=line-too-long, invalid-name, old-style-class, multiple-statements, too-many-branches """ This module contains the PyChop2 class which allows calculation of the resolution and flux of direct geometry time-of-flight inela
stic neutron spectrometers. """ from __future__ import (absolute_import, division, print_function) from .ISISFermi import ISISFermi from .ISISDisk import ISISDisk import warnings class PyChop2: """ PyChop2 is a class to calculate the energy resolution of direct geometry time-of-flight spectrometers based...
opencord/voltha
voltha/northbound/rpc_dispatcher.py
Python
apache-2.0
803
0
# # Copyright 2017 the original author or 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 # # Unles
s 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. # """ RPC ...
work in progress
MiniSEC/GRR_clone
lib/registry.py
Python
apache-2.0
5,555
0.009541
#!/usr/bin/env python """This is the GRR class registry. A central place responsible for registring plugins. Any class can have plugins if it defines __metaclass__ = MetaclassRegistry. Any derived class from this baseclass will have the member classes as a dict containing class name by key and class as value. """ #...
# defined - We ensure we only run each hook only once. last_run_hooks = len(executed_hooks) self._RunAllHooks(executed_hooks) if last_run_hooks == len(executed_hooks): break except StopIteration: logging.debug("Recalculating Hoo
k dependency.") def RunOnce(self): """Hooks which only want to be run once.""" def Run(self): """Hooks that can be called more than once.""" class InitHook(HookRegistry): """Global GRR init registry. Any classes which extend this class will be instantiated exactly once when the system is initiali...
dartsim/dart
python/tests/unit/dynamics/test_inverse_kinematics.py
Python
bsd-2-clause
2,669
0.000749
import plat
form import pytest import math import nump
y as np import dartpy as dart def test_solve_for_free_joint(): ''' Very simple test of InverseKinematics module, applied to a FreeJoint to ensure that the target is reachable ''' skel = dart.dynamics.Skeleton() [joint0, body0] = skel.createFreeJointAndBodyNodePair() ik = body0.getOrCreat...
antonow/concept-to-clinic
interface/backend/cases/apps.py
Python
mit
85
0
from djan
go.apps import AppConfig class CasesConfig
(AppConfig): name = 'cases'
destijl/grr
grr/gui/plugins/flow_management_test.py
Python
apache-2.0
14,194
0.003382
#!/usr/bin/env python """Test the flow_management interface.""" import os from grr.gui import gui_test_lib from grr.gui import runtests_test from grr.lib import action_mocks from grr.lib import aff4 from grr.lib import flags from grr.lib import flow from grr.lib import hunts from grr.lib import test_lib from grr.l...
with hunts.GRRHunt.StartHunt( hunt_name=standard.GenericHunt.__name__, flow_runner_args=rdf_flows.FlowRunnerArgs( flow_name=gui_test_lib.RecursiveTestFlow.__name__), client_rate=0, token=self.token) as hunt: hunt.Run() self.AssignTasksToClients...
lient.flows']") # There should be a RecursiveTestFlow in the list. Expand nested flows. self.Click("css=tr:contains('RecursiveTestFlow') span.tree_branch") # Click on a nested flow. self.Click("css=tr:contains('RecursiveTestFlow'):nth(2)") # Nested flow should have Depth argument set to 1. sel...
chenqi123/ipaas
example/views.py
Python
apache-2.0
6,131
0.047953
from django.shortcuts import render # Create your views here. def proindex(request): return render(request, 'example/probase.html' ) def index(request): return render(request, 'e_index.html' ) def badges_labels(request): return render(request, 'badges_labels.html' ) def four(requ...
uest): return render(request, 'layouts.html' ) def lockscreen(request): return render(request, 'lockscreen.html' ) def login(request): return render(request, 'login.html' ) def mailbox(request): return render(request, 'mailbox.html'
) def mail_compose(request): return render(request, 'mail_compose.html' ) def mail_detail(request): return render(request, 'mail_detail.html' ) def modal_window(request): return render(request, 'modal_window.html' ) def nestable_list(request): return render(request,...
splotz90/urh
src/urh/ui/urh_rc.py
Python
gpl-3.0
463,208
0.000011
# -*- coding: utf-8 -*- # Resource object code # # Created by: The Resource Compiler for PyQt5 (Qt v5.9.2) # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore qt_resource_data = b"\ \x00\x00\x07\x27\ \x00\ \x00\x1a\x8b\x78\x9c\xe5\x58\xdd\x8f\xdb\x36\x12\x7f\xdf\xbf\x82\ \x55\x1f\xd2\x4...
\xdd\xa0\x2c\x1f\ \x98\xc2\xe5\x6e\x10\xc9\x73\xe9\x47\x9c\x6b\xce\x0a\x28\x30\x89\ \xec\xe4\x50\xde\xe3\x23\x38\x14\x3e\xe1\x84\x02\x8f\x44\x38\x08\ \x89\x1b\xc8\xef\x06\x0e\x9d\x12\x81\x78\x6c\xf6\x60\x2a\x95\xaa\ \xb8\xaa\xa2\xaa\x85\x6a\x01\x8a\x03\x75\x8a\xa4\x82\xcf\x55\x2d\ \x35\x59\xa9\xd5\x3c\x37\x82\x68\xe4\x...
b8\ \xcf\x2f\xe1\x94\x6b\x34\xf5\x2e\xc1\xd4\xbb\x81\xa5\xfc\x0a\x94\ \x7a\xd7\x90\xd4\x04\xd2\x2b\x30\xfa\x35\x10\xe5\x97\x10\x7a\x1b\ \x40\x4d\xfc\xbc\x80\xcf\x6f\x43\xcf\x4b\xf0\x34\x3e\x04\xf8\x1c\ \x3a\xf9\xb7\x20\x27\xbf\x01\x9c\x9e\xc6\x4d\x7e\x09\x9b\xfc\xab\ \xa8\x79\x05\x34\xf9\x35\xcc\x34\x21\xf3\x0a\x62\x3e...
MatthewWilkes/mw4068-packaging
src/melange/src/soc/logic/models/role.py
Python
apache-2.0
4,706
0.006587
#!/usr/bin/env python2.5 # # Copyright 2008 the Melange 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 applic...
ith all Role Logics to notify """ return [] def getSuggestedInitialProperties(self, user): """Suggest role properties for a given user based on its previous entries. Args: user: a user entity Returns: A dict with values for fields defined in SUGGESTED_FIELDS or an empty dicti...
""" filter = { 'status': ['active', 'inactive'], 'user': user, } role = None for role_logic in ROLE_LOGICS.values(): role = role_logic.getForFields(filter, unique=True) if role: break if not role: return {} return dict([(field, getattr(role, fiel...
Jumpscale/jumpscale_portal8
apps/portalbase/macros/page/email/1_main.py
Python
apache-2.0
436
0.002294
from JumpScale.portal.macrolib import div_base def main(j, args, params, *other_args): return div_base.macro(j, args,
params, self_closing=True, tag='input', additional_tag_params={'type': 'email', 'pattern': r"^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)+$"}) def match(j, args, params, tags, tasklet): return
True
netrack/python-netrackclient
netrackclient/client.py
Python
lgpl-3.0
2,454
0
import sys import json import importlib import http.client import traceback from netrackclient import broker from netrackclient import errors class HTTPClient(object): def __init__(self, *args, **kwargs): super(HTTPClient, self).__init__() self._broker = broker.RequestBroker() self.serv...
def put(self, uri, body, **kwargs): request = self._request() url = self.service_url + uri body = json.dumps(body)
response = request.put(url, body, **kwargs) if response.status() != http.client.OK: raise errors.BaseError(response.body()) return response def delete(self, uri, body, **kwargs): request = self._request() url = self.service_url + uri body = json.dumps(body) ...
mcflugen/wmt-rest
wmt/flask/components/__init__.py
Python
mit
155
0.006452
from flask import current_app from ..core import Service, db from .models import Component class ComponentsService(Service):
__model__ = Compo
nent
DarthStrom/python_koans
python2/koans/about_dictionaries.py
Python
mit
1,970
0
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Based on AboutHashes in the Ruby Koans # from runner.koan import * class AboutDictionaries(Koan): def test_creating_dictionaries(self): empty_dict = dict() self.assertEqual(dict, type(empty_dict)) self.assertEqual(dict(), empty_dict) ...
ish['
one'] = 'eins' expected = {'two': 'dos', 'one': __} self.assertEqual(expected, babel_fish) def test_dictionary_is_unordered(self): dict1 = {'one': 'uno', 'two': 'dos'} dict2 = {'two': 'dos', 'one': 'uno'} self.assertEqual(____, dict1 == dict2) def test_dictionary_keys...
gkc1000/pyscf
pyscf/tddft/__init__.py
Python
apache-2.0
660
0
#!
/usr/bin/env python # Copyright 2014-2018 The PySCF Developers. 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 # # Unl...
uted 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. from pyscf.tdscf import *
nickstenning/honcho
tests/test_manager.py
Python
mit
8,625
0.000116
import datetime import queue import multiprocessing import pytest from honcho.printer import Message from honcho.manager import Manager from honcho.manager import SYSTEM_PRINTER_NAME HISTORIES = { 'one': { 'processes': {'foo': {}}, 'messages': (('foo', 'start', {'pid': 123}), ...
rocess_name, colour=None)) def fetch_events(self): """ Retrieve any pending events from the queue and put them on the local event cache """ while 1: try: self.events_local.append(self._q.get(False)) ...
xcept queue.Empty: break def find_events(self, name=None, type=None): self.fetch_events() results = [] for event in self.events_local: if name is not None and event['name'] != name: continue if type is not None and event['type'] != typ...
jhunkeler/hstcal
tests/wfc3/test_uvis_13single.py
Python
bsd-3-clause
864
0.003472
import subprocess import pytest from ..helpers import BaseWFC3 class TestUVIS13Single(BaseWFC3): """ Test pos UVIS2 DARK images """ detector = 'uvis' def _single_raw_calib(self, rootname): raw_file = '{}_raw.fits'.format(rootname) # Prepare input file. self.get_inpu...
# 'rootname', ['iaao09l2q', 'iaao09l3q', 'iaa
o11ofq', 'iaao11ogq', 'iblk57c1q']) def test_uvis_13single(self, rootname): self._single_raw_calib(rootname)
Kentoseth/rangoapp
tango_with_django_project/rango/forms.py
Python
mit
1,390
0.035971
from django import forms from rango.models import Page, Category from rango.models import UserProfile from
django.contrib.auth.models import User class CategoryForm(forms.ModelForm): name = forms.CharField(max_length=128, help_text="Please enter the category name.") views = forms.IntegerField(widget=forms.HiddenInput(), initial=0) likes = forms.IntegerField(widget=forms.HiddenInput(), initial=0) class Meta: # Provi...
arField(max_length=128, help_text="Please enter title of the page") url = forms.URLField(max_length=200, help_text="Please enter URL of the page") views = forms.IntegerField(widget=forms.HiddenInput(), initial=0) class Meta: # Provide an association between the ModelForm and a model model = Page fields = ...
gitgitcode/myflask
maomew/__init__.py
Python
mit
219
0.004566
# !/bin/env/ python from flask import Flask app
= Flask(__name__, instance_relative_config=True) app.config.from_object('config.default') app.config.from_pyfile('config.py'
) #app.config.from_envvar('APP_CONFIG_FILE')
mamchecker/mamchecker
mamchecker/done/__init__.py
Python
gpl-3.0
3,545
0.001975
# -*- coding: utf-8 -*- import re import datetime import logging from urlparse import parse_qsl from mamchecker.model import depth_1st, problemCtxObjs, keysOmit, table_entry, ctxkey from mamchecker.hlp import datefmt, last from mamchecker.util import PageBase from google.appengine.ext import ndb def prepare( ...
ext(iter(x.split(','))) le = le.replace('~', '=') match = re.match(r'(\w+)([=!<>]+)([\w\d\.]+)', le) if match: grps = match.groups() name, op, value = grps if name in ABBR: name = ABBR[name] age = Non...
name if age: value = datetime.datetime.now( ) - datetime.timedelta(**{age: int(value)}) name = 'answered' filters.append((name, op, value)) return filters #qs = '' O = problemCtxObjs # q=query, qq=*->[], qqf...
ColOfAbRiX/ansible
lib/ansible/modules/cloud/docker/docker_image.py
Python
gpl-3.0
21,614
0.003007
#!/usr/bin/python # # Copyright 2016 Red Hat | Ansible # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any la...
ption: - Used to select an image when pulling. Will be added to the image when pushing, tagging or building. Defaults to I(latest). - If C(
name) parameter format is I(name:tag), then tag value from C(name) will take precedence. default: latest required: false buildargs: description: - Provide a dictionary of C(key:value) build arguments that map to Dockerfile ARG directive. - Docker expects the value to be a string. For convenien...
openstack/tacker
tacker/common/constants.py
Python
apache-2.0
813
0
# Copyright (c) 2012 OpenStack Foundation. # # 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...
nse.
# TODO(salv-orlando): Verify if a single set of operational # status constants is achievable MAX_VLAN_TAG = 4094 MIN_VLAN_TAG = 1 PAGINATION_INFINITE = 'infinite' SORT_DIRECTION_ASC = 'asc' SORT_DIRECTION_DESC = 'desc'
tykling/tykurllog
src/tykurllog/admin.py
Python
bsd-3-clause
204
0.009804
from django.contrib import admin from django.apps import apps ### register all models in this app in the admin for model in apps.get_app_config('ty
kurllog').get_models(): admin.site.regist
er(model)
prmtl/fuel-web
nailgun/nailgun/test/unit/test_objects.py
Python
apache-2.0
27,637
0
# -*- coding: utf-8 -*- # Copyright 2014 Mirantis, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requi...
{'roles': ['controller', 'cinder'], 'pending_addition': True}, {'roles': ['compute', 'cinder'], 'pending_addition': True}, {'roles
': ['compute'], 'pending_addition': True}, {'roles': ['mongo'], 'pending_addition': True}, {'roles': [], 'pending_roles': ['cinder'], 'pending_addition': True}, {'roles': [], 'pending_roles': ['controller'], 'pending_addition': True}] self.env.create...
jocke-l/blues
blues/redis.py
Python
mit
1,054
0.000949
""" Redis Blueprint =============== **
Fabric environment:** .. code-block:: yaml blueprints: - blues.redis settings: redis: # bind: 0.0.0.0 # Set the bind address specifically (Default: 127.0.0.1) """ from fabric.decorators import task from refabric.context_managers import sudo from refabric.contrib import blueprints from...
'configure'] blueprint = blueprints.get(__name__) start = debian.service_task('redis-server', 'start') stop = debian.service_task('redis-server', 'stop') restart = debian.service_task('redis-server', 'restart') @task def setup(): """ Install and configure Redis """ install() configure() def i...
youtube/cobalt
third_party/blink/Source/bindings/scripts/compute_interfaces_info_individual.py
Python
bsd-3-clause
17,799
0.002472
#!/usr/bin/python # # Copyright (C) 2013 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of...
ry of idl_file in POSIX format.""" relative_path_local = os.path.relpath(idl_filename, base_path) relative_dir_local = os.path.dirname(relative_path_local) return relative_dir_local.replace(os.path.sep, posixpath.sep) def include_path(idl_filename, root_path, implemented_as=None): """Returns relative ...
used in includes. POSIX format is used for consistency of output, so reference tests are platform-independent. """ relative_dir = relative_dir_posix(idl_filename, root_path) # IDL file basename is used even if only a partial interface file cpp_class_name = implemented_as or idl_filename_to_int...
ricklupton/sankeyview
floweaver/sankey_definition.py
Python
mit
9,779
0.001636
from textwrap import dedent from pprint import pformat from collections import OrderedDict import attr from . import sentinel from .ordering import Ordering # adapted from https://stackoverflow.com/a/47663099/1615465 def no_default_vals_in_repr(cls): """Class decorator on top of attr.s that omits attributes from...
nodes: raise ValueError('Unknown waypoint "{}" in bundle {}'.format( u, k)) if not isinstance(instance.nodes[u], Waypoint): raise ValueError( 'Waypoint "{}" of bundle {} is not a waypoint'.forma
t(u, k)) def _validate_ordering(instance, attribute, ordering): for layer_bands in ordering.layers: for band_nodes in layer_bands: for u in band_nodes: if u not in instance.nodes: rais...
balazsdukai/batch3dfier
batch3dfier/config.py
Python
gpl-3.0
20,894
0.000814
# -*- coding: utf-8 -*- """Configure batch3dfier with the input data.""" import os.path from subprocess import call from shapely.geometry import shape from shapely import geos from psycopg2 import sql import fiona def call_3dfier(db, tile, schema_tiles, pc_file_name, pc_tile_case, pc_dir, ...
ntcloud files. See 'dataset_dir' in batch3dfier_config.yml. thread : str Name/ID of the active thread. extent_ewkb : str EWKB representation of
'extent' in batch3dfier_config.yml. clip_prefix : str Prefix for naming the clipped/united views. This value shouldn't be a substring of the pointcloud file names. prefix_tile_footprint : str or None Prefix prepended to the footprint tile view names. If None, the views are named as the v...
MTG/essentia
test/src/unittests/highlevel/test_coversongsimilarity.py
Python
agpl-3.0
3,115
0.004815
#!/usr/bin/env python # Copyright (C) 2006-2017 Music Technology Group - Universitat Pompeu Fabra # # This file is part of Essentia # # Essentia 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 (FSF), e...
coversim_streaming.distance >> (pool, 'distance') # run th
e algorithm network run(matrix_input) self.assertAlmostEqualFixedPrecision(self.expected_distance, pool['distance'][-1]) suite = allTests(TestCoverSongSimilarity) if __name__ == '__main__': TextTestRunner(verbosity=2).run(suite)
jtian0/project-platform
conduct.py
Python
mit
5,372
0.001303
#!/usr/bin/env python3 from thesis import Submit import time import logging import signal import threading import boto.ec2 import multiprocessing as mp import subprocess as sp from pprint import pprint from thesis import Propagator from thesis import Pattern from thesis import Parser from thesis import Console __au...
conn': conn, 'opts': opts, 'graph_gen': True, 'data_exportable': True} d = mp.Process(target=dispatcher, kwargs=kwargs) else: kwargs = {'task_id': task_id, 'conn': conn, 'opts': opts, 'graph_gen': True, 'data_exportable': True, 'no_avail_pattern'...
data_exportable=True) elapsed = time.time() - start logging.info('Submission #%s finished, p%s_i%s, taking %.6f seconds' % (task_id, opts.partition, opts.iteration, elapsed)) def main(): conn = boto.ec2.connect_to_region("us-east-1") opts, _action = Parser.experiment_parse_args() ...
nottimbergling/isREAL-ui
backend/entities/base_request.py
Python
mit
292
0.010274
class BaseRequest(ob
ject): def __init__(self, raw_request_dict): self.body = raw_request_dict if not self.body: self.body ={} def validate_scheme(self, scheme): scheme.vali
date(self.body) def get_value(self,key): return self.body[key]
Undeterminant/archlinux-metapkg
run_tests.py
Python
cc0-1.0
5,479
0.000183
from click.testing import CliRunner from contextlib import contextmanager from metapkg import main as metapkg_main from unittest import TestCase, main import os import metapkg as mp class TestBuilds(TestCase): def setUp(self): self.maxDiff = None def assertValidPKGBUILD(self, directory): meta...
Case): def setUp(self): self.maxDiff = None @contextmanager def runCLI(self, args=[], input=None, mb=None, pb=None): runner = CliRunner() with runner.isolated_filesystem(): if mb: with open('METABUILD', 'w') as f: print(mb, file=f) ...
f pb: with open('PKGBUILD', 'w') as f: print(pb, file=f) yield runner.invoke(metapkg_main, args, input) def assertGeneratedPKGBUILD(self, metabuild): with open('PKGBUILD') as f: self.assertEqual(f.read(), mp.quick_metapkg(metabuild)) def asse...
dpausp/arguments
src/ekklesia_portal/lib/vvvote/election_config.py
Python
agpl-3.0
2,273
0.00264
import datetime from uuid import uuid4 import ekklesia_portal.li
b.vvvote.schema as vvvote_schema def ballot_to_vvvote_question(ballot, question_id=1): options = [] voting_scheme_yes_no = vvvote_schema.YesNoScheme( name='yesNo', abstention=True, abstentionAsNo=False, quorum=2, mod
e=vvvote_schema.SchemeMode.QUORUM ) voting_scheme_score = vvvote_schema.ScoreScheme(name='score', minScore=0, maxScore=3) voting_scheme = [voting_scheme_yes_no, voting_scheme_score] for option_id, proposition in enumerate(ballot.propositions, start=1): proponents = [s.name for s in propositio...
Choko256/pysfmlengine
util.py
Python
gpl-3.0
528
0.035985
#-*- coding:utf-8 -*- class EventThrower: de
f __init__(self): self.events = {} def on(self, name, callback, priority=99): if name in self.events: self.events[name].append({ 'fct': callback, 'priority': priority }) self.events[name] = sorted(self.events[name], key=lambda x: x['priority'], reverse=True) def off(self, name): if name in s...
](self, **kwargs)
tommybobbins/velpi
utilities/redis_sensor.py
Python
gpl-2.0
2,563
0.017948
#!/usr/bin/python # Modified 30-Oct-2013 # tng@chegwin.org # Retrieve: # 1: current temperature from a TMP102 sensor # 2: Send to redis import sys,time from sys import path import datetime from time import sleep import re import redis time_to_live = 3600 ###### IMPORTANT ############# ###### How close to comfortable ...
s Tmp102: i2c = None # Constructor def __init__(self, address=0x48, mode=1, debug=False): self.i2c = Adafruit_I2C(address, debug=debug) self.address = address self.debug = debug # Make sure the specified mode is in the appropriate range if ((mode < 0) | (mode > 3)): if (self.debug): ...
ode = self.__BMP085_STANDARD else: self.mode = mode def readRawTemp(self): "Reads the raw (uncompensated) temperature from the sensor" self.i2c.write8(0, 0x00) # Set temp reading mode raw = self.i2c.readList(0,2) val = raw[0] << 4; val |= raw[1] >> 4; return val ...
bnookala/fsm
example.py
Python
mit
448
0.015625
#/usr/bin
/env python from fsm import Machine states = ["q1", "q2", "q3"] alphabet = ["0","1"] transitions = { "q1": {"0": "q1", "1": "q2"}, "q2": {"0": "q3", "1": "q2"}, "q3": {"0": "q2", "1": "q2"}, } start = "q1" end = ["q2"] machine = Machine.from_arguments(states, alphabet, transitions, start, end) machine...
run(123) # fail machine.run("") # fail machine.run("1") # pass machine.run("11") # pass machine.run("0100101") # pass
polymorphm/scgi-wsgi-daemon
lib_scgi_wsgi_daemon__2011_08_06/daemonize.py
Python
gpl-3.0
1,222
0.003273
# -*- mode: python; coding: utf-8 -*- # # Copyright 2011 Andrej A Antonov <polymorphm@qmail.com> # # This program is free software:
you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at
your option) any later version. # # 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 Lesser General Public License for more details. # # You should have received a copy ...
rousseab/pymatgen
pymatgen/io/vaspio/vasp_output.py
Python
mit
539
0.003711
# coding: utf-8 #!/usr/bin/env python from __future__ import div
ision, unicode_literals """ #TODO: Write module doc. """ __author__ = 'Shyue Ping Ong' __copyright__ = 'Copyright 2013, The Materials Virtual Lab' __version__ = '0.1' __maintainer__ = 'Shyue Ping Ong' __email_
_ = 'ongsp@ucsd.edu' __date__ = '8/1/15' import warnings warnings.warn("pymatgen.io.vaspio.vasp_output has been moved " "pymatgen.io.vasp.outputs " "This stub will be removed in pymatgen 4.0.") from pymatgen.io.vasp.outputs import *
rspavel/spack
lib/spack/spack/cmd/dev_build.py
Python
lgpl-2.1
3,928
0
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) import sys import os import llnl.util.tty as tty import spack.config import spack.cmd import spack.cmd.common.arguments ...
(spec.name): tty.die("No package for '{0}' was found.".format(spec.name), " Use `spack create` to create a new package") if not spec.versions.concrete: tty.die( "spack dev-build spec must have a single, concrete version. " "Did you forget a package version n...
r try adding a version suffix for this dev build.") sys.exit(1) source_path = args.source_path if source_path is None: source_path = os.getcwd() source_path = os.path.abspath(source_path) # Forces the build to run out of the current directory. package.stage = DIYStage(source_path) ...
jharris2268/osmquadtreeutils
osmquadtreeutils/rendertiles.py
Python
gpl-3.0
3,227
0.047412
import mapnik import subprocess,PIL.Image,cStringIO as StringIO import time,sys,os ew = 20037508.3428 tz = 8 def make_mapnik(fn, tabpp = None, scale=None, srs=None, mp=None, avoidEdges=False, abspath=True): cc=[l for l in subprocess.check_output(['carto',fn]).split("\n") if not l.startswith('[mills...
if avoidEdges: for i,c in enumerate(cc): if '<ShieldSymbolizer size' in c: cs = c.replace("ShieldSymbolizer size", "ShieldSymbolizer avo
id-edges=\"true\" size") cc[i]=cs if tabpp != None: cc=[l.replace("planet_osm",tabpp) for l in cc] #cc2=[c.replace("clip=\"false","clip=\"true") for c in cc] #cc3=[c.replace("file=\"symbols", "file=\""+root+"/symbols") for c in cc2] #cc4=[c.r...
fbradyirl/home-assistant
homeassistant/components/simplisafe/const.py
Python
apache-2.0
203
0
"""Define constants for the SimpliSafe component.""" from datetime import timedelta DOMAIN = "simplisafe" DATA_CLIENT = "client" DEFAULT_SCAN_INTERVAL =
timedelta(seconds=30) TOPIC_UPDATE = "u
pdate"
JeffHoogland/mtg-totals
Qt/ui_mainWindow.py
Python
bsd-3-clause
13,255
0.001283
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'mainWindow.ui' # # Created: Fri Sep 25 14:24:01 2015 # by: pyside-uic 0.2.15 running on PySide 1.2.1 # # WARNING! All changes made in this file will be lost! from PySide import QtCore, QtGui class Ui_mainWindow(object): def setupU...
) self.p1Deck.setObjectName("p1Deck") self.verticalLayout_3.addWidget(self.p1Deck) self.verticalLayout_7.addWidget(self.frame_4) self.frame_14 = QtGui.QFrame(self.frame_2) self.frame_14.setFrameShape(QtGui.QFrame.StyledPanel) self.frame_14.setFrameShadow(QtGui.QFrame.Rais...
elf.verticalLayout_8.setObjectName("verticalLayout_8") self.label_11 = QtGui.QLabel(self.frame_14) self.label_11.setObjectName("label_11") self.verticalLayout_8.addWidget(self.label_11) self.p1Life = QtGui.QSpinBox(self.frame_14) self.p1Life.setMaximum(10000) self.p1Life....
unnikrishnankgs/va
venv/lib/python3.5/site-packages/nbconvert/tests/base.py
Python
bsd-2-clause
5,773
0.003811
"""Base test class for nbconvert""" # Copyright (c) IPython Development Team. # Distributed under the terms of the Modified BSD License. import io import os import glob import shlex import shutil import sys import unittest import nbconvert from subprocess import Popen, PIPE import nose.tools as nt from nbformat imp...
nce(parameters, string_types): parameters = shlex.split(parameters) cmd = [sys.executable, '-m', 'nbconvert'] + parameters p = Popen(cmd, stdout=PIPE, stderr=PIPE, stdin=PIPE) stdout, stderr = p.communicate(i
nput=stdin) if not (p.returncode == 0 or ignore_return_code): raise OSError(bytes_to_str(stderr)) return stdout.decode('utf8', 'replace'), stderr.decode('utf8', 'replace') def assert_big_text_equal(a, b, chunk_size=80): """assert that large strings are equal Zooms in on first chun...
nhuntwalker/astroML
astroML/stats/random.py
Python
bsd-2-clause
3,890
0.000771
""" Statistics for astronomy """ import numpy as np from scipy.stats.distributions import rv_continuous def bivariate_normal(mu=[0, 0], sigma_1=1, sigma_2=1, alpha=0, size=None, return_cov=False): """Sample points from a 2D normal distribution Parameters ---------- mu : array-lik...
d = 1. / (b - a) - 0.5 * c * (b + a) pdf = c * x + d pdf[(x < a) | (x > b)] = 0 return pdf def _rvs(self, a, b, c): mu = 0.5 * (a + b) W = (b - a) x0 = 1. / c / W - mu r = np.random.random(self._size) return -x0 + np.sqrt(2. * r / c + a * a ...
+ 2. * a * x0 + x0 * x0) linear = linear_gen(name="linear", shapes='a, b, c')
ksmit799/Toontown-Source
toontown/minigame/RaceGameGlobals.py
Python
mit
1,615
0.003096
from toontown.toonbase import TTLocalizer ValidChoices = [0, 1, 2, 3, 4] NumberToWin = 14 InputTimeout = 20 ChanceRewards = (((1, 0), TTLocalizer.RaceGameForwardOneSpace, 0), ((1, 0), TTLocalizer.RaceGameForwardOneSpace, 0), ((1, 0), TTLocalizer.RaceGameForwardOneSpace, 0), ((2, 0), TTLocalizer.RaceGameForwardTw...
lybeans4, 4), ((0, 0), TTLocalizer.RaceGameJellybeans4, 4), ((0, 0), TTLocalizer.RaceGameJellybeans4, 4), ((0, 0), TTLocalizer.RaceGameJellybeans10, 10), ((0, 0), -1, 0), ((N
umberToWin, 0), TTLocalizer.RaceGameInstantWinner, 0))
Diti24/python-ivi
ivi/tektronix/tektronixMDO3012.py
Python
mit
1,724
0.00116
""" Python Interchangeable Virtual Instrument Library Copyright (c) 2016 Alex Forencich Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the righ...
LL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from .tektronixMDO3000 import * class tektronixMDO3012(tektronixMDO30...
self.__dict__.setdefault('_instrument_id', 'MDO3012') super(tektronixMDO3012, self).__init__(*args, **kwargs) self._analog_channel_count = 2 self._digital_channel_count = 16 self._channel_count = self._analog_channel_count + self._digital_channel_count self._bandwidth = 100e6 ...
fcurella/django-settings_inspector
settings_inspector/gui/windows/variables.py
Python
mit
1,500
0.000667
from .base import ScrollWindow from settings_inspector.gui import keys class VariablesWindow(ScrollWindow): def __init__(self, settings, *args, **kwargs): super(VariablesWindow, self).__init__(*args, **
kwargs) self.root_settings = settings self.reset() self.render() return self def reset(self): self.settings = {} self.current_line = 0 self.current_column = 0 self.add_variables() self.refresh() def add_variables(self): for name, ...
h(self, cmd): if cmd == keys.LOWERCASE_S: self.parent_ui.show_settings() else: super(VariablesWindow, self).on_ch(cmd) class VariableHistoryWindow(ScrollWindow): def __init__(self, settings, variable, *args, **kwargs): super(VariableHistoryWindow, self).__init__(*ar...
jmluy/xpython
exercises/concept/log-levels/.meta/exemplar.py
Python
mit
1,610
0.001242
from enum import Enum class LogLevel(Enum): """Represent different log levels by their verbose codes.""" TRACE = 'TRC' DEBUG = 'DBG' INFO = 'INF' WARNING = 'WRN' WARN = 'WRN' ERROR = 'ERR' FATAL = 'FTL' UNKNOWN = 'UKN' class LogLevelInt(Enum): """Represent different log leve...
OR = 6 FATAL = 7 UNKNOWN = 42 def parse_log_level(message): """Return level enum for log message. :param message: log message (string) :return: enum - 'LogLevel.<level>'. Return 'LogLevel.Unknown' if an unknown severity is passed. """ str_split = message.split(':') lvl = str_spli...
"""Convert a log message to its shorter format. :param log_level: enum - 'LogLevel.<level>' e.g. 'LogLevel.Error' :param message: str - log message :return: enum - 'LogLevelInt.<value>` e.g. 'LogLevelInt.5' """ return f'{LogLevelInt[log_level.name].value}:{message}' def get_warn_alias(): ...
eharney/nova
nova/tests/api/openstack/compute/plugins/v3/test_multinic.py
Python
apache-2.0
5,154
0
# Copyright 2011 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requ...
def test_add_fixed_ip_network_id_bigger_than_36(self): body = {'add_fixed_ip': {'network_id': 'a' * 37}} req = webob.Request.blank('/v3/servers/%s/action' % UUID) req.method = 'POST' req.body = jsonutils.dumps(body) req.headers['content-type'] = 'application/json' re...
(self): global last_add_fixed_ip last_add_fixed_ip = (None, None) body = dict(add_fixed_ip=dict()) req = webob.Request.blank('/v3/servers/%s/action' % UUID) req.method = 'POST' req.body = jsonutils.dumps(body) req.headers['content-type'] = 'application/json' ...
rickerc/ceilometer_audit
ceilometer/publisher/file.py
Python
apache-2.0
3,579
0
# -*- encoding: utf-8 -*- # # Copyright 2013 IBM Corp # # Author: Tong Li <litong01@us.ibm.com> # # 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...
path for the file publisher is required') return rfh = None max_bytes = 0 backup_count = 0 # Handling other configuration options in the query string if parsed_url.query: params = urlparse.parse_qs(parsed_url.query) if params.get('max_bytes') ...
= int(params.get('backup_count')[0]) except ValueError: LOG.error('max_bytes and backup_count should be ' 'numbers.') return # create rotating file handler rfh = logging.handlers.RotatingFileHandler( path, ...
stiphyMT/plantcv
plantcv/plantcv/visualize/histogram.py
Python
mit
6,304
0.002855
# Plot histogram import os import numpy as np from plantcv.plantcv.threshold import binary as binary_threshold from plantcv.plantcv import params from plantcv.plantcv import fatal_error from plantcv.plantcv._debug import _debug import pandas as pd from plotnine import ggplot, aes, geom_line, labels, scale_color_manual...
ply mask if one is supplied if mask is not None: min_val = np.min(gray_img) pixels = len(np.where(mask > 0)[0]) # apply plant shaped m
ask to image params.debug = None mask1 = binary_threshold(mask, 0, 255, 'light') mask1 = (mask1 / 255) masked = np.where(mask1 != 0, gray_img, min_val - 5000) else: pixels = gray_img.shape[0] * gray_img.shape[1] masked = gray_img params.debug = debug # Stor...
orchidinfosys/odoo
addons/account/models/partner.py
Python
gpl-3.0
22,069
0.006434
# -*- coding: utf-8 -*- from operator import itemgetter import time from openerp import api, fields, models, _ from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT from openerp.exceptions import ValidationError class AccountFiscalPosition(models.Model): _name = 'account.fiscal.position' _description = '...
fpos = self.search(domain_country + null_state_
dom + null_zip_dom, limit=1) # fallback: country group with no state/zip range if not fpos: fpos = self.search(domain_group + null_state_dom + null_zip_dom, limit=1) if not fpos: # Fallback on catchall (no country, no group) fpos = self.search(base_domain + ...
fajoy/nova
nova/cells/manager.py
Python
apache-2.0
9,098
0.000879
# Copyright (c) 2012 Rackspace Hosting # 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 req...
post_start_hook(self): """Have the driver start its consumers for inter-cell communication. Also ask our child cells for their capacities and capabilit
ies so we get them more quickly than just waiting for the next periodic update. Receiving the updates from the children will cause us to update our parents. If we don't have any children, just update our parents immediately. """ # FIXME(comstud): There's currently no ho...
sanjeevtripurari/hue
desktop/core/src/desktop/lib/metrics/file_reporter.py
Python
apache-2.0
2,100
0.007619
# Licensed to Cloudera, Inc. under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. Cloudera, Inc. licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file ex...
= METRICS.LOCATION.get() interval = METRICS.COLLECTION_INTERVAL.get() if location is not None and interval is not None: _reporter = FileReporter( location,
reporting_interval=interval / 1000.0, registry=global_registry()) _reporter.start()
mrjacobagilbert/gnuradio
gr-vocoder/python/vocoder/qa_g723_24_vocoder.py
Python
gpl-3.0
858
0
#!/usr/bin/env python # # Copyright 2011,2013
Free Software Foundation, Inc. # # This file is part of GNU Radio # # SPDX-License-Identifier: GPL-3.0-or-later # # from gnuradio import gr, gr_unittest, vocoder, blocks class test_g723_24_vocoder (gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb...
ource_s(data) enc = vocoder.g723_24_encode_sb() dec = vocoder.g723_24_decode_bs() snk = blocks.vector_sink_s() self.tb.connect(src, enc, dec, snk) self.tb.run() actual_result = snk.data() self.assertEqual(list(data), actual_result) if __name__ == '__main__': ...
forbidden-ali/Beebeeto-framework
demo/openssl_man_in_middle.py
Python
gpl-2.0
9,009
0.002612
#!/usr/bin/env python # coding=utf-8 """ Site: http://www.beebeeto.com/ Framework: https://github.com/n0tr00t/Beebeeto-framework """ import time import struct import random import socket import select import urlparse from baseframe import BaseFrame from utils.common.str import hex_dump class MyPoc(BaseFrame): ...
help='host port.') handshake_message = "" \ "\x16" \ "\x03\x01" \ "\x00\x9a" \ "\x01" \ "\x00\x00\x
96" \ "\x03\x01" \ "\x00\x00\x00\x00" \ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" \ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" \ "\x00" \ "\x00\x68" \ "\xc0\x14" \ "\xc0\x13" \ "\xc0\x12" \ "\xc0\x11" \ ...
huggingface/transformers
tests/mobilebert/test_modeling_mobilebert.py
Python
apache-2.0
15,383
0.00351
# coding=utf-8 # Copyright 2020 The HuggingFace Team. 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 requir...
ult = model(input_ids, token_type_ids=token_type_ids) result = model(input_ids) self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size)) self.parent.assertEqual(result.pooler_output.shape, (self.batch_size, self.hidden_size)) def create_...
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels ): model = MobileBertForMaskedLM(config=config) model.to(torch_device) model.eval() result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=token_labe...
Danielhiversen/home-assistant
tests/auth/test_auth_store.py
Python
apache-2.0
9,513
0.00021
"""Tests for the auth store.""" import asyncio from unittest.mock import patch from homeassistant.auth import auth_store async def test_loading_no_group_data_format(hass, hass_storage): """Test we correctly load old data without any groups.""" hass_storage[auth_store.STORAGE_KEY] = { "version": 1, ...
id": "user-id", "is_active": True, "is_owner": True, "name": "Paulus", "system_generated": False, }, { "id": "system-id", "is_active": True, "is_own...
{ "access_token_expiration": 1800.0, "client_id": "http://localhost:8123/", "created_at": "2018-10-03T13:43:19.774637+00:00", "id": "user-token-id", "jwt_key": "some-key", "last_used_at"...
CCBG/django-rolodex
rolodex/urls.py
Python
mit
1,436
0.009053
from django.conf.urls import patterns, url from ro
lodex import views urlpatterns = [ # Default view if the user have not navigated yet
url(r'^$', views.index, name='index'), # company related urls url(r'^company/add/$', views.company_add, name='company_add'), url(r'^company/edit/(?P<company_name>[A-Za-z0-9. \-]+)/$', views.company_edit, name='company_edit'), url(r'^company/lis...
AriZuu/micropython
tests/extmod/uzlib_decompio.py
Python
mit
691
0
try: import uz
lib as zlib import uio as io except ImportError: print("SKIP") raise SystemExit # Raw DEFLATE bitstream buf = io.BytesIO(b'\xcbH\xcd\xc9\xc9\x07\x00') inp = zlib.DecompIO(buf, -8) print(bu
f.seek(0, 1)) print(inp.read(1)) print(buf.seek(0, 1)) print(inp.read(2)) print(inp.read()) print(buf.seek(0, 1)) print(inp.read(1)) print(inp.read()) print(buf.seek(0, 1)) # zlib bitstream inp = zlib.DecompIO(io.BytesIO(b'x\x9c30\xa0=\x00\x00\xb3q\x12\xc1')) print(inp.read(10)) print(inp.read()) # zlib bitstream, w...
Frenesius/CrawlerProject56
crawler/ConfigManager.py
Python
gpl-3.0
4,164
0.005764
__author__ = 'j' import ConfigParser class ParseConfig: config = ConfigParser.ConfigParser() def __init__(self): pass def sumSection(self, filePath): ''' Counts the row amounts in the config file. :param file: path to the file. :return: Int with the amount of rows ...
DEFAULT", "xpathvalue") return customPath def getKeyxPath(self, int, filePath): file = filePath self.config.read(file) if self.config.has_option("ROW"+str(int), "xpathkey"): customPath = self.config.get("ROW"+str(int), "xpathkey") el
se: customPath = self.config.get("DEFAULT", "xpathkey") return customPath def getxPathPriceCrawler(self, int, filePath): ''' Gets the xpaths in the config of the price crawler. :param int: The row number. :param filePath:Path to the config file. :return: ...
d0c-s4vage/gramfuzz
examples/grams/postal.py
Python
mit
2,381
0.009244
#!/usr/bin/env python # -*- coding: utf-8 -*- from gramfuzz.fields import * import names TOP_CAT = "postal" # Adapted from https://en.wikipedia.org/wiki/Backus%E2%80%93Naur_form # The name rules have been modified and placed into names.py class PDef(Def): cat = "postal_def" class PRef(Ref): cat = "pos...
eet", "Spooner Street", "0day Causeway", "Diagon Alley", )) PDef("zip-part", PRef("town-name"), ", ", PRef("state-code"), " ", PRef("zip-code"), EOL ) PDef("apt-num", UInt(min=0, max=10000), Opt(String(charset=String.charset_alpha_upper, min=1, max=2)) ) PDef("town-name", Or( "Seoul", "São Paulo", "Bomb...
, "Delhi", "London", "HongKong", "Cairo", "Tehran", "Bogota", "Bandung", "Tianjin", "Lima", "Rio de Janeiro" "Lahore", "Bogor", "Santiago", "St Petersburg", "Shenyang", "Calcutta", "Wuhan", "Sydney", "Guangzhou", "Singapore", "Madras", "Baghdad", "Pusan", "Los Angeles", "Yokohama", "Dhaka", "Berlin", "A...
ejetzer/spinmob
egg/examples/example_sweeper.py
Python
gpl-3.0
5,048
0.008122
import numpy as _n import time as _t import spinmob.egg as egg ##### GUI DESIGN # create the main window w = egg.gui.Window(autosettings_path="example_sweeper_w.cfg") # add the "go" button b_sweep = w.place_object(egg.gui.Button("Sweep!", checkable=True)).set_width(50) b_select = w.place_object(egg.gui.B...
'x'] = [] d_sweep['mag'] = [] d_sweep['phase'] = [] # add a "region of interest" (ROI) for selecting the sweep range roi_sweep = egg.pyqtgraph.LinearRegionItem([settings['sweep/x_start'], settings['sweep/x_sto
p']]) d_sweep.ROIs = [roi_sweep] # show the blank plots d_sweep.plot() ##### MAIN FUNCTIONALITY # define a function to set some parameter on an external instrument def set_x(x): """ Pretends to set some instrument to a value "x" somehow. This is where your code should go. """ # for now just...
pywbem/pywbemtools
tests/unit/pywbemcli/all_types_method_mock_v1old.py
Python
apache-2.0
2,630
0
""" Test mock script that installs a test method provider for CIM method AllTypesMethod() in CIM class PyWBEM_AllTypes, using the old setup approach with global variables. Note: This script and its method provider perform checks because their purpose is to test the provider dispatcher. A real mock script with a real m...
self.provider_classnames.lower() if methodname != 'AllTypesMethod': raise pywbem.CIMError(pywbem.CIM_ERR_METHOD_NOT_AVAILABLE) # Test if class exists. if not self.class
_exists(namespace, classname): raise pywbem.CIMError( pywbem.CIM_ERR_NOT_FOUND, "class {0} does not exist in CIM repository, " "namespace {1}".format(classname, namespace)) # Return the input parameters as output parameters out_params = params...
Exploit-install/Veil-Pillage
modules/enumeration/host/detect_powershell.py
Python
gpl-3.0
2,043
0.007832
""" Module to detect a functional Powershell installation on a host or host list. TODO: implement parts of https://github.com/DiabloHorn/DiabloHorn/blob/master/remote_appinitdlls/rapini.py for remote registry modifications? Module built by @harmj0y """ from lib import command_methods class Module: ...
mand, triggerMethod) if result.strip() == "42": self.output += "[*] Powershell detected as functional using creds '"+username+":"+password+"' on : " + target + "\n" else: self.output += "[!] Powershell not detected as functional using creds '"+usern
ame+":"+password+"' on : " + target + "\n"
maximilianh/maxtools
lib/tabfile.py
Python
gpl-2.0
15,316
0.012471
import sys import glob #import sets import re def openSpec(fname, mode="r"): """ open and return filehandle, open stdin if fname=="stdin", do nothing if none """ if fname=="stdin": return sys.stdin elif fname=="stdout": return sys.stdout elif fname=="none" or fname==None: return...
"\t") if columnNames==None or len(columnNames)==0: columnNames=headers for c in columnNames: if c not in headers: sys.stderr.write("error tabfile.py: columnName %s (out of %s) not found in headers %s\n" % (c,str(columnNames), str(headers))) sys.exit(1) noList = range...
headers)) headerToNum = dict(zip(headers,noList)) data = [] #lno=0 for l in f: if l.startswith("#"): continue #lno+=1 #if lno==1: # ignore headers #continue fs = l.strip().split("\t") if asListOfDicts: rec = {} else: ...
pierg75/pier-sosreport
sos/plugins/tomcat.py
Python
gpl-2.0
2,298
0
# This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # This program is distributed in the hope that it will be useful, # but...
at*/*") def postproc(self): serverXmlPasswordAttributes = ['keyPass', 'keystorePass', 'truststorePass', 'SS
LPassword'] for attr in serverXmlPasswordAttributes: self.do_path_regex_sub( r"\/etc\/tomcat.*\/server.xml", r"%s=(\S*)" % attr, r'%s="********"' % attr ) self.do_path_regex_sub( r"\/etc\/tomcat.*\/tomcat-users.xml", ...
AxisPhilly/py-li
li/exceptions.py
Python
mit
302
0
class LIException(Exception): """There was an ambiguous exception that o
ccurred while handling your request.""" class DocTypeException(LIException): """The provided document type is invalid. """ cla
ss DocIDException(LIException): """The provided document ID is invalid. """
aljim/deploymentmanager-samples
examples/v2/saltstack/python/minion.py
Python
apache-2.0
3,271
0.003057
# Copyright 2016 Google Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
properties['minionCount']): resources.append(GenerateInstanceConfig(context, replica)) return {'resources': resources} def Gen
erateInstanceConfig(context, replica): """Generate configuration for every minion instance.""" name = (context.env['deployment'] + '-' + context.env['name'] + '-' + str(replica)) machine_type = ('https://www.googleapis.com/compute/v1/projects/' + context.env['project'] + '/zones/' ...
agconti/njode
env/lib/python2.7/site-packages/floppyforms/gis/widgets.py
Python
bsd-3-clause
5,019
0
from django.conf import settings from django.utils import translation, six try: from django.contrib.gis import gdal, geos except ImportError: """GDAL / GEOS not installed""" import floppyforms as forms __all__ = ('GeometryWidget', 'GeometryCollectionWidget', 'PointWidget', 'MultiPointWidget', ...
geom_type = 'GEOMETRYCOLLECTION' class PointWidget(BaseGeometryWidget): is_point = True geom_type = 'POINT' class MultiPoint
Widget(PointWidget): is_collection = True geom_type = 'MULTIPOINT' class LineStringWidget(BaseGeometryWidget): is_linestring = True geom_type = 'LINESTRING' class MultiLineStringWidget(LineStringWidget): is_collection = True geom_type = 'MULTILINESTRING' class PolygonWidget(BaseGeometryWid...
tastyproject/tasty
tasty/tests/functional/protocols/mul/unsignedvec_server_server_client/protocol.py
Python
gpl-3.0
442
0.004525
# -*- coding: utf-8 -*- __params__ = {'la': 32, 'lb': 32, 'da': 10
} def protocol(client, server, params): la = params['la'] lb = params['lb'] da = params["da"] server.a = UnsignedVec(bitlen=la, dim=da).input(src=driver, desc="a") server.b = Unsi
gned(bitlen=lb).input(src=driver, desc="b") client.a <<= server.a client.b <<= server.b client.c = client.a * client.b client.c.output(dest=driver, desc="c")
felixbb/forseti-security
google/cloud/security/scanner/audit/buckets_rules_engine.py
Python
apache-2.0
8,802
0.000227
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
les_file_path=rules_file_path) self.rule_bo
ok = None def build_rule_book(self): """Build BucketsRuleBook from the rules definition file.""" self.rule_book = BucketsRuleBook(self._load_rule_definitions()) # pylint: disable=arguments-differ def find_policy_violations(self, buckets_acls, force_rebuild=Fa...
talespaiva/folium
tests/test_features.py
Python
mit
3,684
0.000272
# -*- coding: utf-8 -*- """" Folium Features Tests --------------------- """ import os from branca.six import text_type from branca.element import Element from folium import Map, Popup from folium import features tmpl = """ <!DOCTYPE html> <head> <meta
http-equiv="content-type" content="text/html; charset=UTF-8" /> </head> <body> </body> <script> </script> """ # noqa # Figure def test_figure_creation(): f = features.Figure() assert isinstance(f, Element) bounds = f.get_bounds() assert bounds == [[None, None], [None, None]], bounds def test_figur...
f = features.Figure() out = f.render() assert type(out) is text_type bounds = f.get_bounds() assert bounds == [[None, None], [None, None]], bounds def test_figure_html(): f = features.Figure() out = f.render() out = os.linesep.join([s.strip() for s in out.splitlines() if s.strip()]) ...