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
supermari0/ironic
ironic/tests/matchers.py
Python
apache-2.0
3,436
0
# Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # Copyright 2012 Hewlett-Packard Development Company, L.P. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the L...
self.tolerance = tolerance def __str__(self): return 'DictMatches(%s)' % (pprint.pformat(self.d1)) # Useful assertions def match(self, d2): """Assert two dicts are equivalent. Thi
s is a 'deep' match in the sense that it handles nested dictionaries appropriately. NOTE: If you don't care (or don't know) a given value, you can specify the string DONTCARE as the value. This will cause that dict-item to be skipped. """ d1keys = ...
jileiwang/CJ-Glo
tools/AnalogyData.py
Python
apache-2.0
5,375
0.005767
class AnalogyData(): def __init__(self): self.read_analogy() self.translationPairs = None self.crossZh = None self.crossJa = None self.cross2Zh2Ja = None self.cross1Zh3Ja = None self.cross3Zh1Ja = None def read_analogy(self): self.records = [] ...
oss1vs3(self, lang): # lang has 1 token result = [] for
record1 in self.records: for record2 in self.records: if record1 == record2: continue for c in [0, 1]: result.append((record1[lang][c], record1[1-lang][1-c], record2[1-lang][c], record2[1-lang][1-c])) result.append((...
fhcrc/taxtastic
taxtastic/subcommands/rollforward.py
Python
gpl-3.0
2,393
0.000418
# This file is part of taxtastic. # # taxtastic 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 later version. # # taxtastic is distrib...
k. If any operation besides a rollback occurs, all roll forward information is removed. """ import logging from taxtastic import refpkg log = logging.getLogger(__name__) def build_parser(p
arser): parser.add_argument('refpkg', action='store', metavar='refpkg', help='the reference package to operate on') parser.add_argument('-n', action='store', metavar='int', default=1, type=int, help='Number of operations to roll back') de...
autogestion/sh_ctracker
ctracker/migrations/0001_initial.py
Python
bsd-3-clause
3,369
0.003859
# -*- coding: utf-8 -*- # Generated by Django 1.10.8 on 2017-10-06 14:43 from __future__ import unicode_literals import django.contrib.gis.db.models.fields from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] ...
delete=django.db.models.deletion.CASCADE, to='ctracker.Polygon')), ('organizations', models.ManyToManyField(blank=True, to='ctracker.Organization')), ], ), migrations.Creat
eModel( name='Uploader', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('json_file', models.FileField(upload_to='geojsons')), ], options={ 'verbose_name_plural': ...
pypy90/graphite-web
webapp/graphite/settings.py
Python
apache-2.0
5,977
0.010373
"""Copyright 2008 Orbitz WorldWide 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...
the libs shipped in thirdparty to take precedence sys.path.append(THIRDPARTY_DIR) # Cluster settings CLUSTER_SERVERS = [] REMOTE_FIND_TIMEOUT = 3.0 REMOTE_FETCH_TIMEOUT = 6.0 REMOTE_RETRY_DELAY = 60.0 REMOTE_READER_CACHE_SIZE_LIMIT = 1000 CARBONLINK_HOSTS = ["127.0.0.1:7002"] CARBONLINK_TIMEOUT = 1.0 CARBONLINK_HASHIN...
_RETRY_DELAY = 15 REPLICATION_FACTOR = 1 MEMCACHE_HOSTS = [] FIND_CACHE_DURATION = 300 FIND_TOLERANCE = 2 * FIND_CACHE_DURATION DEFAULT_CACHE_DURATION = 60 #metric data and graphs are cached for one minute by default LOG_CACHE_PERFORMANCE = False #Remote rendering settings REMOTE_RENDERING = False #if True, rendering ...
ducksboard/libsaas
libsaas/services/recurly/subscriptions.py
Python
mit
2,990
0
from libsaas import http, parsers from libsaas.services import base from . import resource class SubscriptionsBase(resource.RecurlyResource): path = 'subscriptions' def delete(self, *args, **kwargs): raise base.MethodNotSupported() class Subscriptions(SubscriptionsBase): @base.apimethod ...
red billing information. :var refund: The type of the refund to perform: 'full' or 'partial' Defaults to 'none'. :vartype refund: str """ self.require_item() url = '{0}/terminate'.format(self.get_url()) params = { 'refund': refund if refu
nd else 'none' } url = url + '?' + http.urlencode_any(params) request = http.Request('PUT', url) return request, parsers.parse_empty @base.apimethod def postpone(self, next_renewal_date): """ Postpone a subscription :var next_renewal_date: The next ren...
italomandara/mysite
myresume/routers.py
Python
mit
456
0
from .viewsets import * from rest_framework import routers # Routers provide an easy way of automat
ically determining the URL conf. router = routers.DefaultRouter() router.register(r'person', PersonViewSet) router.register(r'skill', SkillViewSet) router.register(r'mycontent', MyContentViewSet) router.register(r'job', JobViewSet) router.register(r'course', CourseViewSet) router.register(r'post', PostViewSet) router.r...
ct', ContactViewSet)
tehp/reddit
SubmissionRatio/submissionratio.py
Python
mit
6,743
0.026991
#/u/GoldenSights import praw import time import sqlite3 import datetime import traceback '''USER CONFIGURATION''' USERNAME = "" #This is the bot's Username. In order to send mail, he must have some amount of Karma. PASSWORD = "" #This is the bot's Password. USERAGENT = "" #This is a short description of what the b...
RT != 0: fetched.reverse() table = '\n\nUsername | Comments | Submissions | Ratio\n' tabl
e += ':- | -: | -: | -:\n' for item in fetched: table += '/u/' + item[0] + ' | ' + str(item[1]) + ' | ' + str(item[2]) + ' | ' + str(item[3]) + '\n' table += '\n\n' lines[pos] = line.replace('__BUILDTABLE__', table) if "__STRFTIME" in line: print('\tBuilding timestamp') ...
mne-tools/mne-tools.github.io
0.20/_downloads/7bb433a8c5a4cf876b244e99c2c7c8b7/plot_stats_spatio_temporal_cluster_sensors.py
Python
bsd-3-clause
7,444
0
""" ===================================================== Spatiotemporal permutation F-test on full sensor data ===================================================== Tests for differential evoked responses in at least one condition using a permutation clustering test. The FieldTrip neighbor templates will be used to d...
='orange', alpha=0.3) # clean up viz mne.viz.tight_layout(fig=fig) fig.subplots_adjust(bottom=.05) p
lt.show() ############################################################################### # Exercises # ---------- # # - What is the smallest p-value you can obtain, given the finite number of # permutations? # - use an F distribution to compute the threshold by traditional significance # levels. Hint: take a look...
tsoporan/tehorng
blog/urls.py
Python
agpl-3.0
421
0.011876
from django.conf.urls.defaults import * urlpat
terns = patterns('', url(r'^$', 'blog.views.entry_list', name="entry-list"), url(r'^archive/(?P<year>\d{4})/$', 'blog.views.entry_archive_year', name="year-archive"), url(r'^archive/(?P<year>\d{4})/(?P<month>\d{1,2})/$', 'blog.views.entry_archive_month', name="month-archive"), url(r'^(?P<slug>[-\w]+)/$...
g.views.entry_detail', name="entry-detail"), )
teeple/pns_server
work/install/Python-2.7.4/Lib/lib2to3/fixes/fix_ne.py
Python
gpl-2.0
573
0
# Copyright 2006 Google, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. """Fixer that turns <> into !=.""" # Local imports from .. import pytree from ..pgen2 import token from .. import fixer_base class FixNe(fixer_base.BaseFix): # This is so simple that we don't need the pattern com...
ride return node.value == u"<>" def transform(self, node, results): new = pytree.Leaf(token.NOTEQUAL, u"!=", pr
efix=node.prefix) return new
benwilburn/fitist
FITist_project/user_profiles/forms.py
Python
mit
1,871
0
from django import forms # from django.core import validators from django.contrib.auth.models import User from django.contrib.auth.forms import AuthenticationForm class LoginForm(AuthenticationForm): username = forms.CharField( label="Username", max_length=30, widget=forms....
Field(widget=forms.EmailInput) confirm_email = forms.CharField(widget=forms.EmailInput) class Meta: model
= User fields = [ 'username', 'first_name', 'last_name', 'email', 'confirm_email', 'password', 'confirm_password', ] def clean(self): cleaned_data = super(UserForm, self).clean() password = cleaned_d...
alanbowman/home-assistant
homeassistant/components/camera/__init__.py
Python
mit
6,728
0
# pylint: disable=too-many-lines """ homeassistant.components.camera ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Component to interface with various cameras. The following features are supported: - Returning recorded camera images and streams - Proxying image requests via HA for external access - Converting a still image url i...
REC_DIR_PREFI
X = 'recording-' REC_IMG_PREFIX = 'recording_image-' STATE_STREAMING = 'streaming' STATE_IDLE = 'idle' CAMERA_PROXY_URL = '/api/camera_proxy_stream/{0}' CAMERA_STILL_URL = '/api/camera_proxy/{0}' ENTITY_IMAGE_URL = '/api/camera_proxy/{0}?time={1}' MULTIPART_BOUNDARY = '--jpegboundary' MJPEG_START_HEADER = 'Content-t...
mesnardo/PetIBM
examples/ibpm/cylinder2dRe3000_GPU/scripts/plotDragCoefficient.py
Python
bsd-3-clause
2,006
0
""" Plots the instantaneous drag coefficient between 0 and 3 time-units of flow simulation and compares with numerical results from Koumoutsakos and Leonard (1995). _References:_ * Koumoutsakos, P., & Leonard, A. (1995). High-resolution simulations of the flow around an impulsively started cylinder using vortex me...
ag coefficients. fig, ax = pyplot.subplots(figsize=(8.0, 6.0)) ax.grid() ax.set_xlabel('Non-dimensional time') ax.set_ylabel('Drag coefficient') for label, subdata in data.items(): ax.plot(subdata['t'], subdata['cd'], label
=label, **subdata['kwargs']) ax.axis((0.0, 3.0, 0.0, 2.0)) ax.legend() pyplot.show() # Save figure. fig_dir = simu_dir / 'figures' fig_dir.mkdir(parents=True, exist_ok=True) filepath = fig_dir / 'dragCoefficient.png' fig.savefig(str(filepath), dpi=300)
linkfloyd/linkfloyd
linkfloyd/notifications/templatetags/notification_tags.py
Python
bsd-3-clause
427
0.002342
# -*-
coding: utf-8 -*- from django.template import Library from notifications.models import Notification register = Library() @register.assignment_tag(takes_context=True) def get_unread_notifications_count(context): if 'user' not in context: return '' user = context['user'] if user.is_anonymous(): ...
filter(recipient=user, seen=False).count()
STIXProject/python-stix
stix/common/kill_chains/__init__.py
Python
bsd-3-clause
4,359
0.001376
# Copyright (c) 2017, The MITRE Corporation. All rights reserved. # See LICENSE.txt for complete terms. from mixbox import fields from mixbox import typedlist from mixbox import entities # internal import stix import stix.bindings.stix_common as common_binding class KillChain(stix.Entity): __hash__ = entities.E...
PhaseReference, multiple=True, listfunc=_KillChainPhaseReferenceList, key_name="kill_chain_phases" ) @classmethod def _dict_as_list(cls): retur
n False # NOT AN ACTUAL STIX TYPE! class _KillChainPhases(stix.TypedList): _contained_type = KillChainPhase
mage2k/pg_partitioner
pg_partitioner/sql_util.py
Python
bsd-3-clause
2,074
0.007715
def table_exists(curs, table_name=''): ''' If table_name is a schema qualified table name and it exists it is returned, else if it is not schema qualified and the table name exists in the search path then that schema qualified table name is returned, else None. ''' curs.execute('SELECT pgparti...
tuple of the given table's attributes ''' curs.execute('SELECT * FROM pgpartitioner.get_table_attributes(%s);', (table_name,)) atts = tuple([res[0] for res in curs.fetchall()]) return atts def normalize_date(curs, date_str, fmt, units='month', diff='0 months'): '''
Takes a valid date string in any format and formats it according to fmt. ''' normalize_date_sql = \ ''' SELECT to_char(date_trunc(%s, %s::timestamp + %s), %s); ''' curs.execute(normalize_date_sql, (units, date_str, diff, fmt)) return curs.fetchone()[0]
nicholas-leonard/hyperopt
hyperopt/ipy.py
Python
bsd-3-clause
7,175
0.002787
"""Utilities for Parallel Model Selection with IPython Author: James Bergstra <[email protected]> Licensed: MIT """ from time import sleep, time import numpy as np from IPython.parallel import interactive #from IPython.parallel import TaskAborted #from IPython.display import clear_output from .base import Tri...
f.refresh() if verbose and last_print_time + verbose_print_interval < time(): print 'fmin: %4i/%4i/%4i/%4i %f' % ( self.count_by_state_unsynced(JOB_STATE_NEW), self.count_by_state_unsynced(JOB_STATE_RUNNING), self.count_by_state_un...
float('inf')] + [l for l in self.losses() if l is not None]) ) last_print_time = time() if self.count_by_state_unsynced(JOB_STATE_NEW): sleep(1e-1) continue if self.count_by_state_unsynced(JOB_STATE_RUNNI...
SmartInfrastructures/fuel-web-dev
nailgun/nailgun/test/integration/test_node_handler.py
Python
apache-2.0
12,873
0.000078
# -*- coding: utf-8 -*- # Copyright 2013 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...
jsonutils.dumps({'meta': new_m
etadata}), headers=self.default_headers) self.assertEqual(resp.status_code, 200) self.db.refresh(node) nodes = self.db.query(Node).filter( Node.id == node.id ).all() self.assertEqual(len(nodes), 1) self.assertEqual(nodes[0].meta, new_metadata) ...
pierg75/pier-sosreport
sos/plugins/openvswitch.py
Python
gpl-2.0
6,609
0
# Copyright (C) 2014 Adam Stokes <[email protected]> # 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 progr...
Capture tnl arp table" "ovs-appctl tnl/arp/show", # Capture a list of listening ports" "ovs-appctl tnl/ports/show", # Captu
re upcall information "ovs-appctl upcall/show", # Capture DPDK and other parameters "ovs-vsctl -t 5 get Open_vSwitch . other_config", # Capture OVS list "ovs-vsctl list Open_vSwitch", # Capture DPDK datapath packet counters and config "...
valmynd/pyrel
setup.py
Python
agpl-3.0
311
0.016077
from distutils.core import setup from distutils.extension import Extension from Cython.Distutils import build_ext setup( cmdclass = {'build_ext': build_ext}, #ext_modules = [Extension("database", ["data
base.pyx", "cescape.c"])] ext_modu
les = [Extension("database", ["database.py", "cescape.c"])] )
docusign/docusign-python-client
docusign_esign/models/payment_gateway_accounts_info.py
Python
mit
3,706
0.00027
# coding: utf-8 """ DocuSign REST API The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign. # noqa: E501 OpenAPI spec version: v2.1 Contact: [email protected] Generated by: https://github.com/swagger-api/swagger-codegen.gi...
ypes (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value
is json key in definition. """ swagger_types = { 'payment_gateway_accounts': 'list[PaymentGatewayAccount]' } attribute_map = { 'payment_gateway_accounts': 'paymentGatewayAccounts' } def __init__(self, payment_gateway_accounts=None): # noqa: E501 """PaymentGatewayAccou...
163gal/Time-Line
libs_arm/dependencies/pysvg-0.2.1/pysvg/gradient.py
Python
gpl-3.0
5,902
0.009658
#!/usr/bin/python # -*- coding: iso-8859-1 -*- ''' (C) 2008, 2009 Kerim Mansour For licensing information please refer to license.txt ''' from attributes import * from core import BaseElement, PointAttrib, DimensionAttrib class linearGradient(BaseElement, CoreAttrib, XLinkAttrib, PaintAttrib, StyleAttrib, ...
nsionAttrib
): """ Class representing the pattern element of an svg doc. """ def __init__(self, x=None, y=None, width=None, height=None, patternUnits=None, patternContentUnits=None, patternTransform=None, viewBox=None, preserveAspectRatio=None, **kwargs): BaseElement.__init__(self, 'pattern') self.s...
iulian787/spack
var/spack/repos/builtin/packages/py-tap-py/package.py
Python
lgpl-2.1
1,128
0.003546
# 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) from spack import * class PyTapPy(PythonPackage): """Python TAP interface module for unit
tests""" homepage = "https://github.com/python-tap/tappy" url = "https://pypi.io/packages/source/t/tap.py
/tap.py-3.0.tar.gz" version('3.0', sha256='f5eeeeebfd64e53d32661752bb4c288589a3babbb96db3f391a4ec29f1359c70') version('2.6.2', sha256='5f219d92dbad5e378f8f7549cdfe655b0d5fd2a778f9c83bee51b61c6ca40efb') version('1.6', sha256='3ee315567cd1cf444501c405b7f7146ffdb2e630bac58d0840d378a3b9a0dbe4') extend...
Jasper-Koops/THESIS_LIFEBOAT
DJANGO_GUI/django_gui/gui/migrations/0002_auto_20170526_2213.py
Python
mit
621
0.00161
# -*- coding: utf-8 -*- # Generated by Djan
go 1.11 on 2017-05-26 22:13 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('gui', '0001_initial'), ] operations = [ migrations.RemoveField( model_name='saveddata', name='id...
_key=True, serialize=False), preserve_default=False, ), ]
odahoda/noisicaa
noisicaa/core/ipc_perftest.py
Python
gpl-2.0
1,459
0.001371
#!/usr/bin/python3 # @begin:license # # Copyright (c) 2015-2019, Benjamin Niemann <[email protected]> # # 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 y...
st.t.add(numerator=random.rand
int(0, 4), denominator=random.randint(1, 2)) await self.run_test(request, 100)
ZompaSenior/fask
fask/src/fask_dj/dashboard/urls.py
Python
agpl-3.0
1,461
0.002053
"""fask_dj URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') ...
elect_day>[0-9]+)/(?P<negative>[\w]+)/$', views.task_calendar_details_request, name='task_calendar_details_request'), url(r'^task_project/(?P<task_id>[0-9]+)/(?P<project_id>[0-9]+)/(?P<redirect_name>[\w]+)/$', task_project, name='task_project'), url(r'^import_export_page/$', views.import_export_page, name='im...
rt'), ]
saurabh6790/erpnext
erpnext/erpnext_integrations/doctype/shopify_settings/test_shopify_settings.py
Python
gpl-3.0
3,757
0.024754
# -*- coding: utf-8 -*- # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # See license.txt from __future__ import unicode_literals import frappe import unittest, os, json from frappe.utils import cstr from erpnext.erpnext_integrations.connectors.shopify_connection import create_order from erpnext.e...
the fixture data import_doc(path=frappe.get_app_path("erpnext", "erpnext_
integrations/doctype/shopify_settings/test_data/custom_field.json"), ignore_links=True, overwrite=True) frappe.reload_doctype("Customer") frappe.reload_doctype("Sales Order") frappe.reload_doctype("Delivery Note") frappe.reload_doctype("Sales Invoice") self.setup_shopify() def setup_shopify(self): sh...
JamesNickerson/py-junos-eznc
tests/unit/utils/test_fs.py
Python
apache-2.0
13,790
0
__author__ = "Nitin Kumar, Rick Sherman" __credits__ = "Jeremy Schulman" import unittest from nose.plugins.attrib import attr import os from ncclient.manager import Manager, make_device_handler from ncclient.transport import SSHSession from jnpr.junos import Device from jnpr.junos.utils.fs import FS from mock impor...
1039', 'owner': 'root', 'path': 'abc', 'size': 2, 'type': 'dir', 'permissions': 555}}, 'path': '/var', 'type': 'dir',
'file_count': 1, 'size': 2}) def test_ls_return_none(self): path = 'test/abc' self.fs.dev.rpc.file_list = MagicMock() self.fs.dev.rpc.file_list.find.return_value = 'output' self.assertEqual(self.fs.ls(path), None) @patch('jnpr.junos.u...
zenoss/ZenPacks.community.TokyoTyrant
setup.py
Python
gpl-2.0
2,602
0.009992
################################ # These variables are overwritten by Zenoss when the ZenPack is exported # or saved. Do not modify them directly here. # NB: PACKAGES is deprecated NAME = 'ZenPacks.community.TokyoTyrant' VERSION = '1.0' AUTHOR = 'B Maqueira' LICENSE = "GPLv2" NAMESPACE_PACKAGES = ['ZenPacks', 'ZenPack...
RS = '>=2.5.2' PREV_ZENPACK_NAME = '' # STOP_REPLACEMENTS ################################ # Zenoss will not overwrite any changes you make below here. from setuptools import setup, find_packages setup( # This ZenPack metadata should usually be edited with the Zenoss # ZenPack edit page. Whenever the edit pa...
SE, # This is the version spec which indicates what versions of Zenoss # this ZenPack is compatible with compatZenossVers = COMPAT_ZENOSS_VERS, # previousZenPackName is a facility for telling Zenoss that the name # of this ZenPack has changed. If no ZenPack with the current name is # installe...
django-json-api/rest_framework_ember
example/migrations/0007_artproject_description.py
Python
bsd-2-clause
405
0
# Generated by Django 2.2.2 on 2019-06-07 06:46 from django.db import migrations, models class Migration(migrations.Migration):
dependencies = [ ("example", "0006_auto_20181228_0752"), ]
operations = [ migrations.AddField( model_name="artproject", name="description", field=models.CharField(max_length=100, null=True), ), ]
JasonGross/time-worked
pastWeekTime.py
Python
mit
128
0
#!/usr/bin/python from TimeWorked import * import os files = [T
IME_WORKED] print get_total_time_by_day_files(files) raw_i
nput()
Azure/azure-sdk-for-python
sdk/cognitiveservices/azure-cognitiveservices-vision-customvision/azure/cognitiveservices/vision/customvision/prediction/models/_models.py
Python
mit
10,932
0.000091
# 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 ...
_validation =
{ 'id'
wesley1001/dokomoforms
tests/db_test.py
Python
gpl-3.0
47,704
0
""" Tests for the dokomo database """ import unittest import uuid from sqlalchemy import cast, Text, Boolean from datetime import timedelta from passlib.hash import bcrypt_sha256 from dokomoforms.db import update_record, delete_record from dokomoforms import db from dokomoforms.db.answer import answer_insert, answer...
survey_id=survey_id)) submission_id = submission_exec.inserted_primary_key[0] answer_exec = connection.execute(answer_insert( answer=1, question_id=question_id, answer_metadata={}, submission_id=submission_id, survey_id=survey_id, type_co...
rted_primary_key[0] self.assertIsNotNone(answer_id) def testAnswerInsertNoMetadata(self): survey_id = connection.execute(survey_table.select().where( survey_table.c.survey_title == 'test_title')).first().survey_id q_where = question_table.select().where( question_tab...
sanguinariojoe/aquagpusph
examples/3D/spheric_testcase2_dambreak_mpi/cMake/plot_h.py
Python
gpl-3.0
4,882
0.003892
#****************************************************************************** # * # * ** * * * * * # * * * * * * * * * * ...
* # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * # GNU General Public License for more details. * #
* # You should have received a copy of the GNU General Public License * # along with AQUAgpusph. If not, see <http://www.gnu.org/licenses/>. * # * #**************************************...
broad-well/aoc2016
day19p1.py
Python
unlicense
89
0.011236
# Day 19
of Advent of Code i = 0 for o in range(1, 3012211): i = (i+2)%o pr
int(i+1)
klen/adrest
tests/rpc/api.py
Python
lgpl-3.0
1,511
0.000662
from adrest.api import Api from adrest.utils.auth import AnonimousAuthenticator from adrest.utils.emitter import XMLEmitter, JSONTemplateEmitter from adrest.views import ResourceView from adrest.resources.rpc import RPCResource, JSONEmitter, JSONPEmitter API = Api('1.0.0', api_rpc=True, emitters=XMLEmitter) class T...
model = 'rpc.child' class CustomResource(ResourceView): class Meta: model = 'rpc.custom' API.register(ChildResource) API.register(CustomResource, emitters=JSONTemplateEmitter) API.register(RootResource, authenticators=TestAuth) API.register(RPCResource, url_regex=r'^rpc2$', url_name='rpc2', ...
e=C
tadashi-aikawa/gemini
jumeaux/addons/res2res/json.py
Python
mit
2,536
0.001183
# -*- coding:utf-8 -*- import json import sys from importlib import import_module from importlib.util import find_spec from owlmixin import OwlMixin, TOption from owlmixin.util import load_json from jumeaux.addons.res2res import Res2ResExecutor from jumeaux.logger import Logger from jumeaux.models import Res2ResAddOn...
odule} module") sys.exit(1) def exec(self, payload: Res2ResAddOnPayload) -> Res2ResAddOnPayload: req: Request = payload.req res: Response = payload.response if not self.config.when.map(lambda x: when_filter(x, {"req": req, "res": res})).get_or( True ): ...
on_str: str = self.module(res.body, res.encoding.get()) new_encoding: str = res.encoding.get_or(self.config.default_encoding) return Res2ResAddOnPayload.from_dict( { "response": { "body": json_str.encode(new_encoding, errors="replace"), ...
jadnohra/connect
proto_2/ddq/fol/equality.py
Python
unlicense
119
0
from .predicate import Predicate class Equality(Predicate): def __init__(self):
super().__init__('='
, 2)
the-zebulan/CodeWars
tests/kyu_7_tests/test_sum_of_numbers_from_zero_to_n.py
Python
mit
566
0
import unittest from katas.kyu_7.sum_of_numbers_from_zero_to_n import show_sequence class ShowSequenceTestCase(unittest.TestCase): def test_equal_1(self): self.assertEqual(show_sequence(6), '0+1+2+3+4+5+6 = 21') def test_equal_2(self): self.assertEqual
(show_sequence(7), '0+1+2+3+4+5+6+7 = 28') def test_equal_3(self): self.assertEqual(show_sequence(0), '0=0') def test_equal_4(self): self.assertEqual(show_s
equence(-1), '-1<0') def test_equal_5(self): self.assertEqual(show_sequence(-10), '-10<0')
micvision/neo-sdk
neopy/neopy/__main__.py
Python
mit
3,657
0.011485
#!/usr/bin/env python # coding=utf-8 import itertools, threading import sys, math import neopy def main(): ### USAGE: python -m neopy /dev/ttyACM0 if len(sys.argv) < 2: sys.exit('python -m neopy /dev/ttyACM0') dev = sys.argv[1] ### Named a device as neo_device with neopy.neo(dev) as neo_d...
self.datax = [None] * 360 # self.datay = [None] * 360 #for i in range(360): #x[i] = np.random.randint(-40, 40) #y[i] = np.random.randint(-40, 40) #self.datax = np.random.randn(100) #self.datay = np.random.randn(100) self.draw_data, = self.ax.plot(x, y, ...
self.canvas.draw() self.bg = self.canvas.copy_from_bbox(self.ax.bbox) wx.EVT_TIMER(self, TIMER_ID, self.onTimer) th.start() def onTimer(self, evt): global x, y global flag self.canvas.restore_region(self.bg) #self.draw_data.set_data(x, y) #self.d...
dstrockis/outlook-autocategories
shared/auth.py
Python
apache-2.0
5,109
0.007046
from models import User from google.appengine.ext import ndb from datetime import timedelta, datetime import logging import urllib import urllib2 import socket import os import json import config from shared import config import socket isDevEnv = True if 'localhost' in socket.gethostname() else False # Get AT from ca...
ex # Parse token response auth_resp = json.loads(response.read()) # Store tokens logging.debug('Storing r
efresh_token in ndb') entry.access_token = auth_resp['access_token'] entry.refresh_token = auth_resp['refresh_token'] entry.acquired = datetime.utcnow() entry.put() return auth_resp['access_token'] raise Exception('Unable to get an access_token, sign in requ...
bp-kelley/rdkit
rdkit/sping/PS/psmetrics.py
Python
bsd-3-clause
17,605
0.009543
# $Id$ # Christopher Lee [email protected] # based upon pdfmetrics.py by Andy Robinson from . import fontinfo from . import latin1MetricsCache ############################################################## # # PDF Metrics # This is a preamble to give us a stringWidth function. # loads and caches AFM files...
600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 60
0, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 6...
thehq/python-branchio
tests/test_client.py
Python
mit
5,185
0.002314
import unittest import branchio import os import mock class ClientCheckParamTests(unittest.TestCase): def setUp(self): self.branch_client = branchio.Client(None) self.params = {} def test_optional(self): self.branch_client._check_param("test", None, self.params) self.assertF...
ww.example
.com/"}, {"url": "https://www.example.com/"}]) params1 = client.create_deep_link_url( data={ branchio.DATA_BRANCH_IOS_URL: "https://www.google.com", "custom": "payload" }, channel="facebook", tags=["signup"], skip_api_ca...
avagin/p.haul
p_haul_img.py
Python
lgpl-2.1
2,640
0.030682
# # images driver for migration (without FS transfer) # import os import tempfile import rpyc import tarfile import time import shutil import time img_path = "/var/local/p.haul-fs/" img_tarfile = "images.tar" xfer_size = 64 * 1024 def copy_file(s, d): while True: chunk = s.read(xfer_size) if not chunk: break...
ny images (yet?) # so copy only those from the top dir print "Sending images to target" start = time.time() print "\tPack" tf_name = os.path.join(self.current_dir, img_tarfile) tf = tarfile.open(tf_name, "w") for img in os.listdir(self.current_dir): if img.endswith(".img"): tf.add(os.path.join(se...
himg in htype.get_meta_images(self.current_dir): tf.add(himg[0], himg[1]) tf.close() print "\tCopy" lfh = open(tf_name, "rb") os.unlink(tf_name) rfh = th.open_image_tar() copy_file(lfh, rfh) print "\tUnpack" rfh.unpack_and_close() self.sync_time = time.time() - start # This one is created by ...
kargakis/test-infra
experiment/fix_testgrid_config.py
Python
apache-2.0
2,759
0.000725
#!/usr/bin/env python # Copyright 2018 The Kubernetes 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 appli...
D_PREFIX): for tab in dashboard['dashboard_tab']: name = tab['test_group_name'] for key, val in MAP.iteritems(): name = name.replace(key, val) tab['name'] = name # write out yaml with open(testgrid, 'w') as fp: yaml.dump( ...
estgrid configs') PARSER.add_argument( '--testgrid-config', default='./testgrid/config.yaml', help='Path to testgrid/config.yaml') ARGS = PARSER.parse_args() main(ARGS.testgrid_config)
johnstonskj/PyDL7
setup.py
Python
mit
915
0
from setuptools import setup def readme(): with open('README.md') as f: return f.read() setup( name='PyDL7', version='0.0.3', description='Python API for parsing DAN Dive Log files.', long_description=readme(), author='Simon Johnston', author_email='[email protected]',
download_url='https://pypi.python.org/pypi/PyDL7', url='https://github.com/johnstonskj/PyDL7', license='MIT', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License',
], packages=['divelog'], setup_requires=['pytest-runner'], tests_require=[ 'pytest', 'pytest-cov', 'pytest-catchlog', 'pytest-pep8' ], entry_points={ 'console_scripts': [ 'dl7dump=divelog.command_line:main', ], } )
tschmorleiz/amcat
amcat/models/coding/codedarticle.py
Python
agpl-3.0
12,691
0.003703
########################################################################### # (C) Vrije Universiteit, Amsterdam (the Netherlands) # # # # This file is part of AmCAT - The Amsterdam Content Analysis Toolkit # # ...
rns an iterator with CodingValue's. """ return map(partial(_to_codingvalue, coding), values) class CodedArticle(models.Model): """ A CodedArticle is an article in a context of two other objects: a codingjob and an article. It exist for e
very (codingjob, article) in {codingjobs} X {codingjobarticles} and is created when creating a codingjob (see `create_coded_articles` in codingjob.py). Each coded article contains codings (1:N) and each coding contains codingvalues (1:N). """ comments = models.TextField(blank=True, null=True) statu...
shanezhiu/pyspider
pyspider/database/mysql/projectdb.py
Python
apache-2.0
2,401
0.001249
#!/usr/bin/env python # -*- encoding: utf-8 -*- # vim: set et sw=4 ts=4 sts=4 ff=unix fenc=utf8: # Author: Binux<[email protected]> # http://binux.me # Created on 2014-07-17 21:06:43 import time import mysql.connector from pyspider.database.base.projectdb import ProjectDB as BaseProjectDB from pyspider.database.base...
elds) def get(self, name, fields=None): where = "`name` = %s" % self.placeholder for each in self._select2dic(what=fields, where=where, where_values=(name, )): return each return None def drop(self, name): where = "`name` = %s" % self.placeholder return self...
def check_update(self, timestamp, fields=None): where = "`updatetime` >= %f" % timestamp return self._select2dic(what=fields, where=where)
tdi/cfn-inspect
cfn_inspect/__main__.py
Python
mit
58
0
from .cli import cli if __n
ame__ == "__main__": cli()
steveb/heat
heat/tests/engine/service/test_stack_resources.py
Python
apache-2.0
32,282
0
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed unde...
Raises(dispatcher.ExpectedException, self.eng.describe_stack_resource, self.ctx, self.stack.identifier(), 'foo') self.assertEqual(exception.ResourceNotFound, ex.exc_info[0]) mock_load.assert_called_once_with(self.ctx, stack=mock.ANY) @to...
rce_describe_noncreated_test_stack', create_res=False) def test_stack_resource_describe_noncreated_resource(self): self._test_describe_stack_resource() @mock.patch.object(service.EngineService, '_authorize_stack_user') @tools.stack_context('service_resource_describe_user_de...
flumotion-mirror/flumotion
flumotion/worker/checks/gst010.py
Python
lgpl-2.1
8,378
0.000716
# -*- Mode: Python -*- # vi:si:et:sw=4:sts=4:ts=4 # Flumotion - a streaming media server # Copyright (C) 2004,2005,2006,2007,2008,2009 Fluendo, S.L. # Copyright (C) 2010,2011 Flumotion Services, S.A. # All rights reserved. # # This file may be distributed and/or modified under the terms of # the GNU Lesser General Pub...
set_state_deferred: bool @returns: a deferred that will fire with the result of check_proc, or fail. @rtype: L{twisted.internet.defer.Deferred} """ def run_check(pipeline, resolution): element = pipeline.get_by_name(element_name) try: retval = check_proc(eleme...
kProcError, e: log.debug('check', 'CheckProcError when running %r: %r', check_proc, e.data) resolution.errback(errors.RemoteRunError(e.data)) except Exception, e: log.debug('check', 'Unhandled exception while running %r: %r', check_...
therewillbecode/ichnaea
ichnaea/models/observation.py
Python
apache-2.0
6,285
0
import operator import colander import mobile_codes from ichnaea import geocalc from ichnaea.models.base import ( CreationMixin, ValidationMixin, ValidPositionSchema, ) from ichnaea.models.cell import ( decode_radio_dict, encode_radio_dict, CellKeyPsc, ValidCellKeySchema, ValidCellSign...
accuracy = DefaultNode( colander.Float(), missing=None, validator=colander.Range( 0, constants.MAX_ALTITUDE_ACCURACY)) heading = DefaultNode(
colander.Float(), missing=None, validator=colander.Range( 0, constants.MAX_HEADING)) speed = DefaultNode( colander.Float(), missing=None, validator=colander.Range( 0, constants.MAX_SPEED)) def validator(self, node, cstruct): super(ValidReportSchema, self).valida...
Etenil/anvil
anvillib/avatar.py
Python
mit
1,254
0.00319
from hashlib import md5 from urllib import urlencode import common import httplib import re import config def url_exists(site, path): try: conn = httplib.HTTPConnection(site) conn.request('HEAD', path) response = conn.getresponse() conn.close() return response.status == 200 ...
host = url[7:sep] path = url[sep:] if not path.endswith('/'): path += "/" path += avatar if url_exists(host, path): return "http://" + host + path else: return False def gravatar(email): url = "http://www.gravatar.com/avatar.php?" url += urlencode({'grav...
t avatar: avatar = gravatar(email) return avatar def logo(url): logo = pavatar(url, "logo.png") if not logo: logo = config.prefix + "/static/img/project.png" return logo
shahsaifi/handystuff
wc.py
Python
unlicense
388
0.03866
imp
ort sys def linecount(filename): return len(open(filename).readlines()) def wordcount(filename): return len(open(filename).read().split()) def charcount(filename): return len(open(filename).read()) def main(): filename = sys.argv[1] print linecount(filename), wordcount(filename), charco...
name if __name__ == "__main__": main()
trep/opentrep
test/i18n/utf8/pyutf8.py
Python
lgpl-2.1
263
0.007605
#!/usr/bin/python charList = [ '\xd
9', '\x83', '\xd8', '\xa7', '\xd9', '\x81', '\x20', '\xd8', '\xa7', '\xd9', '\x84', '\xd8', '\xac', '\xd8', '\xa7', '\xd8', '\xb9', '\x00' ] location = '' lo
cation = ''.join(charList) print location
sdoran35/hate-to-hugs
venv/lib/python3.6/site-packages/nltk/classify/decisiontree.py
Python
mit
12,314
0.002193
# Natural Language Toolkit: Decision Tree Classifiers # # Copyright (C) 2001-2017 NLTK Project # Author: Edward Loper <[email protected]> # URL: <http://nltk.org/> # For license information, see LICENSE.TXT """ A classifier model that decides which label to assign to a token on the basis of a tree structure, where bra...
@staticmethod def leaf(labeled_featuresets): label = FreqDist(label for (featureset, label) in labeled_featuresets).max() return Decisio
nTreeClassifier(label) @staticmethod def stump(feature_name, labeled_featuresets): label = FreqDist(label for (featureset, label) in labeled_featuresets).max() # Find the best label for each value. freqs = defaultdict(FreqDist) # freq(label|value) for f...
ProfessorX/Config
.PyCharm30/system/python_stubs/-1247972723/samba/dcerpc/netlogon/netr_ChangeLogEntry.py
Python
gpl-2.0
1,801
0.007773
# encoding: utf-8 # module samba.dcerpc.netlogon # from /usr/lib/python2.7/dist-packages/samba/dcerpc/netlogon.so # by generator 1.135 """ netlogon DCE/RPC """ # imports import dcerpc as __dcerpc import talloc as __talloc class netr_ChangeLogEntry(__talloc.Object): # no doc def __init__(self, *args, **kwargs...
# default object_rid = property(lambda self: object(), lambda self, v: None, lambda self: None) # default serial_number1 = property(lambda self: object(), lambda self, v: None, lambda self: None) # default serial_number2 = property(lambda self: object(), lambda self, v:
None, lambda self: None) # default
b0ttl3z/SickRage
sickbeard/clients/generic.py
Python
gpl-3.0
12,050
0.002656
# coding=utf-8 # URL: https://sickrage.github.io # # This file is part of SickRage. # # SickRage 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 late...
return False def _set_torrent_label(self, result): # pylint:disable=unused-argument, no-self-use """ This should be overridden should return the True/False from the client when a torrent is set with label """ return True def _set_torrent_ratio(self, result): # pylint:...
overridden should return the True/False from the client when a torrent is set with ratio """ return True def _set_torrent_seed_time(self, result): # pylint:disable=unused-argument, no-self-use """ This should be overridden should return the True/False from the client ...
tongxindao/shiyanlou
shiyanlou_cs869/ershoufang_info/pic.py
Python
apache-2.0
766
0.001475
# _*_ coding: utf-8 _*_ # filename: pic.py import csv import numpy import matplotlib.pyplot as plt # 读取 house.csv 文件中价格和面积列 price, size = numpy.loadtxt('house.csv', delimiter='|'
, usecols=(1, 2), unpack=True) print price print size plt.figure() plt.subplot(211) # plt.title("price") plt.title("/ 10000RMB") plt.hist(price, bins=20) plt.subplot(212) # plt.title("area") plt.xlabel("/ m**2") plt.hist(size, bins=20) plt.figure(2) plt.title("price") plt.plot(price) plt.show() # 求价格和面积的平均值 price...
y.mean(price) size_mean = numpy.mean(size) # 求价格和面积的方差 price_var = numpy.var(price) size_var = numpy.var(size) print "价格的方差为:", price_var print "面积的方差为:", size_var
stiphyMT/plantcv
plantcv/plantcv/rectangle_mask.py
Python
mit
2,816
0.002841
# Make masking rectangle import cv2 import numpy as np import os from plantcv.plantcv import fatal_error from plantcv.plantcv import print_image from plantcv.plantcv import plot_image from plantcv.plantcv import params def rectangle_mask(img, p1, p2, color="black"): """Takes an input image and ret
urns a binary imag
e masked by a rectangular area denoted by p1 and p2. Note that p1 = (0,0) is the top left hand corner bottom right hand corner is p2 = (max-value(x), max-value(y)). Inputs: img = RGB or grayscale image data p1 = point 1 p2 = point 2 color = black,white, or gray R...
rgayon/plaso
tests/parsers/sqlite_plugins/mac_notes.py
Python
apache-2.0
1,683
0.002377
# -*- coding: utf-8 -*- """Tests for mac notes plugin.""" from __future__ import unicode_literals import unittest from plaso.lib import definitions from plaso.parsers.sqlite_plugins import mac_notes from tests.parsers.sqlite_plugins import test_lib class MacNotesTest(test_lib.SQLitePluginTestCase): """Tests for ...
stamp, '2014-02-11 02:38:27.097813') self.assertEqual( event.timestamp_desc, definitions.TIME_DESCRIPTION_CREATION) event_data = self._GetEventDataOfEvent(storage_writer, event) expected_title = 'building 4th brandy gibs' self.assertEqual(event_data.title, expected_title) expected_text = (...
nd heating claim#123456 Small ' 'business ') self.assertEqual(event_data.text, expected_text) expected_short_message = 'title:{0:s}'.format(expected_title) expected_message = 'title:{0:s} note_text:{1:s}'.format( expected_title, expected_text) self._TestGetMessageStrings( event...
graingert/alembic
alembic/operations/ops.py
Python
mit
69,224
0.000058
from .. import util from ..util import sqla_compat from . import schemaobj from sqlalchemy.types import NULLTYPE from .base import Operations, BatchOperations import re class MigrateOperation(object): """base class for migration command and organization objects. This system is part of the operation extensibi...
types = { "unique_constraint": "unique", "foreign_key_constraint": "foreignkey", "primary_key_constraint": "primary", "check_constraint": "check", "column_check_constraint": "check", } constraint_table = sqla_compat._table_for_co
nstraint(constraint) return cls( constraint.name, constraint_table.name, schema=constraint_table.schema, type_=types[constraint.__visit_name__], _orig_constraint=constraint ) def to_constraint(self): if self._orig_constraint is not...
p-morais/rl
rl/utils/plotting.py
Python
mit
1,503
0.001331
"""This screws up visualize.py""" """ import numpy as np from matplotlib import pyplot as plt from matplotlib.lines import Line2D from torch.autograd import Variable as Var from torch import Tensor class RealtimePlot(): def __init__(self, style='ggplot'): plt.style.use(style) plt.ion() se...
ax.add_line(self.line) def config(self, ylabel, xlabel): self.ax.set_ylabel(ylabel) self.ax.set_xlabel(xlabel) self.fig.tight_layout() def plot(self, y): self.yvals.append(y) self.line.set_data(np.arange(len(self.yvals)), self.yvals) self.ax.relim() sel...
vents() def done(self): plt.ioff() plt.show() def policyplot(env, policy, trj_len): obs_dim = env.observation_space.shape[0] action_dim = env.action_space.shape[0] y = np.zeros((trj_len, action_dim)) X = np.zeros((trj_len, obs_dim)) obs = env.reset() for t in range(trj_l...
nieklinnenbank/FreeNOS
support/scons/autoconf.py
Python
gpl-3.0
3,238
0.005868
# # Copyright (C) 2010 Niek Linnenbank # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed...
(int argc, char **argv)" \ "{" \ " return 0;" \ "}\n" # Try to compile and link it. result = context.TryLink(source_file, '.c') # Return the result status. context.Result(result) return result # # Checks if the compiler in the given en
vironment supports # the given command-line CFLAGS, and unsets it if not. # # Thanks to loonycyborg on #scons for his help! # def CheckCCFlags(env): cflags = env['_CCFLAGS'][:] # Loop all CFLAGS. for flag in cflags: # Setup a temporary environment. conf = Configure(env.Clone(), ...
summer1988/pythunder
pythunder/libs/dispatch/dispatcher.py
Python
lgpl-3.0
11,389
0.001317
import sys import threading import warnings import weakref import six if six.PY2: from .weakref_backports import WeakMethod else: from weakref import WeakMethod from six.moves import range def _make_id(target): if hasattr(target, '__func__'): return (id(target.__self__), id(target.__func__)) ...
elf.sender_receivers_cache.get(sender) is NO_RECEIVERS: return responses # Call each receiver with whatever arguments it can accept. # Return a list of tuple pairs [(receiver, response), ... ]. for receiver in self._live_
receivers(sender): try: response = receiver(signal=self, sender=sender, **named) except Exception as err: if not hasattr(err, '__traceback__'): err.__traceback__ = sys.exc_info()[2] responses.append((receiver, err)) ...
DaveA50/lbry
lbrynet/create_network.py
Python
mit
2,692
0.004086
#!/usr/bin/env python # # This library is free software, distributed under the terms of # the GNU Lesser General Public License Version 3, or any later version. # See the COPYING file included in this archive # # Thanks to Paul Cannon for IP-address resolution functions (taken from aspn.activestate.com) import argpar...
to automatically determine the system's IP address, but this may " "result in the nodes being reachable only from this system") args = parser.parse_args() global amount amount = args.amount_of_nodes if args.nic_ip_address: ipAddress = args.nic_ip_address else: ...
itted; using %s...' % ipAddress startPort = 4000 port = startPort+1 nodes = [] print 'Creating Kademlia network...' try: nodes.append(os.spawnlp(os.P_NOWAIT, 'lbrynet-launch-node', 'lbrynet-launch-node', str(startPort))) for i in range(amount-1): time.sleep(0.15) ...
clovis/PhiloLogic4
www/scripts/get_notes.py
Python
gpl-3.0
1,038
0.009634
#!/usr/bin/env python3 import json import os from wsgiref.handlers import CGIHandler from philologic.runtime.DB import DB from philologic.runtime import generate_text_object import sys sys.path.app
end("..") import custom_functions try: from custom_functions import WebConfig except ImportError: from philologic.runtime import WebConfig try: from custom_functions import WSGIHandler except ImportError: from philologic.runtime import WSGIHandler def get_notes(environ, start_response): st
atus = '200 OK' headers = [('Content-type', 'application/json; charset=UTF-8'), ("Access-Control-Allow-Origin", "*")] start_response(status, headers) config = WebConfig(os.path.abspath(os.path.dirname(__file__)).replace('scripts', '')) db = DB(config.db_path + '/data/') request = WSGI...
ghostcode/django-blog
blogproject/blog/models.py
Python
mit
3,967
0.002287
from django.db import models from django.contrib.auth.models import User from django.urls import reverse class Category(models.Model): """ Django 要求模型必须继承 models.Model 类。 Category 只需要一个简单的分类名 name 就可以了。 CharField 指定了分类名 name 的数据类型,CharField 是字符型, CharField 的 max_length 参数指定其最大长度,超过这个长度的分类名就不能被存入数据库...
project.com/en/1.10/topics/db/models/#relationships category = models.ForeignKey( Category, on_delete=models.CASCADE, ) tags = models.ManyToManyField(Tag, blank=True) # 文章作者,这里 User 是从 django.contrib.auth.mo
dels 导入的。 # django.contrib.auth 是 Django 内置的应用,专门用于处理网站用户的注册、登录等流程,User 是 Django 为我们已经写好的用户模型。 # 这里我们通过 ForeignKey 把文章和 User 关联了起来。 # 因为我们规定一篇文章只能有一个作者,而一个作者可能会写多篇文章,因此这是一对多的关联关系,和 Category 类似。 author = models.ForeignKey( User, on_delete=models.CASCADE, ) def __str__(self): ...
lodemo/CATANA
src/data_collection/sblade/sblade/spiders/makerstudio.py
Python
mit
3,250
0.006154
# -*- coding: utf-8 -*- # MIT License # # Copyright (c) 2017 Moritz Lode # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to...
youtube/s/\?q=(.+)$') links = response.css('a').xpath('@href').extr
act() for ref in links: m = p.match(ref) if m: self.channelIDs.add(m.groups()[0]) if self.i <= self.MAX_ITERATION: self.i = self.i + 1 yield scrapy.Request(response.url, callback=self.parse, dont_filter=True) else: ...
vbannai/neutron
neutron/db/migration/alembic_migrations/versions/24c7ea5160d7_cisco_csr_vpnaas.py
Python
apache-2.0
2,012
0.001491
# Copyright 2014 Cisco Systems, 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 requir...
er the License. """Cisco CSR VPNaaS Revision ID: 24c7ea5160d7 Revises: 492a106273f8 Create Date: 2014-02-03 13:06:50.407601 """ # revision identifiers, us
ed by Alembic. revision = '24c7ea5160d7' down_revision = '492a106273f8' # Change to ['*'] if this migration applies to all plugins migration_for_plugins = [ 'neutron.services.vpn.plugin.VPNDriverPlugin', ] from alembic import op import sqlalchemy as sa from neutron.db import migration def upgrade(active_plugi...
aitjcize/micropython
tests/io/file1.py
Python
mit
79
0
f = open
("io/data/file1") print(f.read(5)) print(f.readline(
)) print(f.read())
openbudgets/openbudgets
openbudgets/apps/accounts/admin.py
Python
bsd-3-clause
2,240
0.003125
from django.conf import settings from django.contrib import admin from django.contrib.auth.models import Group from django.contrib.sites.models import Site from django.contrib.auth.admin import UserAdmin from django.utils.translation import ugettext_lazy as _ from registration.models import RegistrationProfile from ope...
ntAdmin): """Admin form for Public users""" def
queryset(self, request): public_users = Group.objects.filter(id=settings.OPENBUDGETS_GROUP_ID_PUBLIC) qs = super(PublicAccountAdmin, self).get_queryset(request) qs = qs.filter(groups=public_users) return qs # Django Auth admin config admin.site.unregister(Group) # Django Sites admin c...
klim-/pyplane
core/Toolbar.py
Python
gpl-3.0
1,723
0.00058
# -*- coding: utf-8 -*- # Copyright (C) 2013 # by Klemens Fritzsche, [email protected] # # 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 # ...
y1 = height - y1 y0 = height - y0 w = abs(x1 - x0) h = abs(y1 - y0) rect = [int(val) for val in mi
n(x0, x1), min(y0, y1), w, h] self.canvas.drawRectangle(rect) def set_cursor(self, cursor): QtGui.QApplication.restoreOverrideCursor() QtGui.QApplication.setOverrideCursor(QtGui.QCursor(cursord[cursor])) if __package__ is None: __package__ = "core.toolbar"
noemis-fr/old-custom
e3z_report_ipbox/report/report_account_invoice_layout.py
Python
agpl-3.0
8,491
0.007066
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU...
ll 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 copy of the GNU Affero General Public License # along with this program. If
not, see <http://www.gnu.org/licenses/>. # ############################################################################## import time from report import report_sxw from lxml import etree from openerp.osv import osv,fields from openerp.tools.translate import _ class account_invoice_1(report_sxw.rml_parse): def __...
BhallaLab/moose-core
pymoose/__init__.py
Python
gpl-3.0
613
0.003263
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_
function # Bring everything from c++ module to global namespace. from moose._moose import * # Bring everything from moose.py to
global namespace. # IMP: It will overwrite any c++ function with the same name. We can override # some C++ here. from moose.moose import * from moose.server import * # SBML and NML2 support. from moose.model_utils import * # create a shorthand for version() call here. __version__ = version() # C++ core override fr...
1ukash/horizon
horizon/dashboards/admin/networks/panel.py
Python
apache-2.0
938
0.001066
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012 NEC Corporation # # 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 #...
UT # 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 django.utils.translation import ugettext_lazy as _ import horizon from horizon.dashboards.admin import dashboard class Networks(h...
ug = 'networks' permissions = ('openstack.services.network',) dashboard.Admin.register(Networks)
edx/edx-enterprise
integrated_channels/sap_success_factors/exporters/learner_data.py
Python
agpl-3.0
9,167
0.003382
# -*- coding: utf-8 -*- """ Learner data exporter for Enterprise Integrated Channel SAP SuccessFactors. """ from logging import getLogger from requests import RequestException from django.apps import apps from enterprise.models import EnterpriseCustomerUser, PendingEnterpriseCustomerUser from enterprise.tpa_pipelin...
nty about the type of content (course vs. course run) that was sent to the integrated channel. course_run = get_course_run_for_enrollment(enterprise_enrollment
) total_hours = 0.0 if course_run and self.enterprise_configuration.transmit_total_hours: total_hours = course_run.get("estimated_hours", 0.0) return [ SapSuccessFactorsLearnerDataTransmissionAudit( enterprise_course_enrollment_id=e...
smacfiggen/horus
revert_osiris.py
Python
unlicense
6,871
0.007131
from __future__ import print_function import httplib2 import io import os import sys import time import dateutil.parser from apiclient import discovery from oauth2client import client from oauth2client import tools from oauth2client.file import Storage from apiclient.http import MediaIoBaseDownload import pprint #Ch...
credentials = tools.run_flow(flow, store, flags) else: # Needed only for compatibility with Python 2.6 credentials = tools.run(flow, store) print('Storing credentials to ' + credential_path) return credentials def main(): credentials = get_credentials() http = credentia...
first batch of possible infected files results = service.files().list(pageSize=1, fields="nextPageToken, files(id, name)").execute() items = results.get('files', []) next_page = results.get('nextPageToken', None) bad_files = [] done = False next_page = None ...
balajikris/autorest
src/generator/AutoRest.Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/date_wrapper.py
Python
mit
878
0
# 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 ...
eWrapper(Model): """DateWrapper. :param field: :type field: date :param leap: :type leap: date """ _attribute_map = { 'field': {'key': 'field', 'type': 'date'}, 'leap': {'key': 'leap', 'type': 'date'}, } def
__init__(self, field=None, leap=None): self.field = field self.leap = leap
IvanMalison/okcupyd
okcupyd/profile.py
Python
mit
14,154
0.001413
import datetime import logging from lxml import html import simplejson from . import details from . import essay from . import helpers from . import looking_for from . import util from .question import QuestionFetcher from .xpath import xpb log = logging.getLogger(__name__) class Profile(object): """Represent...
'ajax': 1, 'sendmsg': 1, 'r1': self.username, 'body': content, 'threadid': thread_id, 'authcode': self.authcode, 'reply': 1 if thread_id else 0, 'from_profile': 1
} @util.cached_property def authcode(self): return helpers.get_authcode(self.profile_tree) _photo_info_xpb = xpb.div.with_class('photo').img.select_attribute_('src') @util.cached_property def photo_infos(self): """ :returns: list of :class:`~okcupyd.photo.Info` instance...
liosha2007/temporary-groupdocs-python3-sdk
groupdocs/models/ChangePasswordResult.py
Python
apache-2.0
920
0.006522
#!/usr/bin/env
python """ Copyright 2012 GroupDocs. 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 g...
SickGear/SickGear
sickbeard/metadata/generic.py
Python
gpl-3.0
53,307
0.003114
# Author: Nic Wolfe <[email protected]> # URL: http://code.google.com/p/sickbeard/ # # This file is part of SickGear. # # SickGear 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,...
distributed in the hope that it will be useful, # but WITHOUT ANY WAR
RANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with SickGear. If not, see <http://www.gnu.org/licenses/>. from __future__ import wit...
ContinuumIO/multiuserblazeserver
build.py
Python
bsd-3-clause
1,553
0.006439
import os from os.path import join, getctime, dirname import glob import subprocess import argparse def newest_file(root): path = join(root, "*tar.bz2") newest = max(glob.iglob(path), key=getctime) return newest def upload(pkg, user): cmd = ["binstar", "upload", "--force","-u", user, pkg] subproce...
if binstar_user: upload(pkg, binstar_user) for plat in platforms:
cmd = ["conda", "convert", "-p", plat, pkg] subprocess.check_call(cmd) if binstar_user: to_upload = newest_file(plat) upload(to_upload, binstar_user) if __name__ == "__main__": p = argparse.ArgumentParser() p.add_argument("build_dir") p.add_a...
unikmhz/npui
netprofile/netprofile/alembic/env.py
Python
agpl-3.0
8,705
0
#!/usr/bin/env python # -*- coding: utf-8 -*- # # NetProfile: DB migrations environment for Alembic # Copyright © 2016-2017 Alex Unigovsky # # This file is part of NetProfile. # NetProfile is free software: you can redistribute it and/or # modify it under the terms of the GNU Affero General Public # License as publishe...
efault, DefaultClause): meta_arg = meta_default.arg if isinstance(meta_arg, npf.npbool): proc = meta_col.type.result_processor(context.dialect, types.Unicode) insp_
default = insp_default.strip('\'') if proc: insp_default = proc(insp_default) return meta_arg.val != insp_default elif isinstance(meta_arg, TextClause): meta_text = meta_arg.text if meta_text.upper() == 'NULL' and insp_default is None: ...
acfogarty/espressopp
bench/polymer_melt/espressopp/espressopp_polymer_melt.py
Python
gpl-3.0
5,227
0.006122
#!/usr/bin/env python # -*- coding: iso-8859-1 -*- ########################################################################### # # # ESPResSo++ Benchmark Python script for a polymer melt # # ...
P Pxy etotal ekinetic epair ebond eangle\n') sys.stdout.write(fmt % (0, T, P, Pij[3], Etotal, Ek, Ep, Eb, Ea)) start_time = time.clock() integrator.run(steps) end_time = time.clock() T = temperature.compute() P = pressure.compute() Pij = pressureTensor.compute() Ek = 0.5 * T ...
icles) Ep = interLJ.computeEnergy() Eb = interFENE.computeEnergy() Ea = interCosine.computeEnergy() Etotal = Ek + Ep + Eb + Ea sys.stdout.write(fmt % (steps, T, P, Pij[3], Etotal, Ek, Ep, Eb, Ea)) sys.stdout.write('\n') # print timings and neighbor list information timers.show(integrator.getTimers(), precision=2) sys....
olemb/mido
extras/hid_joystick.py
Python
mit
6,820
0.000733
"""Read from /dev/input/js0 and return as dictionaries
. If yo
u have pygame it is easier and more portable to do something like:: import pygame.joystick from pygame.event import event_name pygame.init() pygame.joystick.init() js = pygame.joystick.Joystick(0) js.init() while True: for event in pygame.event.get(): if event.axis ==...
jeremiahyan/odoo
addons/payment_alipay/models/payment_transaction.py
Python
gpl-3.0
7,132
0.002944
# Part of Odoo. See LICENSE file for full copyright and licensing details. import logging from werkzeug import urls from odoo import _, api, models from odoo.exceptions import ValidationError from odoo.tools.float_utils import float_compare from odoo.addons.payment_alipay.controllers.main import AlipayController _...
raise ValidationError( "Alipay: " + _( "Received data with missing reference %(r)s or txn_id %(t)s.", r=reference, t=txn_id ) ) tx = self.search([('reference', '=', reference), ('provider', '=', 'alipay')]) if not tx: ...
need the reference to get the acquirer) sign_check = tx.acquirer_id._alipay_build_sign(data) sign = data.get('sign') if sign != sign_check: raise ValidationError( "Alipay: " + _( "Expected signature %(sc) but received %(sign)s.", sc=sign_check, sig...
adsabs/biblib-service
biblib/tests/functional_tests/test_returned_data_epic.py
Python
mit
14,756
0.000339
""" Functional test Returned Data Epic Storyboard is defined within the comments of the program itself """ import time import unittest from datetime import datetime, timedelta from flask import url_for from biblib.tests.stubdata.stub_data import UserShop, LibraryShop from biblib.tests.base import MockEmailService, T...
self.assertEqual(library['public'], False) self.assertEqual(library['owner'], user_dave.email.split('@')[0]) date_created = datetime.strptime(library['date_created'], '%Y-%m-%dT%H:%M:%S.%f') date_last_modified = datetime.strptime(library['date_last_mod...
date_last_modified, delta=timedelta(seconds=1)) # Dave adds content to his library number_of_documents = 20 for i in range(number_of_documents): # Stub data library = LibraryShop() # Add document url = ...
sapo/python-kyototycoon
tests/config.py
Python
bsd-3-clause
271
0
#!/usr/bin/env python # # Copyright 2011, Toru Maesaka # # Redistr
ibution and use of this source code is licensed under # the BSD license. See COPYING file for license description. import os import sys sys.path.insert(0, os.path.join(os.path.split(__file__)[0],
'..'))
rinsewester/SchemaViz
edge.py
Python
mit
15,908
0.006726
#!/usr/bin/python3 # -*- coding: utf-8 -*- """ Widget to display simulation data of a CSDF graph. author: Sander Giesselink """ from PyQt5.QtWidgets import QGraphicsItem, QInputDialog, QMessageBox from PyQt5.QtCore import Qt, QRectF, QPointF from PyQt5.QtGui import QColor, QPen, QBrush, QPainterPath, QF...
lf.curvePoint1.y() + yTranslation) curvePoint2
= QPointF(self.curvePoint2.x()+4, self.curvePoint2.y() + yTranslation) endPoint = QPointF(self.endPoint.x(), self.endPoint.y() + yTranslation) path = QPainterPath(beginPoint) point1 = QPointF(curvePoint1.x(), curvePoint1.y()) point2 = QPointF(curvePoint2.x(), curvePoint2.y()) ...
EnEff-BIM/EnEffBIM-Framework
SimModel_Python_API/simmodel_swig/Release/SimModel_PyCallBack.py
Python
mit
9,889
0.005157
# This file was automatically generated by SWIG (http://www.swig.org). # Version 3.0.7 # # Do not make changes to this file unless you know what you are doing--modify # the SWIG interface file instead. from sys import version_info if version_info >= (2, 6, 0): def swig_import_helper(): from os.path imp...
bId in range(0, _objList.sizeInt()): self._dict[_objList.at(subId).RefId()] = _objList.at(subId) def loadSimGeomClassObj(self, _geomDataName, _simGeomClassList): if self._simGeom == None: self._simGeom = SimModel.SimModel_(_geomDataName) for id in range(0, _simGeomClassLi...
st = getattr(self._simGeom, _simGeomClassList[id])() for subId in range(0, _objList.sizeInt()): self._dict[_objList.at(subId).RefId()] = _objList.at(subId) def loadSimSysClassObj(self, _sysDataName, _simSysClassList): if self._
SavenR/Bingether
app/admin.py
Python
artistic-2.0
250
0
fr
om django.contrib import admi
n from .models import personalBinge from .models import Bingether from .models import Comment # Register your models here. admin.site.register(personalBinge) admin.site.register(Bingether) admin.site.register(Comment)
dbrattli/RxPY
rx/linq/observable/ignoreelements.py
Python
apache-2.0
587
0
from rx import Observable, AnonymousObservable from rx.internal import noop from rx.internal import extensionmethod @extensionmethod(Observable) def ignore_elements(self): """Ignores all elements in an observable sequence leavin
g only the termination messages. Returns an empty observable {Observable} sequence that signals termination, successful or exceptional, of the source sequence. """ source = self def subscribe(observer): return source.subscribe(noop, observer.on_error, observer.on_completed)
return AnonymousObservable(subscribe)
streamlink/streamlink
tests/plugins/test_sportschau.py
Python
bsd-2-clause
411
0.004866
from streamlink.plugins.sportschau import Sportschau from tests.plugins import PluginCanHandleUrl c
lass TestPluginCanHandleUrlSportschau(PluginCanHandleUrl): __plugin__ = Sportschau should_match = [ 'http://www.sportschau.de/wintersport/videostream-livestream---wintersport-im-ersten-242.html',
'https://www.sportschau.de/weitere/allgemein/video-kite-surf-world-tour-100.html', ]
d3banjan/polyamide
webdev/lib/python2.7/site-packages/pagedown/widgets.py
Python
bsd-2-clause
2,219
0.002253
from django import forms from django.contrib.admin import widgets as admin_widgets from django.forms.widgets import flatatt from django.utils.html import conditional_escape from django.template.loader import render_to_string from pagedown import settings as pagedown_settings from pagedown.utils import compatible_stati...
js'), compatible_staticpath('pagedown_init.js'), )) media = property(_media) def render(self, name, value, attrs=None): if value is None: value = '' if 'class' not in attrs: attrs['class'] = "" attrs['class'] += " wmd-input" fi...
att(final_attrs), 'body': conditional_escape(force_unicode(value)), 'id': final_attrs['id'], 'show_preview': self.show_preview, }) class AdminPagedownWidget(PagedownWidget, admin_widgets.AdminTextareaWidget): class Media: css = { 'all': (compatible_...
rouxcode/django-cms-plugins
cmsplugins/sliders/migrations/0008_auto_20190823_1324.py
Python
mit
977
0.003071
# Generated by Django 2.1.11 o
n 2019-08-23 11:24 from django.db import migrations, models import django.db.models.deletio
n class Migration(migrations.Migration): dependencies = [ ('sliders', '0007_slide_name_sub'), ] operations = [ migrations.AlterField( model_name='link', name='plugin', field=models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletio...
vpv11110000/pyss
other/binominal.py
Python
mit
4,240
0.018462
##!/usr/bin/python # -*- coding: utf-8 -*- """ Две модели биноминального распределения (N=2 и N=40) Запуск: python ./binominal.py Пример визуализации возникновения событий в соответствии с биноминальным распределением. Биномиальное распределение представляется как сумма исходов событий, которые следуют распреде...
#генерится см. mf() Generate(sgm, med_value=0, modificatorFunc=mf,first_tx=0, max_amount=1000) Tabulate(sgm, table=m.getTables()[0],valFunc=valFunc_T_1
) Terminate(sgm, deltaTerminate=0) # m.initPlotTable(title=CAPTION) # m.start(terminationCount=MAX_TIME, maxTime=MAX_TIME) # m.plotByModulesAndSave(CAPTION) m.plotByModulesAndShow() if __name__ == '__main__': main(N=2) main(N=40)
kgao/MediaDrop
mediadrop/plugin/tests/events_test.py
Python
gpl-3.0
2,599
0.005387
# This file is a part of MediaDrop (http://www.mediadrop.net), # Copyright 2009-2014 MediaDrop contributors # For the exact contribution history, see the git revision log. # The source code contained in this file is licensed under the GPLv3 or # (at your option) any later version. # See LICENSE.txt in the main project ...
elf.event.pre_observers.append(self.probe) assert_equals(0, self.observers_called) self.event() assert_equals(2, self.observers_called) class FetchFirstResultEventTest(PythonicTestCase): def test_returns_first_non_null_result(self): event = FetchFirstResultEvent([]) ...
rvers.append(lambda: 2) assert_equals(1, event()) def test_passes_all_event_parameters_to_observers(self): event = FetchFirstResultEvent([]) event.post_observers.append(lambda foo, bar=None: foo) event.post_observers.append(lambda foo, bar=None: bar or foo) ...
alexkasko/krakatau-java
krakatau-lib/src/main/resources/Lib/Krakatau/verifier/verifier_types.py
Python
gpl-3.0
4,399
0.01273
import collections #Define types for Inference nt = collections.namedtuple fullinfo_t = nt('fullinfo_t', ['tag','dim','extra']) #Differences from Hotspot with our tags: #BOGUS changed to None. Array omitted as it is unused. Void omitted as unecessary. Boolean added valid_tags = ['.'
+_x for _x in 'int float double double2 long long2 obj new init address byte short char boolean'.split()] valid_tags = frozenset([None] + valid_tags) def _makeinfo(tag, dim=0, extra=None): assert(tag in valid_tags) return fullinfo_t(tag, dim, extra) T_INVALID = _makeinfo(None) T_INT = _makeinfo('.int') T_FLOA...
keinfo('.double') T_DOUBLE2 = _makeinfo('.double2') #Hotspot only uses these in locals, but we use them on the stack too to simplify things T_LONG = _makeinfo('.long') T_LONG2 = _makeinfo('.long2') T_NULL = _makeinfo('.obj') T_UNINIT_THIS = _makeinfo('.init') T_BYTE = _makeinfo('.byte') T_SHORT = _makeinfo('.short') ...