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 |
|---|---|---|---|---|---|---|---|---|
siosio/intellij-community | python/testData/mover/multiLineSelectionDifferentIndentLevelsMoveToEmptyLine_afterDown.py | Python | apache-2.0 | 74 | 0.081081 | pass
<caret | ><selection>n = 0
while n:
print("sp | am")</selection>
pass |
CloudBoltSoftware/cloudbolt-forge | blueprints/azure_functions/create.py | Python | apache-2.0 | 3,475 | 0.007194 | """
Creates an Azure serverless function.
"""
from common.methods import set_progress
from infrastructure.models import CustomField
from common.methods import generate_string_from_template
import os, json
def create_custom_fields_as_needed():
CustomField.objects.get_or_create(
name='azure_function_name', ... | rmat(storage_account_name, resource_group_name)
os.system(create_storage_command)
| else:
return "failure", '{0}'.format(name_check_response['reason']), ""
#create the azure function
create_function_command = "az functionapp create --name " + function_name + " --storage-account " + storage_account_name + " --consumption-plan-location westeurope --resource-group " + resource_group_nam... |
nijel/weblate | weblate/addons/apps.py | Python | gpl-3.0 | 905 | 0 | #
# Copyright © 2012–2022 Michal Čihař <michal@cihar.com>
#
# This file is part of Weblate <https://weblate.org/>
#
# 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 Licens... | sion.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
... | name = "weblate.addons"
label = "addons"
verbose_name = "Add-ons"
|
gregbdunn/aws-ec2rescue-linux | tools/moduletests/unit/test_arpcache.py | Python | apache-2.0 | 12,661 | 0.003001 | # Copyright 2016-2020 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
#
# or in the "license" f... | cache.open", mock.mock_open(read_data="net.ipv4.neigh.default.gc_thresh1 = | 0\n"
"net.ipv4.neigh.default.gc_thresh1 = 0\n"))
def test_fix_sudo_true_found_twice(self, check_output_mock, exists_mock):
check_output_mock.return_value = "True"
with contextlib.redirect_stdout(self.output):
self.... |
demianw/tract_querier | tract_querier/tensor/tests/test_scalar_measures.py | Python | bsd-3-clause | 2,117 | 0.000945 | from .. import scalar_measures
import numpy
from numpy.testing import assert_array_almost_equal
def test_fractional_anisotropy(N=10, random=numpy.random.RandomState(0)):
tensors = random.randn(N, 3, 3)
fa = numpy.empty(N)
for i, t in enumerate(tensors):
tt = numpy.dot(t, t.T)
| tensors[i] = tt
ev = numpy.linalg.eigvalsh(tt)
mn = ev.mean()
fa[i] = numpy.sqrt(1.5 * ((ev - mn) ** 2).sum() / (ev ** 2).sum())
assert_array_almost_equal(fa, scalar_measures.fractional_anisotropy(tensors))
def test_volume_fraction(N=10, random=numpy.random.RandomState(0)):
tensors = ... | tensors):
tt = numpy.dot(t, t.T)
tensors[i] = tt
ev = numpy.linalg.eigvalsh(tt)
mn = ev.mean()
vf[i] = 1 - ev.prod() / (mn ** 3)
assert_array_almost_equal(vf, scalar_measures.volume_fraction(tensors))
def test_tensor_determinant(N=10, random=numpy.random.RandomState(0)):
... |
jokajak/itweb | data/env/lib/python2.6/site-packages/SQLAlchemy-0.6.7-py2.6.egg/sqlalchemy/dialects/oracle/base.py | Python | gpl-3.0 | 43,930 | 0.005304 | # oracle/base.py
# Copyright (C) 2005-2011 the SQLAlchemy authors and contributors <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""Support for the Oracle database.
Oracle version 8 through current (11g at the time ... | flag should be left off.
"""
import random, re
from sqlalchemy import schema as sa_schema
from sqlalchemy import util, sql, log
from sqlalchemy.engine import de | fault, base, reflection
from sqlalchemy.sql import compiler, visitors, expression
from sqlalchemy.sql import operators as sql_operators, functions as sql_functions
from sqlalchemy import types as sqltypes
from sqlalchemy.types import VARCHAR, NVARCHAR, CHAR, DATE, DATETIME, \
BLOB, CLOB, TIMESTAMP, FLOA... |
impactlab/eemeter | eemeter/modeling/split.py | Python | mit | 7,118 | 0.000281 | import logging
import traceback
import numpy as np
from eemeter.structures import EnergyTrace
logger = logging.getLogger(__name__)
class SplitModeledEnergyTrace(object):
''' Light wrapper around models applicable to a single trace which
fits and predicts multiple models for different segments.
Paramet... | ----------
| modeling_period_label : str
Label for modeling period for which derivative should be computed.
derivative_callable : callable
Callable which can be used as follows:
.. code-block: python
>>> derivative_callable(formatter, model, **kwargs)
**kwargs
... |
arunhotra/tensorflow | tensorflow/python/framework/random_seed.py | Python | apache-2.0 | 4,427 | 0.002259 | """For seeding individual ops based on a graph-level seed.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.framework import ops
_DEFAULT_GRAPH_SEED = 87654321
def get_seed(op_seed):
"""Returns the local seeds an operation sh... | print sess1.run(a) # generates 'A1'
print sess1.run(a) # generates 'A2'
print sess1.run(b) # generates 'B1'
print sess1.run(b) # generates 'B2'
print "Session 2"
with tf.Session() as sess2:
print sess2.run(a) # generates 'A1'
print sess2.run(a) # generates 'A2'
print sess2.run(b) #... | Args:
seed: integer.
"""
ops.get_default_graph().seed = seed
|
Unallocated/UAS_IRC_Bot | modules/address.py | Python | gpl-3.0 | 195 | 0.010256 | def address(self, data): |
self.irc.send(self.privmsg("512 Sha | w Court #105, Severn, MD 21144"))
|
rackerlabs/django-DefectDojo | dojo/api_v2/prefetch/utils.py | Python | bsd-3-clause | 1,916 | 0.003132 | from django.db.models.fields import related
def _is_many_to_many_relation(field):
"""Check if a field specified a many-to-many relationship as defined by django.
This is the case if the field is an instance of the ManyToManyDescriptor as generated
by the django framework
Args:
field (django.d... | lizer, "Meta", None)
if meta is None:
return []
model = getattr(meta, "model", None)
if model is None:
return []
fields = []
for field_name in dir(model):
field = getattr(model, field_name)
if _is_field_prefetchable(field):
# ManyToMany relationship can ... | reverse:
fields.append((field_name, field.field.model))
else:
fields.append((field_name, field.field.related_model))
return fields
|
unnikrishnankgs/va | venv/lib/python3.5/site-packages/jedi/evaluate/__init__.py | Python | bsd-2-clause | 26,873 | 0.001191 | """
Evaluation of Python code in |jedi| is based on three assumptions:
* The code uses as least side effects as possible. Jedi understands certain
list/tuple/set modifications, but there's no guarantee that Jedi detects
everything (list.append in different modules for example).
* No magic is being used:
- metac... | left = precedence.calculate(self, context, left, operator, t)
types = left
else:
| types = precedence.calculate(self, context, left, operator, types)
debug.dbg('eval_statement result %s', types)
return types
def eval_element(self, context, element):
if isinstance(context, iterable.CompForContext):
return self._eval_element_not_cached(context, elemen... |
satriaphd/bgc-learn | bgc-learn.py | Python | gpl-3.0 | 18,044 | 0.004434 | import os
import sys
import shutil
import straight.plugin
import numpy as np
import pkg_resources
from os import path
from core import utils
from core import argparser
from core import log
from core import parser
def main():
## Parse arguments
ap = argparser.init_arg_parser()
options = ap.parse_args()
... | if plugin.name == feature["name"]:
if len(options["features_scope"]) > 0 and plugin.scope != options["features_scope"]:
log.error("You selected fe | atures of different scope ('%s:%s', '%s:%s'). Please select only combination of features with the same scope." % (feature["name"], plugin.scope, options["features"][idx - 1]["name"], options["features_scope"]))
sys.exit(1)
options["features_scope"] = plugin.scope
brea... |
pupeng/hone | Controller/hone_lib.py | Python | bsd-3-clause | 9,045 | 0.015478 | # Copyright (c) 2011-2013 Peng Sun. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the COPYRIGHT file.
# hone_lib.py
# provide library for mgmt program to create dataflow
import inspect
from cStringIO import StringIO
import hone_rts
from hone_util import LogU... | ret += subFlow.printDataFlow()
return ret
def getFlowCriterion(self):
return self.flow[0].wh
''' query part '''
class HoneQuery:
def __init__(self,var,ft,wh,gp,every,agg,compose):
self.complete = False
self.var = var
self.ft = ft
self.wh = wh
sel... | rshift__(self, other):
HoneQuerySyntaxCheck(self)
#debugLog('lib', 'new HoneQuery instance created', self.printQuery())
return self.convertToHoneDataFlow() >> other
def __mul__(self, other):
otherName = other.__class__.__name__
if otherName=='HoneQuery':
retu... |
tommy-u/enable | kiva/agg/tests/clip_to_rect_test_case.py | Python | bsd-3-clause | 12,045 | 0.003653 | """ Needed Tests
clip_to_rect() tests
--------------------
DONE *. clip_to_rect is inclusive on lower end and exclusive on upper end.
DONE *. clip_to_rect behaves intelligently under scaled ctm.
DONE *. clip_to_rect intersects input rect with the existing clipping rect.
DONE *. ... | -------- | -----------------------------
# Successive Clipping of multiple rectangles.
#------------------------------------------------------------------------
def successive_clip_helper(self, desired, scale,
clip_rect1, clip_rect2):
""" desired -- 2D array with a single channe... |
MungoRae/home-assistant | tests/components/test_splunk.py | Python | apache-2.0 | 3,879 | 0 | """The tests for the Splunk component."""
import unittest
from unittest import mock
from homeassistant.setup import setup_component
import homea | ssistant.components.splunk as splunk
from homeassistant.const import STATE_ON, STATE_OFF, EVENT_STATE_CHANGED
from tests.common import get_test_home_assistant
class TestSplunk(unittest.TestCase):
"""Test the Splunk component."""
def setUp(self): # pylint: disable=invalid-name
"""Setup things to be ... | ed."""
self.hass = get_test_home_assistant()
def tearDown(self): # pylint: disable=invalid-name
"""Stop everything that was started."""
self.hass.stop()
def test_setup_config_full(self):
"""Test setup with all data."""
config = {
'splunk': {
... |
darcyliu/storyboard | boto/rds/parametergroup.py | Python | mit | 7,126 | 0.002666 | # Copyright (c) 2006-2009 Mitch Garnaat http://garnaat.org/
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modi... |
#
# THE SOFTWARE IS PROVIDED "AS IS" | , WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARIS... |
lewissbaker/cake | src/cake/task.py | Python | mit | 15,540 | 0.013964 | """Task Utilities.
@see: Cake Build System (http://sourceforge.net/projects/cake-build)
@copyright: Copyright (c) 2010 Lewis Baker, Stuart McMahon.
@license: Licensed under the MIT license.
"""
import sys
import threading
_threadPool = None
_threadPoolLock = threading.Lock()
def setThreadPool(threadPool):
"""Set ... | , immediate=False, required=False, threadPool=threadPool)
def start(self, immediate=False, threadPool=None):
"""Start this task now.
@param immediate: If True the task is pushed ahead of any other (waiting)
tasks on the task queue.
@type immediate: bool
@param threadPool: If specified then ... | then the task
will be queued for execution on the default thread-pool.
@type threadPool: L{ThreadPool} or C{None}
@raise TaskError: If this task has already been started or
cancelled.
"""
self._start(other=None, immediate=immediate, required=True, threadPool=threadPool)
def startAfte... |
Antergos/whither | whither/toolkits/gtk/web_container.py | Python | gpl-3.0 | 985 | 0 | # -*- coding: utf-8 -*-
#
# web_container.py
#
# Copyright © 2016-2017 Antergos
#
# This file is part of whither.
#
# whither 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... | ithout even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# The following additional terms are in effect as per Section 7 of the license:
#
# The preservation of all legal notices and author attributions in
# the material or in t... | cense
# along with whither; If not, see <http://www.gnu.org/licenses/>.
|
scripnichenko/nova | nova/api/openstack/compute/floating_ip_pools.py | Python | apache-2.0 | 2,196 | 0 | # Copyright (c) 2011 X.commerce, a business unit of eBay 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 req... | translate_floating_ip_view(pool_name):
return {
'name': pool_name,
}
def _translate_floating_ip_pools_view(pools):
return {
'floating_ip_pools': [_translate_floating_ip_view(pool_name)
for pool_name in pools]
}
class FloatingIPPoolsController(wsgi.Contro... | PI."""
def __init__(self):
self.network_api = network.API(skip_policy_check=True)
super(FloatingIPPoolsController, self).__init__()
@extensions.expected_errors(())
def index(self, req):
"""Return a list of pools."""
context = req.environ['nova.context']
authorize(co... |
videntity/django-djmongo | djmongo/mongoutils.py | Python | gpl-2.0 | 17,724 | 0.00079 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: ai ts=4 sts=4 et sw=4
from django.conf import settings
import json
import sys
import csv
from datetime import datetime, date, time
from bson.code import Code
from bson.objectid import ObjectId
from bson.errors import InvalidId
from bson import json_util
from pymongo... | tings, 'MONGODB_CLIENT',
'mongodb://localhost:27017/')
mc = MongoClient(mongodb_client_url)
db = mc[str(database_name)]
collection = db[str(collection_name)]
# explain = db.command('aggregate', collection, pipeline=pipeline, explain=True)
# print explain
collect... | ts_dict):
return json.dumps(results_dict, indent=4, default=json_util.default)
def normalize_results(results_dict):
mydt = datetime.now()
myd = date.today()
myt = time(0, 0)
for r in results_dict['results']:
for k, v in r.items():
if isinstance(r[k], type(mydt)) or \
... |
cliftonmcintosh/openstates | openstates/mt/people.py | Python | gpl-3.0 | 7,587 | 0.001977 | import re
import csv
from urllib import parse
import lxml.html
from pupa.scrape import Person, Scraper
class NoDetails(Exception):
pass
SESSION_NUMBERS = {
'2011': '62nd',
'2013': '63rd',
'2015': '64th',
'2017': '65th',
}
class MTPersonScraper(Scraper):
def url_xpath(self, url):
#... | if phone:
legislator.add_contact_detail(type='voice', value=phone, note='District Office')
if fax:
legislator.add_contact_detail(type='fax', value=fax, note='Di | strict Office')
if email:
legislator.add_contact_detail(type='email', value=email, note='District Office')
yield legislator
def _district_legislator_dict(self):
'''Create a mapping of districts to the legislator who represents
each district in each house.
... |
purrcat259/peek | tests/unit/test_line.py | Python | mit | 1,585 | 0.001262 | import copy
import pytest
from peek.line import InvalidIpAddressException, Line, InvalidStatusException
# 127.0.0.1 - - [01/Jan/1970:00:00:01 +0000] "GET / HTTP/1.1" 200 193 "-" "Python"
test_line_contents = {
'ip_address': '127.0.0.1',
'timestamp': '[01/Jan/1970:00:00:01 +0000]',
'verb': 'GET',
... | (193, test_line.byte_count),
('-', test_line.referrer),
('Python', test_line.user_agent)
])
def test_retrieval(self, expec | ted, actual):
assert expected == actual
class TestLineExceptions:
def test_passing_invalid_ip_address_throws_exception(self):
with pytest.raises(InvalidIpAddressException):
line = Line(line_contents=get_updated_line_contents({'ip_address': 'foobar'}))
def test_passing_non_parseabl... |
liyigerry/caixiang | mysite/views/weibo/oauthreturn.py | Python | mit | 941 | 0.026567 | from flask import request, render_template
from flask.ext.login import current_user, login_user
from mysite.weibo import Client
from mysite import app, db
from mysite.models import Wuser, User
from . import weibo
@weibo.route('/oauthreturn')
def oauthreturn():
code = request.args.get('code', '')
if code:
client = ... |
login_user(user)
wuser.update_access_token(client.token['access_token'])
wuser.update_profile(profile)
db.session.add(wuser)
db.session.commit()
return render_template("weibo/profile.html", wuser=wus | er) |
nikesh-mahalka/cinder | cinder/api/contrib/services.py | Python | apache-2.0 | 7,673 | 0 | # Copyright 2012 IBM Corp.
# 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 app... | alse
try:
utils.check_string_length(reason.strip(), 'Disabled reason',
min_length=1, max_length=255)
| except exception.InvalidInput:
return False
return True
@wsgi.serializers(xml=ServicesUpdateTemplate)
def update(self, req, id, body):
"""Enable/Disable scheduling for a service."""
context = req.environ['cinder.context']
authorize(context, action='update')
... |
eProsima/Fast-DDS | test/communication/liveliness_assertion.py | Python | apache-2.0 | 2,185 | 0.003661 | # Copyright 2016 Proyectos y Sistemas de Mantenimiento SL (eProsima).
#
# 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... | os.getpid()), "--exit_on_lost_liveliness",
"--xmlfile", real_xml_file], stdout=subprocess.PIPE)
while True:
line = publisher_proc.stdout.readline()
if line.strip().decode('utf-8').startswith('Publisher matched with subscriber '):
print("Subscriber matched.")
break
subscriber_proc.kill()
pu... | "Test failed: " + str(retvalue))
else:
print("Test successed")
sys.exit(retvalue)
|
Alwnikrotikz/pyicqt | src/contact.py | Python | gpl-2.0 | 9,153 | 0.037365 | # Copyright 2005-2006 Daniel Henninger <jadestorm@nc.rr.com>
# Licensed for distribution under the GPL version 2, check COPYING for details
import utils
from twisted.internet import reactor
from twisted.words.xish.domish import Element
import jabw
import config
from debug import LogEvent, INFO, WARN, ERROR
import lang... | updateRoster(self, ptype):
self.contactList.session.sendRosterImport(jid=self.j | id, ptype=ptype, sub=self.sub, groups=self.groups)
def fillvCard(self, vCard, jid):
if self.nickname:
NICKNAME = vCard.addElement("NICKNAME")
NICKNAME.addContent(self.nickname)
if self.avatar and not config.disableAvatars and not config.disableVCardAvatars:
PHOTO = self.avatar.makePhotoElement()
vCard... |
Juniper/tempest | tempest/lib/services/compute/servers_client.py | Python | apache-2.0 | 36,704 | 0 | # Copyright 2012 OpenStack Foundation
# Copyright 2013 Hewlett-Packard Development Company, L.P.
# Copyright 2017 AT&T Corp.
# 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 t... | """List servers.
For a full list of available parameters, please refer to the official
API reference:
https://developer.openstack.org/api-ref/compute/#list-servers
https://developer.openstack.org/api-ref/compute/#list-servers-detailed
"""
url = | 'servers'
schema = self.get_schema(self.schema_versions_info)
_schema = schema.list_servers
if detail:
url += '/detail'
_schema = schema.list_servers_detail
if params:
url += '?%s' % urllib.urlencode(params)
resp, body = self.get(url)
... |
Timurdov/bionicprojectpython | shadrus/article/migrations/0002_comments_comments_date.py | Python | apache-2.0 | 548 | 0.001825 | # - | *- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import datetime
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('article', '0001_initial'),
]
operations = [
migrations.AddField(
... | preserve_default=False,
),
]
|
unbit/uwsgi-gif | uwsgiplugin.py | Python | mit | 28 | 0.071429 | NAME | ='gif'
GCC_LIST=['gif | ']
|
deeso/slow-hitter | src/slow/hitter.py | Python | apache-2.0 | 10,877 | 0.001747 | from hashlib import sha256
from .etl import ETL
from kombu.mixins import ConsumerMixin
from kombu import Connection
import traceback
import Queue
import json
import time
import pytz
from datetime import datetime
from tzlocal import get_localzone
import socket
import logging
import os
class KnownHosts(object):
H... | return cls.KNOWN_HOSTS.resolve_host(ip_host)
def process_message(self, syslog_msg,
syslog_server_ip,
catcher_name, catcher_host, | catcher_tz):
m = "Extracting and converting msg from %s msg (syslog: %s)" % (syslog_server_ip, catcher_name)
logging.debug(m)
r = self.get_base_json(syslog_msg, syslog_server_ip,
catcher_name, catcher_host, catcher_tz)
sm = {}
try:
resul... |
minhphung171093/GreenERP | openerp/addons/payment_adyen/models/adyen.py | Python | gpl-3.0 | 7,511 | 0.003728 | # -*- coding: utf-'8' "-*-"
import base64
import json
from hashlib import sha1
import hmac
import logging
import urlparse
from openerp.addons.payment.models.payment_acquirer import ValidationError
from openerp.addons.payment_adyen.controllers.main import AdyenController
from openerp.osv import osv, fields
from opener... | rl': 'https://%s.adyen.com/hpp/pay.shtml' % ('live' if environment == 'prod' else environment),
}
def _get_providers(self, cr, uid, context=None):
providers = super(AcquirerAdyen, self)._get_providers(cr, uid, context=context)
providers.append(['adyen', 'Adyen'])
return providers
... | fields.char('Skin Code', required_if_provider='adyen'),
'adyen_skin_hmac_key': fields.char('Skin HMAC Key', required_if_provider='adyen'),
}
def _adyen_generate_merchant_sig(self, acquirer, inout, values):
""" Generate the shasign for incoming or outgoing communications.
:param browse... |
AdvancedClimateSystems/Diode | diode/exceptions.py | Python | mpl-2.0 | 830 | 0 | import json
class JSON_RPCError(Exception):
""" Base class for JSON-RPC errors. """
def to_json(self):
return json.dumps({
| 'code': self.code,
'message': self.__doc__,
})
class ParseError(JSON_RPCError):
""" Invalid JSON was received by the server | . An error occurred on the
server while parsing the JSON text.
"""
code = -32700
class InvalidRequestError(JSON_RPCError):
""" The JSON sent is not a valid Request object. """
code = -32600
class MethodNotFoundError(JSON_RPCError):
""" The method does not exist / is not available. """
co... |
juancferrer/Card-Magic | setup.py | Python | bsd-3-clause | 463 | 0.008639 | #!/usr/bin/env python
from distutils.core import setup
setup(name='Card-Magic',
version='1.0',
description='The best card and decks ever',
author='Juan Carlos Ferrer',
author_email='juan | .carlos@micronixsolutions.com',
| packages=['cardmagic', 'cardmagic.tests'],
package_data = {
'cardmagic': [
'translations/en/LC_MESSAGES/*',
'translations/es/LC_MESSAGES/*'],
},
)
|
msnorm/projects | zspy2/ex41/ex41.py | Python | mit | 2,749 | 0.005457 | """
********************************************************************************
Learn Python the Hard Way Third Edition, by
Zed A. Shaw
ISBN: 978-0321884916
********************************************************************************
"""
import random
from urllib import urlopen
impor | t sys
#debug = "DEBUG: "
WORD_URL = "http://learncodethehardway.org/words.txt"
WO | RDS = []
PHRASES = {
"class %%%(%%%):":
"Make a class named %%% that is-a %%%.",
"class %%%(object):\n\tdef __init__(self, ***)":
"class %%% has-a __init__ that takes self and *** parameters.",
"class %%%(object):\n\tdef ***(self,@@@)":
"class %%% has-a function named *** that takes... |
joke2k/faker | faker/providers/company/th_TH/__init__.py | Python | mit | 4,173 | 0.000946 | from collections import OrderedDict
from .. import Provider as CompanyProvider
class Provider(CompanyProvider):
formats = OrderedDict(
(
("{{company_limited_prefix}}{{last_name}} {{company_limited_suffix}}", 0.2),
(
"{{company_limited_prefix}}{{last_name}}{{company... | จอร์",
"อุตสาหกรรม",
"เอนเตอรไพรส์",
"จิวเวลรี่",
"อะไหล่ยนต์",
"ภาพยนตร์",
"ยานยนต์",
"เทรดดิ้ง",
"การค้า",
"แลบ",
"เคมิคอล" | ,
"อิมปอร์ตเอ็กซปอร์ต",
"อินเตอร์เนชั่นแนล",
"บรรจุภัณฑ์",
"แพคกิ้ง",
"มอเตอร์",
"โอสถ",
"การบัญชี",
"สโตร์",
)
company_limited_prefixes = OrderedDict(
(
("บริษัท ", 0.95),
("ธนาคาร", 0.03),
("บริษัทหลัก... |
rohitranjan1991/home-assistant | homeassistant/components/raspihats/binary_sensor.py | Python | mit | 4,436 | 0.001127 | """Support for raspihats board binary sensors."""
from __future__ import annotations
import logging
import voluptuous as vol
from homeassistant.components.binary_sensor import PLATFORM_SCHEMA, BinarySensorEntity
from homeassistant.const import (
CONF_ADDRESS,
CONF_DEVICE_CLASS,
CONF_NAME,
DEVICE_DEFA... | that uses a I2C-HAT digital input."""
I2C_HATS_MANAGER: I2CHatsManager | None = None
def __init__(self, address, channel, name, invert_logic, device_class):
"""Initialize the raspihats sensor."""
self._address = address
self._channel = channel
self._name | = name or DEVICE_DEFAULT_NAME
self._invert_logic = invert_logic
self._device_class = device_class
self._state = self.I2C_HATS_MANAGER.read_di(self._address, self._channel)
def online_callback():
"""Call fired when board is online."""
self.schedule_update_ha_stat... |
jresendiz27/EvolutionaryComputing | escom/pepo/utils.py | Python | apache-2.0 | 469 | 0.002132 | __author__ = 'alberto'
import time
from functools import wraps
from config import logger
def measure_time(func):
| """
Decorator that reports the execution time.
"""
@wraps(func)
def wrapper(*args, **kwargs):
log | ger.info("Running %s", func.__name__)
start = time.time()
result = func(*args, **kwargs)
end = time.time()
logger.info("Execution time: %s", end - start)
return result
return wrapper |
PanDAWMS/panda-server | pandaserver/taskbuffer/TaskBufferInterface.py | Python | apache-2.0 | 5,146 | 0.008356 | import os
import sys
import time
import pickle
import threading
import multiprocessing
from concurrent.futures import ThreadPoolExecutor
# required to reserve changed attributes
from pandaserver.taskbuffer import JobSpec
from pandaserver.taskbuffer import FileSpec
JobSpec.reserveChangedState = True
FileSpec.reserveC... | rocessing.Semaphore(0)
# run
self.process = multiprocessing.Process(target=self.run,
args=(taskBuffer,
self.commDict, self.comLock,
self.resLock... | faceChild(self.commDict, self.childlock, self.comLock, self.resLock)
# stop the loop
def stop(self):
with self.to_stop.get_lock():
self.to_stop.value = 1
while self.process.is_alive():
time.sleep(1)
# kill
def terminate(self):
self.process.terminate()
|
Maximilian-Reuter/SickRage-1 | sickrage/providers/torrent/TorrentProvider.py | Python | gpl-3.0 | 5,136 | 0.001363 | # coding=utf-8
# This file is part of SickRage.
#
# URL: https://sickrage.github.io
# Git: https://github.com/SickRage/SickRage.git
#
# 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... | for result in sql_results o | r []:
show = Show.find(sickbeard.showList, int(result[b'showid']))
if show:
episode = show.getEpisode(result[b'season'], result[b'episode'])
for term in self.proper_strings:
search_strings = self._get_episode_search_strings(episode, add_strin... |
adelez/grpc | src/python/grpcio_testing/grpc_testing/_common.py | Python | apache-2.0 | 4,406 | 0.000227 | # Copyright 2017 gRPC authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... | e):
| raise NotImplementedError()
@abc.abstractmethod
def send_termination(self, trailing_metadata, code, details):
raise NotImplementedError()
@abc.abstractmethod
def add_termination_callback(self, callback):
raise NotImplementedError()
class Serverish(six.with_metaclass(abc.ABCMeta)):
... |
autozimu/LanguageClient-neovim | tests/LanguageClient_test.py | Python | mit | 9,546 | 0 | import os
import time
import threading
import neovim
import pytest
threading.current_thread().name = "Test"
NVIM_LISTEN_ADDRESS = "/tmp/nvim-LanguageClient-IntegrationTest"
project_root = os.path.dirname(os.path.abspath(__file__))
def join_path(path: str) -> str:
"""Join path to this project tests root."""
... | lier does not support floating window")
nvim.command("edit! {}".format(PATH_MAIN_RS))
time.sleep(1)
win_id = nvim.funcs.win_getid()
nvim.command("split")
try:
assert win_ | id != nvim.funcs.win_getid()
_open_float_window(nvim)
assert win_id != nvim.funcs.win_getid()
# Move to another window
nvim.funcs.win_gotoid(win_id)
assert win_id == nvim.funcs.win_getid()
# Check float window buffer was closed by BufEnter
assert len(getLanguag... |
shailr/vms | applicants/migrations/0011_applicant_number_of_missed_calls.py | Python | gpl-2.0 | 421 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
|
dependencies = [
('applicants', '0010_auto_201511 | 26_0525'),
]
operations = [
migrations.AddField(
model_name='applicant',
name='number_of_missed_calls',
field=models.IntegerField(default=0),
),
]
|
A92hm/expectation-maximization | demo.py | Python | mit | 2,034 | 0.006391 | """
Author: Ali Hajimirza (ali@alihm.net)
Copyright Ali Hajimirza, free for use under MIT license.
"""
import csv
import os
import sys
import numpy as np
import matplotlib.pyplot as plt
from algorithm import EM
import argparse
d | ef line_plot(data_arrays, xlabel, ylabel, labels, title, f):
"""
Plots a scatter chart.
Parameters
----------
data_arrays: 2d numpy array
Data to be plotted. This array consists of matrices of real values to be plotted.
Each row of this matrix will be | plotted as a line on the graph.
xlabel: list of string
The list of categories on for the x axis labels. The length of this list should be equal to the
columns of the data_arrays.
ylabel: string
The label on the y axis.
labels: list of string
The labels for each category.
... |
googleapis/python-storage | samples/snippets/storage_remove_bucket_default_owner.py | Python | apache-2.0 | 1,765 | 0 | #!/usr/bin/env python
# Copyright 2019 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... | o
# remove access for different types of entities.
bucket.default_object_acl.user(user_email).revoke_read()
bucket.default_object_acl.user(user_email).revoke_write()
bucket.default_object_acl.user(user_email).revoke_o | wner()
bucket.default_object_acl.save()
print(
"Removed user {} from the default acl of bucket {}.".format(
user_email, bucket_name
)
)
# [END storage_remove_bucket_default_owner]
if __name__ == "__main__":
remove_bucket_default_owner(
bucket_name=sys.argv[1], use... |
ShivaShinde/gspread | setup.py | Python | mit | 1,845 | 0.015718 | #!/usr/bin/env python
import os.path
<<<<<<< HEAD
import re
import sys
=======
import sys
import gspread
>>>>>>> # This is a combination of 2 commits.
=======
<<<<<<< HEAD
import re
import sys
=======
import sys
import gspread
>>>>>>> # This is a combination of 2 commits.
>>>>>>> Update README.md
try:
from set... | "Operating System :: OS Independent",
"Development Status :: 3 - Alpha",
"Intended Audience :: Developers",
"Intended Audience :: End Users/Desktop",
"Intended Audience :: Science/Research",
"Topic :: Office/Business :: Financial :: Spre | adsheet",
"Topic :: Software Development :: Libraries :: Python Modules"
],
license='MIT'
)
|
ekcs/congress | congress/dse/dataobj.py | Python | apache-2.0 | 3,470 | 0 | # Copyright 2014 Plexxi, 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, ... | # "*****New subdata: %s, %s, %s",
# key, dataindex, id(self.dataObjects))
def getSources(self):
return self.dataObj | ects.keys()
def update(self, sender, newdata):
self.dataObjects[sender] = newdata
def version(self, sender):
version = 0
if sender in self.dataObjects:
version = self.dataObjects[sender].version
return version
def getData(self, sender):
result = dataO... |
nandhp/youtube-dl | youtube_dl/extractor/youjizz.py | Python | unlicense | 2,297 | 0.001741 | from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import (
ExtractorError,
)
class YouJizzIE(InfoExtractor):
_VALID_URL = r'https?://(?:\w+\.)?youjizz\.com/videos/[^/#?]+-(?P<id>[0-9]+)\.html(?:$|[?#])'
_TEST = {
'url': 'http://www.youjizz.com/video... | 89178',
'ext': 'flv',
'title': 'Zeichentrick 1',
'age_limit': 18,
}
}
def _real_extract(self, url):
video_id = self._match_id(url)
webpage = self._download_webpage(url, video_id)
age_li | mit = self._rta_search(webpage)
video_title = self._html_search_regex(
r'<title>\s*(.*)\s*</title>', webpage, 'title')
embed_page_url = self._search_regex(
r'(https?://www.youjizz.com/videos/embed/[0-9]+)',
webpage, 'embed page')
webpage = self._download_webp... |
odoousers2014/odoo-addons-supplier_price | purchase_group_by_period/tests/__init__.py | Python | agpl-3.0 | 821 | 0 | # -*- coding: utf8 -*-
#
# Copyright (C) 2014 NDP Systèmes (<http://www.ndp-systemes.fr>).
#
# This p | rogram is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be u... | NU 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 test_purchase_group_by_period
|
ibtokin/ibtokin | manage.py | Python | mit | 805 | 0 | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ibtokin.settings")
try:
from django.core.management import execute_from_command_line
except ImportError:
# The above import may fail for some other reason. Ensure th | at the
# issue is really that Django is missing to avoid masking other
# exceptions on Python 2.
try:
import django
except ImportError:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your... | o activate a virtual environment?"
)
raise
execute_from_command_line(sys.argv)
|
MaxTyutyunnikov/lino | obsolete/tests/8.py | Python | gpl-3.0 | 2,702 | 0.018135 | # coding: latin1
## Copyright 2003-2007 Luc Saffre
## This file is part of the Lino project.
## Lino 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) ... | lters import NotEmpty
#from lino.apps.addrbook import demo
#from lino.apps.addrbook.tables import Partner
class Case(TestCase):
def test01(self):
db = startup()
s1 = ''
q = db.query(Contact,\
"name street city.name",
orderBy="name")
... | .addColFilter('city',NotEmpty)
## for row in q:
## #print row[0]
## s1 += str(row[0]) + " "
## s1 += str(row[1]) + " "
## s1 += str(row[2]) + "\n"
## #print s1
## self.assertEqual(s1,"""\
## Arens None Eupen
## Ausdemwald None Aachen
## Bodard None... |
kartta-labs/mapwarper | lib/tilestache/TileStache-1.51.5/TileStache/Providers.py | Python | mit | 12,088 | 0.002978 | """ The provider bits of TileStache.
A Provider is the part of TileStache that actually renders imagery. A few default
providers are found here, but it's possible to define your own and pull them into
TileStache dynamically by class name.
Built-in providers:
- mapnik (Mapnik.ImageProvider)
- proxy (Proxy)
- vector (T... | els
- srs: projection as Proj4 string.
"+proj=longlat +ellps=WGS84 +datum=WGS84" is an example,
see http://spatialreference.org for more.
- xmin, ymin, xmax, ymax: coordinates of bounding box in projected coordinates.
- zoom: zoom level of final map. Tech | nically this can be derived from the other
arguments, but that's a hassle so we'll pass it in explicitly.
A provider may offer a method for custom response type, getTypeByExtension().
This method accepts a single argument, a filename extension string (e.g. "png",
"json", etc.) and returns a tuple with twon strings... |
sahana/Turkey | modules/s3/s3sync.py | Python | mit | 33,252 | 0.003248 | # -*- coding: utf-8 -*-
""" S3 Synchronization
@copyright: 2011-15 (c) Sahana Software Foundation
@license: MIT
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
re... | get_vars.get("limit", None)
if limit is not None:
try:
limit = int(limit)
except ValueError:
limit = None
msince = get_vars.get("msince", None)
if msince is not None:
| msince = s3_parse_datetime(msince)
# Sync filters from peer
filters = {}
for k, v in get_vars.items():
if k[0] == "[" and "]" in k:
tablename, urlvar = k[1:].split("]", 1)
if urlvar:
if not tablename or tablename == "~":
... |
jmlong1027/multiscanner | tests/modules/test_2.py | Python | mpl-2.0 | 649 | 0 | """
A test module which has a required module and a config
"""
TYPE = "Test"
NAME = "test_2"
REQUIRES = ["test_1"]
DEFAULTCONF = {'a': 1, 'b': 2}
def check(conf=DEFAULTCONF):
if None in REQUIRES:
return False
return True
def scan(filelist, conf=DEFAULTCONF):
results = []
result1, meta1 = RE... | results.append((fname, True))
else:
results.append((fname, fname))
metadata = {}
metadata["Name"] = NAME
metadata["Type"] = TYPE
metadata["Incl | ude"] = True
return results, metadata
|
wpoely86/easybuild-easyblocks | easybuild/easyblocks/p/python.py | Python | gpl-2.0 | 8,497 | 0.003884 | ##
# Copyright 2009-2016 Ghent University
#
# This file is part of EasyBuild,
# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemish Supercomputer Centre (VSC) (https://vscentrum.be/nl/en),
# Flemish Research Foundation ... | py versions by creating a PythonPackage-derived easyblock f | or it.
"""
def prepare_for_extensions(self):
"""
Set default class and filter for Python packages
"""
# build and install additional packages with PythonPackage easyblock
self.cfg['exts_defaultclass'] = "PythonPackage"
self.cfg['exts_filter'] = EXTS_FILTER_PYTHON... |
atiqueahmedziad/addons-server | src/olympia/amo/management/commands/compress_assets.py | Python | bsd-3-clause | 8,858 | 0.000226 | import hashlib
import os
import re
import time
import uuid
import subprocess
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from django.contrib.staticfiles.finders import find as find_static_path
from olympia.lib.jingo_minify_helpers import ensure_path_exists
def... | e(tmp_concatted))
if file_exists:
orig_hash = self._file_hash(concatted_file)
temp_hash = self._file_hash(tmp_concatted)
return orig_hash != temp_hash
return True # Different filesize, so it was definitely changed
def _clean_tmp(self, concatted_file):
""... | file."""
tmp_concatted = '%s.tmp' % concatted_file
if os.path.exists(concatted_file):
os.remove(concatted_file)
os.rename(tmp_concatted, concatted_file)
def _cachebust(self, css_file, bundle_name):
"""Cache bust images. Return a new bundle hash."""
self.stdout.w... |
cbonoz/codehealth | dependencies/baron/tokenizer.py | Python | mit | 3,585 | 0.000837 | import re
class UnknowItem(Exception):
pass
KEYWORDS = ("and", "as", "assert", "break", "class", "continue", "def", "del", "elif", "else", "except", "exec", "finally", "for", "from", "global", "if", "import", "in", "is", "lambda", "not", "or", "pass", "print", "raise", "return", "try", "while", "with", "yield")
... | rrent_keywords = tokenize_current_keywords()
for item in sequence:
if item in current_keywords:
yield (item.upper(), item)
continue
for candidate, token_name in TOKENS:
if candidate.match(item):
yield (to | ken_name, item)
break
else:
raise UnknowItem("Can't find a matching token for this item: '%s'" % item)
yield ('ENDMARKER', '')
yield
|
jorrit-steporange/CumulusCI | ci/github/tag_to_tag.py | Python | bsd-3-clause | 1,855 | 0.012399 | import os
import sys
from github import Github
from github.GithubException import GithubException
def tag_to_tag():
SRC_TAG=os.environ.get('SRC_TAG')
ORG_NAME=os.environ.get('ORG_NAME | ')
REPO_NAME=os.environ.get('REPO_NAME')
USERNAME=os.environ.get('USERNAME')
PASSWORD=os.environ.get('PASSWORD')
TAG=os.environ.get('TAG')
print 'Attempting to create tag %s from tag %s' % (TAG, SRC_TAG)
g = Github(USERNAME,PASSWORD)
org = g.get_organization(ORG_NAME)
repo... | none found
src_tag = None
for tag in repo.get_tags():
print tag.name
if tag.name == SRC_TAG:
src_tag = tag
break
if not src_tag:
print 'No tag named %s found' % SRC_TAG
exit(1)
tag = repo.create_git_tag(TAG, 'Created from tag %s' % SRC_TAG, s... |
grimfang/quickShadows | src/game/input.py | Python | mit | 4,080 | 0.002206 | #!/usr/bin/python
################
# The MIT License (MIT)
#
# Copyright (c) <2013> <Martin de Bruyn>
#
# 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... | se.cam.getHpr())
if cam <-80:
cam = -80
elif cam > 90:
cam = 90
base.cam.setP(cam)
flashlight.setP(cam + 90)
flashlight_lamp.setZ(flashlight.getZ() - 0.6)
flashlight | _lamp.setY(flashlight.getY() - 0.55)
flashlight_light.setHpr(flashlight_lamp.find("LightPos").getHpr() + 90)
|
chennan47/osf.io | api/files/views.py | Python | apache-2.0 | 5,890 | 0.002207 | from rest_framework import generics
from rest_framework import permissions as drf_permissions
from rest_framework.exceptions import NotFound
from framework.auth.oauth_scopes import CoreScopes
from osf.models import (
Guid,
BaseFileNode,
FileVersion,
QuickFilesNode
)
from api.base.exceptions import Go... | ersion, getattr(maybe_version, '_id', ''), self.request)
def get_serializer_context(self):
context = JSONAPIBaseView.get_serializer_context | (self)
context['file'] = self.file
return context
|
zimenglan-sysu-512/pose_action_caffe | results/pic_iou_curve.py | Python | mit | 7,311 | 0.045137 | #/usr/bin/env python
import os
import cv2
import sys
import time
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import precision_recall_curve
from sklearn.metrics import average_precision_score
disp_n = 200
s_time = 3
radius = 3
thickness = 3
cls_color = (23, 119, 188)
colors = [... | path.basename(im_path)
imgidx = im_name.strip().rsplit(".", 1)[0]
imgidx = imgidx.strip()
if imgidx in imgidxs:
print imgidx, line
imgidxs.append(imgidx)
score = float(score)
x1 = int(x1)
y1 = int(y1)
x2 = int(x2)
y2 = int(y2)
if x1 > x2:
x1, x2 = x2, x1
if y1 > y2:
y1, y2 = y2, y1
... | )))
return gt_dt
def _area(box):
assert len(box) == 4
w = box[2] - box[0] + 1
h = box[3] - box[1] + 1
a = w * h
assert a >= 0
return a
def _overlap(pd_box, gt_box):
pa = _area(pd_box)
ga = _area(gt_box)
x1 = max(pd_box[0], gt_box[0])
y1 = max(pd_box[1], gt_box[1])
x2 = min(pd_box[2], gt_box[2])
y2 = mi... |
prechelt/typecheck-decorator | setup.py | Python | bsd-2-clause | 3,969 | 0.007055 | # based on https://github.com/pypa/sampleproject/blob/master/setup.py
# see http://packaging.python.org/en/latest/tutorial.html#creating-your-own-project
from setuptools import setup, find_packages
from setuptools.command.install import install as stdinstall
import codecs
import os
import re
import sys
def find_v... | k-decorator"
class install_with_test(stdinstall):
def run(self):
stdinstall.run(self) # normal install
##pip/setuptools makes this unbuffering unhelpful:
#sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 1) # m | ake line-buffered
#sys.stderr = os.fdopen(sys.stderr.fileno(), 'w', 1) # make line-buffered
#import typecheck.test_typecheck_decorator # execute post-install test (during beta only)
setup(
# setup customization:
cmdclass={'install': install_with_test},
# basic information:
name=pac... |
MartinHjelmare/home-assistant | homeassistant/helpers/script.py | Python | apache-2.0 | 12,633 | 0 | """Helpers to execute scripts."""
import logging
from contextlib import suppress
from itertools import islice
from typing import Optional, Sequence
import voluptuous as vol
from homeassistant.core import HomeAssistant, Context, callback
from homeassistant.const import CONF_CONDITION, CONF_TIMEOUT
from homeassistant ... | ogger.exception
error = ""
if error is None:
error = str(exception)
meth("%s. %s for %s at pos %s: %s",
message_base, error_desc, action_type, step + 1, error)
async def _handle_action(self, action, variables, context):
"""Handle an action."""
... |
async def _async_delay(self, action, variables, context):
"""Handle delay."""
# Call ourselves in the future to continue work
unsub = None
@callback
def async_script_delay(now):
"""Handle delay."""
# pylint: disable=cell-var-from-loop
wi... |
iulian787/spack | var/spack/repos/builtin/packages/r-rvcheck/package.py | Python | lgpl-2.1 | 958 | 0.003132 | # 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)
fr | om spack import *
class RRvcheck(RPackage):
"""Chec | k latest release version of R and R package (both in 'CRAN',
'Bioconductor' or 'Github')."""
homepage = "https://cloud.r-project.org/package=rvcheck"
url = "https://cloud.r-project.org/src/contrib/rvcheck_0.0.9.tar.gz"
list_url = "https://cloud.r-project.org/src/contrib/Archive/rvcheck"
versi... |
davmre/bayesflow | elbow/util/__init__.py | Python | bsd-3-clause | 77 | 0 | import numpy as np
import te | nsorflow as tf
import dists
from misc import *
| |
chrislit/abydos | abydos/distance/_roberts.py | Python | gpl-3.0 | 3,233 | 0 | # Copyright 2019-2020 by Christopher C. Little.
# This file is part of Abydos.
#
# Abydos 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 versio... | thout 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 Abydos. If not, see <http://www.gnu.org/licenses/>.
"""abydos.distance._roberts.
Roberts s... | s Roberts(_TokenDistance):
r"""Roberts similarity.
For two multisets X and Y drawn from an alphabet S, Roberts similarity
:cite:`Roberts:1986` is
.. math::
sim_{Roberts}(X, Y) =
\frac{\Big[\sum_{i \in S} (X_i + Y_i) \cdot
\frac{min(X_i, Y_i)}{max(X_i, Y_i)}\Big... |
Ebag333/Pyfa | eos/effects/subsystembonusgallenteelectronic2tractorbeamvelocity.py | Python | gpl-3.0 | 458 | 0.004367 | # subSystemBonusGallente | Electronic2TractorBeamVelocity
#
# Used by:
# Subsystem: Proteus Electronics - Emergent Locus Analyzer
type = "passive"
def handler(fit, module, context):
fit.modules.filteredItemBoost(lambda mod: mod.item.group.name == "Tractor Beam",
"maxTractorVel | ocity", module.getModifiedItemAttr("subsystemBonusGallenteElectronic2"),
skill="Gallente Electronic Systems")
|
akhilari7/pa-dude | lib/python2.7/site-packages/image/video_field.py | Python | mit | 1,087 | 0 | from django.db import models
from django.db.models.fields.files import FieldFile
from django.core.files import File
def get_video_dimensions(path):
from ffvideo import VideoStream
vs = VideoStream(path)
return (vs.frame_width, vs.frame_height)
class VideoFile(File):
"""
A mixin for use alongsi... | s.base.File, which provides
additional features for dealing with images.
"""
def _get_width(self):
return self._get_video_dimensions()[0]
width = property(_get_width)
def _get_height(self):
return self._get_video_dimensions()[1]
height = property(_get_height)
def _get_vi... | ache = get_video_dimensions(self.path)
return self._dimensions_cache
# A video field is exactly a file field with a different signature
class VideoFieldFile(VideoFile, FieldFile):
pass
class VideoField(models.FileField):
attr_class = VideoFieldFile
|
OuterDeepSpace/OuterDeepSpace | generators/osgen2.py | Python | gpl-2.0 | 27,347 | 0.037774 | #
# Copyright 2001 - 2006 Ludek Smid [http://www.ospace.net/]
#
# This file is part of IGE - Outer Space.
#
# IGE - Outer Space 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 Lice... | : (8, 11, 0), # TL 3 + 4
5 : (8, 11, 0), # TL 3 + 4
6 : (5, 6, 0), # TL 5
7 : (5, 6, 0), # TL 5
8 : (5, 6, 0), # TL 5
}
if 0: # THIS IS THE RECOMENDED MEDIUM GALAXY
galaxyID = 'Circle42P'
galaxyCenter = (50.0, 50.0)
galaxyRadius = 50.0
galaxyStartR = (32.0, 36.0)
#galaxyPlayers = 30
#galaxyPlayerGroup... | laxyResources = {
# format resourceID : (minDist, maxDist, number of resources)
1 : (20, 45, 15), # TL 1 + 2
2 : (20, 45, 15), # TL 1 + 2
3 : (8, 15, 7), # TL 3 + 4
4 : (8, 15, 7), # TL 3 + 4
5 : (8, 15, 7), # TL 3 + 4
6 : (7.5, 9, 1), # TL 5
7 : (7.5, 9, 1), # TL 5
8 : (7.5, 9, 1), # TL 5
}
galaxyD... |
TobyRoseman/PS4M | engine/sourceManager.py | Python | mit | 1,630 | 0.007362 | from data.database.sourceGroupAssignmentTable import getSourceIdToAssignedGroups
from data.database.sourceGroupTable import getAllSourceGroupNames
from data.database.sourceTable import getAllSources
(categoryToSourceObjects, sourceCategoryNames, sourceIdToAssignments, sourceIdToSourceObject,
unCategorizedSource) = ({... | ct[s.lookupId] = s
if(len(s.ca | tegories) != 0):
_addToCategoryLookup(s)
else:
unCategorizedSource.append(s)
|
MOOCworkbench/MOOCworkbench | user_manager/views.py | Python | mit | 7,680 | 0.004297 | import logging
import math
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.db.models import Q
from django.shortcuts import get_object_or_404, redirect, render
from django.views.generic import View
from experiments_ma... | 'experiments': recent_experiments | ,
'packages': recent_packages})
@login_required
def search(request):
if 'q' in request.GET:
q = request.GET.get('q')
page = request.GET.get('page')
page = int(page) if page is not None else 1
results, nr_of_pages = g... |
alphacharlie/mlxd | mlxview.py | Python | gpl-2.0 | 3,859 | 0.007256 | #!/usr/bin/env python
#Demo code
#
# simple demonstration script showing real-time thermal Imaging
# using the MLX90620 16x4 thermopile array and the mlxd daemon
#
# Copyright (C) 2015 Chuck Werbick
#
#
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the G... | uite 330, Boston, MA 02111-1307, USA.
import time
import picamera
import numpy as | np
import subprocess
import os, sys
import datetime
import skimage
from skimage import io, exposure, transform, img_as_float, img_as_ubyte
from time import sleep
import matplotlib
import matplotlib.pyplot as plt
# IR registration parameters
ROT = np.deg2rad(90)
SCALE = (36.2, 36.4)
OFFSET = (530, 170)
def getImage()... |
agnethesoraa/recipemaster | recipemaster/recipes/migrations/0003_auto_20150325_2130.py | Python | mit | 820 | 0.002439 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
f | rom django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('recipes', '0002_recipecollection_title'),
]
operations = [
migrations.CreateModel(
name='Tag',
fields=[
('id', models.AutoField(verbose_name='ID', seri... | mary_key=True, auto_created=True)),
('title', models.CharField(max_length=255)),
],
options={
},
bases=(models.Model,),
),
migrations.AddField(
model_name='recipe',
name='tags',
field=models.ManyToManyFie... |
leifurhauks/grpc | src/python/grpcio/tests/unit/beta/test_utilities.py | Python | bsd-3-clause | 2,422 | 0.002064 | # Copyright 2015, 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 lis | t of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of | its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCH... |
PredictionIO/Demo-AngelList | backend/angellist_demo/urls.py | Python | apache-2.0 | 840 | 0.009524 | from django.conf.urls.defaults import patterns, include, url
from rest_framework.urlpatterns import format_suffix_patterns
from startups import views
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('startups.views',
# Examples:
... |
urlpatterns = format_suff | ix_patterns(urlpatterns)
|
hjanime/gffutils | gffutils/create.py | Python | mit | 50,151 | 0 | import copy
import warnings
import collections
import tempfile
import sys
import os
import sqlite3
import six
from textwrap import dedent
from gffutils import constants
from gffutils import version
from gffutils import bins
from gffutils import helpers
from gffutils import feature
from gffutils import interface
from gf... | es -- but only if everything else
| matches; otherwise error. This can be slow, but is thorough.
"create_unique":
Autoincrement based on the ID, always creating a new ID.
"replace":
Replaces existing database feature with `f`.
"""
if merge_strategy == 'error':
raise ValueError... |
cthtuf/django-cv | cv/wsgi.py | Python | mit | 381 | 0 | """
WSGI config for cv project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/ | howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "cv.settings")
application = get_wsgi_app | lication()
|
nkgilley/home-assistant | homeassistant/components/spider/climate.py | Python | apache-2.0 | 3,866 | 0.000259 | """Support for Spider thermostats."""
import logging
from homeassistant.components.climate import ClimateEntity
from homeassistant.components.climate.const import (
HVAC_MODE_COOL,
HVAC_MODE_HEAT,
HVAC_MODE_OFF,
SUPPORT_FAN_MODE,
SUPPORT_TARGET_TEMPERATURE,
)
from homeassistant.const import ATTR_T... | ermostat.id
@property
def name(self):
"""Return the name of the thermostat, if any."" | "
return self.thermostat.name
@property
def temperature_unit(self):
"""Return the unit of measurement."""
return TEMP_CELSIUS
@property
def current_temperature(self):
"""Return the current temperature."""
return self.thermostat.current_temperature
@property... |
hackgnar/osquery | tools/tests/test_osqueryd.py | Python | bsd-3-clause | 9,307 | 0.000537 | #!/usr/bin/env python3
# Copyright (c) 2014-present, The osquery authors
#
# This source code is licensed as defined by the LICENSE file found in the
# root directory of this source tree.
#
# SPDX-License-Identifier: (Apache-2.0 OR GPL-2.0-only)
import glob
import os
import signal
import shutil
import time
import uni... | "disable_watchdog": True,
"ephemeral": True,
"disable_database": True,
"disable_logging": True,
})
self.assertTrue(daemon.isAlive())
# Send a SIGINT
os.kill(daemon.pid, signal.SIGINT)
self.assertTrue(daemon.isDead(daemon.pid, 10))
| if os.name != "nt":
self.assertEqual(daemon.retcode, 0)
@test_base.flaky
def test_6_logger_mode(self):
logger_path = test_base.getTestDirectory(test_base.TEMP_DIR)
test_mode = 0o754 # Strange mode that should never exist
daemon = self._run_daemon(
{
... |
codeofdusk/ProjectMagenta | src/keystrokeEditor/constants.py | Python | gpl-2.0 | 2,205 | 0.021769 | # -*- coding: utf-8 -*-
actions = {
"up": _(u"Go up in the current buffer"),
"down": _(u"Go down in the current buffer"),
"left": _(u"Go to the previous buffer"),
"right": _(u"Go to the next buffer"),
"next_account": _(u"Focus the next session"),
"previous_account": _(u"Focus the previous session"),
"show_hide": _(u"Sh... | logue"),
"user_details": _(u"See user details"),
"view_item": _(u"Show tweet"),
"exit": _(u"Quit"),
"open_timeline": _(u"Open user timeline"),
"remove_buffer": _(u"Destroy buffer"),
"interact": _(u"Interact with the currently focused tweet."),
"url": _(u"Open URL"),
"volume_up": _(u"Increase volume by 5%"),
"volume_dow... | first element of a buffer"),
"go_end": _(u"Jump to the last element of the current buffer"),
"go_page_up": _(u"Jump 20 elements up in the current buffer"),
"go_page_down": _(u"Jump 20 elements down in the current buffer"),
"update_profile": _(u"Edit profile"),
"delete": _(u"Delete a tweet or direct message"),
"clear_b... |
Eficent/sale-workflow | product_customer_code_sale/__init__.py | Python | agpl-3.0 | 880 | 0 | # -*- coding: utf-8 -*-
#
#
# Copyright (C) 2013 Agile Business Group sagl (<http://www.agilebg.com>)
# Author: Nicola Malcontenti <nicola.malcontenti@agilebg.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as publis... | etails.
#
# 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/>.
#
#
from . import sale
|
abdullahcaliskan/Python | OOP/props.py | Python | gpl-2.0 | 467 | 0.038544 | class Robot:
def __init__(self):
self.__name = ""
@property
def name(self):
return self.__name
@name.setter
| def name(self, x):
self.__name = x
class Car:
def __init__(self, model=None):
self.__set_model(model)
def __set_model(self, model):
self.__model = model
def __get_model(self):
return self.__model
model = property(__get_model, __set_model)
x = Robot()
x.name = "apo"
prin | t(x.name)
c = Car()
c.model = "Mercedes"
print(c.model)
|
vinneyto/lab-portal | portal/test_models.py | Python | bsd-3-clause | 2,587 | 0.002052 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.core.exceptions import ValidationError
from django.test import TestCase
from models import Student, StudyGroup, Task, Lab, Subject, GroupSubject
class PortalTest(TestCase):
def setUp(self):
self.study_group1 = StudyGroup.objects.... | r(
u | sername="pavel", email=None, password="123456", study_group=self.study_group2
)
self.lab1 = Lab.objects.create(name="Кольца ньютона", subject=self.subject1)
self.lab2 = Lab.objects.create(name="Атвуд", subject=self.subject2)
def test_task_create(self):
has_error = False
try... |
Sharpe49/ts2 | ts2/routing/route.py | Python | gpl-2.0 | 12,444 | 0.001848 | #
# Copyright (C) 2008-2013 by Nicolas Piganeau
# npi@m4x.org
#
# 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 versi... | (index.sibling(index.row(), 0).data())
self._editor.routes[routeNum].initialState = value
self.dataChanged.emit(index, index)
return True
return False
def headerData(self, section, orientation, role = Qt.DisplayRole):
"""Returns the header la | bels"""
if role == Qt.DisplayRole and orientation == Qt.Horizontal:
if section == 0:
return self.tr("Route no.")
elif section == 1:
return self.tr("Begin Signal")
elif section == 2:
return self.tr("End Signal")
elif ... |
alexlo03/ansible | lib/ansible/module_utils/yumdnf.py | Python | gpl-3.0 | 6,502 | 0.001846 | # -*- coding: utf-8 -*-
#
# # Copyright: (c) 2012, Red Hat, Inc
# Written by Seth Vidal <skvidal at fedoraproject.org>
# Contributing Authors:
# - Ansible Core Team
# - Eduard Snesarev (@verm666)
# - Berend De Schouwer (@berenddeschouwer)
# - Abhijeet Kasurde (@Akasurde)
# GNU General Public License v3.0+ (... | install_repoquery = self.module.params['install_repoquery']
self.list = self.module.params['list']
self.names = [p.strip() for p in self.module.params['name']]
self.releasever = self.module.params['releasever']
self.security = self.module.params['security']
self.skip_broken = sel... | ate_only']
self.update_cache = self.module.params['update_cache']
self.validate_certs = self.module.params['validate_certs']
self.lock_timeout = self.module.params['lock_timeout']
# It's possible someone passed a comma separated string since it used
# to be a string type, so we ... |
SinnerSchraderMobileMirrors/django-cms | cms/migrations/0041_auto__add_usersettings.py | Python | bsd-3-clause | 15,866 | 0.00832 | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'UserSettings'
db.create_table(u'cms_usersettings', (
(u'id', self.gf('django.db.... | go.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'creation_date': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
u'id': ('django.db.models.fields.AutoField', [], {'pri | mary_key': 'True'}),
'language': ('django.db.models.fields.CharField', [], {'max_length': '15', 'db_index': 'True'}),
'level': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
'lft': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'})... |
kubeflow/kfp-tekton-backend | components/gcp/container/component_sdk/python/kfp_component/google/bigquery/__init__.py | Python | apache-2.0 | 601 | 0.001664 | # Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# 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 spe | cific language governing permissions and
# limitations under the License.
from ._query import query |
gaqzi/ansible-modules-extras | packaging/language/composer.py | Python | gpl-3.0 | 6,200 | 0.008548 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2014, Dimitrios Tydeas Mengidis <tydeas.dr@gmail.com>
# 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... | map to get a faster autoloader. This is recommended especially for production, but can take a bit of time to run so it is currently not done by default.
required: false
default: "yes"
choices: [ "yes", "no" ]
aliases: [ "optimize-autoloader" ]
requirements:
- php
- composer insta... |
EXAMPLES = '''
# Downloads and installs all the libs and dependencies outlined in the /path/to/project/composer.lock
- composer: command=install working_dir=/path/to/project
'''
import os
import re
def parse_out(string):
return re.sub("\s+", " ", string).strip()
def has_changed(string):
if "Nothing to insta... |
melmothx/jsonbot | jsb/plugs/core/rc.py | Python | mit | 1,732 | 0.017321 | # jsb/plugs/core/rc.py
#
#
""" jsonbot resource files .. files with the .jsb extension which consists of commands to be executed. """
## jsb imports
from jsb.lib.commands import cmnds
from jsb.lib.examples import examples
from jsb.utils.url import geturl2
from jsb.utils.exception import handle_exception
from jsb.uti... | sult = bot.docmnd(event.userhost, event.channel, i, wait=1, event=event)
#if result: result.waitall()
teller += 1
#waitevents(waiting)
event.reply("%s commands executed" % teller)
except Exception, ex: event.reply("an error occured: %s" % str(ex)) ; handle_exception()
cmnds.... | ("rc", "execute a file of jsonbot commands .. from file or url", "1) rc resource.jsb 2) rc http://jsonbot.org/resource.jsb")
|
billhoffman/drake | drake/bindings/python/pydrake/test/testRBTCoM.py | Python | bsd-3-clause | 1,228 | 0.002443 | from __future__ import print_function
import unittest
import numpy as np
import pydrake
import os.path
class TestRBTCoM(unittest.TestCase):
def testCoM0(self):
r = pydrake.rbtree.RigidBodyTree(os.path.join(pydrake.getDrakePath(),
"examples/Pendulum/Pendulum.urdf"))... | ), np.zeros((7, 1)))
c = r.centerOfMass(kinsol)
self.assertTrue(np.allclose(c.flat, [0.0, 0.0, -0.2425], atol=1e-4))
def testCoMJacobian(self):
r = pydrake.rbtree.RigidBodyTree(os.path.join(pydrake.getDrakePath(),
"examples/Pendulum/Pendulum.urdf")... | (np.shape(J) == (3, 7))
q = r.getZeroConfiguration()
kinsol = r.doKinematics(q, np.zeros((7, 1)))
J = r.centerOfMassJacobian(kinsol)
self.assertTrue(np.allclose(J.flat, [1., 0., 0., 0., -0.2425, 0., -0.25,
0., 1., 0., 0.2425, 0., 0., 0.,
0., 0., 1., 0., 0., 0., 0.], ato... |
sdss/marvin | tests/tools/test_rss.py | Python | bsd-3-clause | 8,275 | 0.001693 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# @Author: Brian Cherinka, José Sánchez-Gallego, and Brett Andrews
# @Date: 2018-07-24
# @Filename: test_rss.py
# @License: BSD 3-clause (http://www.opensource.org/licenses/BSD-3-Clause)
#
# @Last modified by: José Sánchez-Gallego (gallegoj@uw.edu)
# @Last modified time: ... | opy.io.f | its
import astropy.table
import numpy
import pytest
import marvin
from ..conftest import Galaxy, set_the_config
@pytest.fixture(scope='session')
def galaxy(get_params, plateifu):
"""Yield an instance of a Galaxy object for use in tests."""
release, bintype, template = get_params
set_the_config(release... |
ligo-cbc/pycbc | pycbc/results/dq.py | Python | gpl-3.0 | 2,187 | 0.002286 | '''This module contains utilities for following up search triggers'''
# JavaScript for searching the aLOG
redirect_javascript = """<script type=" | text/javascript">
function redirect(form,way)
{
// Set location to form and submit.
if(form != '')
{
document.forms[form].action=way;
document.forms[form].submit();
}
else
{
window.top.loc | ation = way;
}
}
</script>"""
search_form_string="""<form name="%s_alog_search" id="%s_alog_search" method="post">
<input type="hidden" name="srcDateFrom" id="srcDateFrom" value="%s" size="20"/>
<input type="hidden" name="srcDateTo" id="srcDateTo" value="%s" size="20"/>
</form>"""
data_h1_string = """H1
 ... |
kolypto/py-mongosql | mongosql/util/history_proxy.py | Python | bsd-2-clause | 5,787 | 0.003974 | from copy import deepcopy
from sqlalchemy import inspect
from sqlalchemy.orm.base import DEFAULT_STATE_ATTR
from sqlalchemy.orm.state import InstanceState
from mongosql.bag import ModelPropertyBags
class ModelHistoryProxy:
""" Proxy object to gain access to historical model attributes.
This leverages SqlAlc... | _state.manager)
my_state.key = instance_state.key
my_state.session_id = instance_state.session_id
setattr(self, DEFAULT_STATE_ATTR, my_state)
def __getattr__(self, key):
# Get a relationship:
if key in self.__bags.relations:
relationship = getattr(self.__model, k... | rty)
if key in self.__bags.properties:
# Because properties may use other columns,
# we have to run it against our`self`, because only then it'll be able to get the original values.
return getattr(self.__model, key).fget(self)
# Every column attribute is accessed thr... |
jac2130/BayesGame | foundations-of-python-network-programming/python2/01/basicserver.py | Python | mit | 745 | 0.013423 | #/usr/bin/env python
#Base Server -Chapter three -basicserver.py
import socket, traceback
host=''
port=8080
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((host, port))
print "Waiting for connections..."
s.listen(1)
while True:
try:
clien... | traceback.print_exc()
try:
clientsock.close()
except KeyboardInterrupt:
| raise
except:
traceback.print_exc()
|
hrashk/sympy | sympy/utilities/tests/test_iterables.py | Python | bsd-3-clause | 24,090 | 0.00083 | from textwrap import dedent
from sympy import (
symbols, Integral, Tuple, Dummy, Basic, default_sort_key, Matrix,
factorial, true)
from sympy.combinatorics import RGS_enum, RGS_unrank, Permutation
from sympy.utilities.iterables import (
_partition, _set_partitions, binary_partitions, bracelets, capture,
... | , x + y, w*(x + y), w*(x + y) + z]
assert list(postorder_traversal(expr, keys=default_sort_key)) == expected
assert list(postorder_traversal(expr, keys=True)) == expected
expr = Piecewise((x, x < 1), (x**2, True))
expected = [
x, 1, x, x < 1, ExprCondPair(x, x < 1),
2, x, x**2, true,
... | ist(postorder_traversal(expr, keys=default_sort_key)) == expected
assert list(postorder_traversal(
[expr], keys=default_sort_key)) == expected + [[expr]]
assert list(postorder_traversal(Integral(x**2, (x, 0, 1)),
keys=default_sort_key)) == [
2, x, x**2, 0, 1, x, Tuple(x, 0, 1),
... |
oihane/odoomrp-wip | mrp_byproduct_operations/__init__.py | Python | agpl-3.0 | 945 | 0 |
# -*- encoding: utf-8 -*-
##############################################################################
#
# Daniel Campos (danielcampos@avanzosc.es) Date: 29/09/2014
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as publi... | program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# ... | program. If not, see http://www.gnu.org/licenses/.
#
##############################################################################
from . import models
|
rieder/MASC | src/amuse/ext/masc/cluster.py | Python | mit | 10,655 | 0 | #!/usr/bin/env python
"""
make_a_star_cluster.py creates a model star cluster,
which can then be used in N-body simulations or for other purposes.
It requires AMUSE, which can be downloaded from http://amusecode.org or
https://github.com/amusecode/amuse.
Currently not feature-complete yet, and function/argument names... | umber_of_stars=number_of_stars,
)
total_mass = mass.sum()
number_of_stars = len(mass)
print(number_of_stars, total_mass, effective_radius)
converter = generic_unit_converter.ConvertBetweenGenericAndSiUnits(
total_mass,
1. | units.kms,
effective_radius,
| )
# Give stars a position and velocity, based on the distribution model.
if star_distribution == "plummer":
stars = new_plummer_sphere(
number_of_stars,
convert_nbody=converter,
)
elif star_distribution == "king":
stars = new_king_model(
number... |
googleinterns/local_global_ts_representation | main.py | Python | apache-2.0 | 3,904 | 0.00666 | # Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | ntation learning modules
| if args.train:
if is_continue:
rep_model.load_weights('./ckpt/glr_%s_lambda%.1f' %(args.data, args.lamda))
train_glr(rep_model, trainset, validset, lr=lr, n_epochs=n_epochs, data=args.data)
# Plot summary performance graphs for the learning framework,
# including the representat... |
staudt/gimmick-generator | lists/generate.py | Python | mit | 352 | 0.028409 |
filenames = ['firstNames', 'secondNames', 'famousWrestlers', 'categories', 'jobs']
for filename in filenames:
with open('%s.csv' % filename, 'r') as f:
namelist = []
for name in f.read().split('\n'):
if len(name)>1: nam | elist.append(name)
with open('../js/%s.js' % filename, 'w') as dest_f:
dest_f.write('%s = %s;' % (fi | lename, namelist)) |
Coderhypo/makinami | illustrious/spiders/poj.py | Python | mit | 12,789 | 0.005943 | #!/usr/bin/env python
# coding=utf-8
from scrapy.spiders import Spider
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import | LinkExtractor as link
from scrapy.http im | port Request, FormRequest
from scrapy.selector import Selector
from illustrious.items import ProblemItem, SolutionItem, AccountItem
from datetime import datetime
import time
LANGUAGE = {
'g++': '0',
'gcc': '1',
'java': '2',
'pascal': '3',
'c++': '4',
'c': '5',
'fortran': '6'
}
class PojIni... |
code-google-com/cortex-vfx | contrib/IECoreArnold/python/IECoreArnold/__init__.py | Python | bsd-3-clause | 1,852 | 0 | ############################# | #############################################
#
# Copyright (c) 2011, Image Engine Design Inc. All rights reserved.
#
# | Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# * Redistributions i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.