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 |
|---|---|---|---|---|---|---|---|---|
AltSchool/django-allauth | allauth/socialaccount/providers/microsoft/tests.py | Python | mit | 988 | 0.001012 | from allauth.socialaccount.tests import OAuth2TestsMixin
from allauth.tests import MockedResponse, TestCase
from .provider import MicrosoftGraphProvider
class MicrosoftGraphTests(OAuth2T | estsMixin, TestCase):
provider_id = MicrosoftGraphProvider.id
de | f get_mocked_response(self):
response_data = """
{
"@odata.context": "https://graph.microsoft.com/v1.0/$metadata#users/$entity",
"id": "16f5a7b6-5a15-4568-aa5a-31bb117e9967",
"businessPhones": [],
"displayName": "Anne Weiler",
"givenName": "Ann... |
juanantoniofm/accesible-moodle | fabtools/python.py | Python | gpl-2.0 | 8,076 | 0.001114 | """
Python environments and packages
================================
This module provides tools for using Python `virtual environments`_
and installing Python packages using the `pip`_ installer.
.. _virtual environments: http://www.virtualenv.org/
.. _pip: http://www.pip-installer.org/
"""
from __future__ import w... | d:
options.append('--allow-unverified="%s"' % package)
if quiet:
options.append('--quiet')
if exists_action:
options.append('--exists-action=%s' % exists_action)
options = ' '.join(options)
command = '%(pip_cmd)s install %(options)s -r %(filename)s' % locals()
if | use_sudo:
sudo(command, user=user, pty=False)
else:
run(command, pty=False)
def create_virtualenv(directory, system_site_packages=False, venv_python=None,
use_sudo=False, user=None, clear=False, prompt=None,
virtualenv_cmd='virtualenv'):
"""
Create a Python `v... |
justb4/stetl | tests/test_args.py | Python | gpl-3.0 | 4,523 | 0.003537 | # testing: to be called by nosetests
import os
from stetl.etl import ETL
from tests.stetl_test_case import StetlTestCase
from stetl.main import parse_args
class ConfigTest(StetlTestCase):
"""Basic configuration tests"""
def setUp(self):
super(ConfigTest, self).setUp()
# Initialize Stetl
... | {'in_file': 'infile.txt', 'out_file': 'outfile.txt'}
# Override in OS env
os.environ['stetl_in_file'] = 'env_infile.txt'
etl = ETL(self.cfg_dict, args_dict)
# Test args substitution from args_dict
self.assertEqual(etl.configdict.get('input_file', 'file_path'), os.environ['ste... | args_dict_env_all(self):
"""
Substitute ALL args from OS env.
:return:
"""
# Set all args in in OS env
os.environ['stetl_in_file'] = 'env_infile.txt'
os.environ['stetl_out_file'] = 'env_outfile.txt'
args_dict = None
etl = ETL(self.cfg_dict, args_... |
zacko-belsch/pazookle | tests/try_Mixer.py | Python | gpl-3.0 | 2,580 | 0.037209 | #!/usr/bin/env python
import os.path
programName = os.path.splitext(os.path.basename(__file__))[0]
from sys import argv,stdin,stderr,exit
from pazookle.shred import zook,Shreduler
from pazookle.ugen import UGen,Mixer
from pazookle.generate import SinOsc
from pazookle.output import WavOut
from p... | Val = arg.split("=",1)[1]
if (arg.startswith("F1=")) or (arg.startswith("--freq1=")) or (arg.startswith("--frequency1=")):
freq1 = float_or_fraction(argVal)
elif (arg.startswith("F2=")) or (arg.startswith("--freq2=")) or (arg.startswith("--frequency2=")):
freq2 = float_or_fra | ction(argVal)
elif (arg.startswith("D=")) or (arg.startswith("--dry=")):
dry = float_or_fraction(argVal)
elif (arg.startswith("W=")) or (arg.startswith("--wet=")):
wet = float_or_fraction(argVal)
elif (arg.startswith("--channels=")):
numChannels = int(argVal)
elif (arg.startswith("T=")) or (arg.startsw... |
wkmanire/StructuresAndAlgorithms | pythonpractice/queueoftwostacks.py | Python | gpl-3.0 | 1,054 | 0 | # -*- coding:utf-8; mode:python -*-
"""
Imple | ments a queue efficiently using only two stacks.
"""
from helpers import SingleNode
from stack import Stack
class QueueOf2Stacks:
def __init__(self):
self.stack_1 = Stack()
self.stack_2 = Stack()
def enqueue(self, value):
self.stack_1.push(value)
def dequeue(self):
self... | elf.stack_2.peek()
def transfer_if_necessary(self):
if not self.stack_2:
while self.stack_1:
self.stack_2.push(self.stack_1.pop())
def __len__(self):
return len(self.stack_1) + len(self.stack_2)
def main():
queue = QueueOf2Stacks()
print()
for i in ran... |
joeykrug/sidecoin | contrib/pyminer/pyminer.py | Python | mit | 6,470 | 0.036321 | #!/usr/bin/python
#
# Copyright (c) 2011 The Bitcoin developers
// Copyright (c) 2014 Dyffy, Inc.
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
import time
import json
import pprint
import hashlib
import struct
import re
i... | name, password):
authpair = "%s:%s" % (user | name, password)
self.authhdr = "Basic %s" % (base64.b64encode(authpair))
self.conn = httplib.HTTPConnection(host, port, False, 30)
def rpc(self, method, params=None):
self.OBJID += 1
obj = { 'version' : '1.1',
'method' : method,
'id' : self.OBJID }
if params is None:
obj['params'] = []
else:
ob... |
ArcEye/machinekit-testing | configs/sim/axis/haltest.py | Python | lgpl-2.1 | 242 | 0.012397 | # exampl | e for using Python with cython bindings as a [HAL]HALFILE
# in the ini file, add as last HALFILE:
#[HAL]
#HALFILE = haltest.py
from machinekit.halfile import rt, hal
rt.loadrt("supply")
hal.addf("supply.0 | .update","servo-thread")
|
FRC-RS/FRS | TBAW/templatetags/getters.py | Python | mit | 750 | 0 | from typing import TypeVar, Dict, Any
from django import template
from django.conf import settings
from util.getters import reverse_model_url
register = template.Library()
| T = TypeVar('T')
@register.filter(name='get_from_dict')
def get_from_dict(dictionary: Dict[T, Any], key: T):
value = dictionary.get(key)
if settings.DEBUG and value is None:
print(key, dictionary)
return value
@register.filter(name='url_finder')
def url_finder(obj):
return reverse_model_ur... | try:
return getattr(obj, attr)
except AttributeError:
return None
|
guardian/alerta | examples/plugins/transient/setup.py | Python | apache-2.0 | 609 | 0 | from setuptools import find_packages, setup
version = '0.0.1'
setup(
name='alerta-transient',
version=version,
description='Example Alerta plugin for transient flapping alerts',
url='https://github.com/alerta/alerta-contrib',
license='Apache License 2.0',
author='Your name',
author_email='... | com',
packages=find_packages(),
py_modules=['alerta_transient'],
install_requires=[],
include_package_data= | True,
zip_safe=True,
entry_points={
'alerta.plugins': [
'transient = alerta_transient:TransientAlert'
]
}
)
|
ctrlaltdel/neutrinator | vendor/openstack/tests/unit/cloud/test_port.py | Python | gpl-3.0 | 14,285 | 0 | # Copyright (c) 2015 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 License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable... | ed',
'binding:profile': {},
'binding:vnic_type': 'normal',
'fixed_ips': [
{
'subnet_id': '008ba151-0b8c-4a67-98b5-0d2b87666062',
| 'ip_address': '172.24.4.2'
}
],
'id': 'd80b1a3b-4fc1-49f3-952e-1e2ab7081d8b',
'security_groups': [],
'device_id': '9ae135f4-b6e0-4dad-9e91-3c223e385824'
},
{
'status': 'ACTIVE',
... |
ShaguptaS/python | bigml/tests/read_project_steps.py | Python | apache-2.0 | 869 | 0.002301 | # -*- coding: utf-8 -*-
#!/usr/bin/env python
# |
# Copyri | ght 2014 BigML
#
# 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
# dis... |
Ghadjeres/DeepBach | DeepBach/helpers.py | Python | mit | 816 | 0 | """
@author: Gaetan Hadjeres
"""
import torch
from torch.autograd import Variable
def cuda_variable(tensor, volatile=False):
if torch.cuda.is_available():
return Variable(tensor.cuda(), volatile=volatile)
else:
return Variable(tensor, volatile=volatile)
def to_numpy(variable: Variable):
... | ch.randn(num_layers, bat | ch_size, lstm_hidden_size),
volatile=volatile),
cuda_variable(
torch.randn(num_layers, batch_size, lstm_hidden_size),
volatile=volatile)
)
return hidden
|
hbussell/pinax-tracker | apps/pyvcal/git_wrapper/resource.py | Python | mit | 719 | 0.011127 | class Resource(object):
"""Abstract class representing a versioned object"""
def __init__(self, identity, revision, repo, isTree):
super(Resource, self).__init__()
self._id = identity # hash of this object
self._revision = revision # revision this object belongs to
self._rep... | y this object belongs to
def get_latest_revision(self):
"""Return the last revision this was modified"""
raise NotImplementedError
def get_properties(self):
"""Return the properties | of a resource"""
raise NotImplementedError
latest_revision = property(get_latest_revision)
properties = property(get_properties)
|
lyft/bandit-high-entropy-string | setup.py | Python | apache-2.0 | 680 | 0 | #!/usr/bin/env python
# Copyright (c) 2016 Lyft 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... | ibuted on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations | under the License.
import setuptools
setuptools.setup(
setup_requires=['pbr'],
pbr=True)
|
joebowen/movement_validation_cloud | djangodev/lib/python2.7/site-packages/neuroml/nml/helper_methods.py | Python | mit | 4,806 | 0.005826 | import sys
imp | ort re
#
# You must include the following class definition at the top of
# your method specification file.
#
class MethodSpec(object):
def __init__(self, name='', source='', class_names='',
class_names_compiled=None):
"""MethodSpec -- A specification of a method.
| Member variables:
name -- The method name
source -- The source code for the method. Must be
indented to fit in a class definition.
class_names -- A regular expression that must match the
class names in which the method is to be inserted.
... |
AntumDeluge/desktop_recorder | source/custom/__init__.py | Python | mit | 80 | 0.0125 | # -*- coding: utf-8 -*-
## \packag | e custom
# MIT licensing
# Se | e: LICENSE.txt
|
Ju2ender/CSharp-Exercise | shadowsocks/shadowsocks/crypto/openssl.py | Python | mit | 5,414 | 0.000185 | #!/usr/bin/env python
#
# Copyright 2015 clowwindy
#
# 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 ... | me)
if not cipher:
raise Exception('cipher %s not found in libcrypto' % cipher_name)
key_ptr = c_char_p(key)
iv_ptr = c_char_p(iv)
self._ctx = libcrypto.EVP_CIPHER_CTX_new()
if not self._ctx:
raise Exception('can not create cipher context')
r = lib... | t_ex(self._ctx, cipher, None,
key_ptr, iv_ptr, c_int(op))
if not r:
self.clean()
raise Exception('can not initialize cipher context')
def update(self, data):
global buf_size, buf
cipher_out_len = c_long(0)
l = len(data)... |
valecs97/Contest | Contest/iteration_3/undoModule.py | Python | gpl-3.0 | 593 | 0.026981 | '''
Created on Oct 18, 2016
@author: Vitoc
'''
import copy
class undoModuleClass:
def __init__(self):
return
'''
Function that undos the operations that you have | made
'''
def saveTheFunction(self,l,undo):
undo.append(copy.deepcopy(l))
def undoIntoPast(self,l,undo):
try:
maximus = | len(undo) -1
l = copy.deepcopy(undo[maximus])
del undo[maximus]
except IndexError:
print("There are no more undos , sry")
return l
|
fashiontec/knitlib | src/knitlib/plugins/dummy_plugin.py | Python | lgpl-3.0 | 1,842 | 0.007058 | # -*- coding: utf-8 -*-
# This file is part of Knitlib.
#
# Knitlib 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.
#
# Knitlib is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without ev | en 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 Knitlib. If not, see <http://www.gnu.org/licenses/>.
#
# Copyright 2015 Sebastian O... |
liosha2007/temporary-groupdocs-python3-sdk | groupdocs/models/State.py | Python | apache-2.0 | 851 | 0.005875 | #!/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... | OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
c | lass State:
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually."""
def __init__(self):
self.swaggerTypes = {
}
|
avara1986/gozokia | gozokia/core/rules.py | Python | mit | 7,566 | 0.001718 | # encoding: utf-8
"""
Rules system.
"""
import copy
from operator import itemgetter
class RuleBase(object):
"""
All rules inherit from RuleBase. All rules needs a condition, a response.
RuleBase is the base model to all rules. with this class, the rules will can to access
to the main class (Gozokia)... | _active_rule(self, key=None):
if key is None:
rule = self.__active_rule |
else:
rule = self.__active_rule[key]
return rule
def set_active_rule(self, rule=None):
if rule:
self.set_rule_status_active(rule)
self.__active_rule = rule
def stop_active_rule(self):
self.set_rule_status_pending(self.__active_rule)
self... |
mikalstill/nova | nova/tests/unit/api/openstack/compute/test_server_groups.py | Python | apache-2.0 | 36,927 | 0.002194 | # Copyright (c) 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 r... | ault('name', 'test')
return sgroup
def server_group_resp_template(**kwargs):
sgroup = kwargs.copy()
sgroup.setdefault('name', 'test')
if 'policy' not in | kwargs:
sgroup.setdefault('policies', [])
sgroup.setdefault('members', [])
return sgroup
def server_group_db(sg):
attrs = copy.deepcopy(sg)
if 'id' in attrs:
attrs['uuid'] = attrs.pop('id')
if 'policies' in attrs:
policies = attrs.pop('policies')
attrs['policies'] ... |
wolfram74/numerical_methods_iserles_notes | venv/lib/python2.7/site-packages/sympy/polys/polytools.py | Python | mit | 171,109 | 0.000316 | """User-friendly public interface to polynomial functions. """
from __future__ import print_function, division
from sympy.core import (
S, Basic, Expr, I, Integer, Add, Mul, Dummy, Tuple
)
from sympy.core.mul import _keep_coeff
from sympy.core.symbol import Symbol
from sympy.core.basic import preorder_traversal
... | rep.items():
rep[monom] = domain.convert(coeff)
return cls.n | ew(DMP.from_dict(rep, level, domain), *gens)
@classmethod
def _from_list(cls, rep, opt):
"""Construct a polynomial from a ``list``. """
gens = opt.gens
if not gens:
raise GeneratorsNeeded(
"can't initialize from 'list' without generators")
elif len(g... |
johnbachman/indra | indra/assemblers/index_card/__init__.py | Python | bsd-2-clause | 42 | 0 | from | .assembler import IndexCardAssembler
| |
rlucio/cinder-violin-driver-icehouse | cinder/volume/drivers/violin/v6000_common.py | Python | apache-2.0 | 32,857 | 0.00003 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2014 Violin Memory, 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... | inder requires the presence of "
"the Violin 'XG-Tools', python libraries for facilitating "
"communication between applications and the v6000 XML API. "
"The libraries can be downloaded from the Violin Memory "
"support website at http://www.violin-memory.com/support"))
rais... | %s"), vxg.__version__)
violin_opts = [
cfg.StrOpt('gateway_vip',
default='',
help='IP address or hostname of the v6000 master VIP'),
cfg.StrOpt('gateway_mga',
default='',
help='IP address or hostname of mg-a'),
cfg.StrOpt('gateway_mgb',
... |
InsuraCoinDev/insuracoin | contrib/testgen/gen_base58_test_vectors.py | Python | mit | 4,344 | 0.006906 | #!/usr/bin/env python
'''
Generate valid and invalid base58 address and private key test vectors.
Usage:
gen_base58_test_vectors.py valid 50 > ../../src/test/data/base58_keys_valid.json
gen_base58_test_vectors.py invalid 50 > ../../src/test/data/base58_keys_invalid.json
'''
# 2012 Wladimir J. van der Laan
# R... | e, suffix, metadata
# None = N/A
((PUBKEY_ADDRESS,), 20, (), (False, False, 'pubkey', None)),
((SCRIPT_ADDRESS,), 2 | 0, (), (False, False, 'script', None)),
((PUBKEY_ADDRESS_TEST,), 20, (), (False, True, 'pubkey', None)),
((SCRIPT_ADDRESS_TEST,), 20, (), (False, True, 'script', None)),
((PRIVKEY,), 32, (), (True, False, None, False)),
((PRIVKEY,), 32, (1,), (True, False, None, True)),
... |
jamalmazrui/InPy | WebClient_XtraWordInfo.py | Python | lgpl-3.0 | 3,600 | 0.012778 | sWordInfo = ReadValue('WordInfo')
if not sWordInfo: sWordInfo = ReadValue('DictionaryLookup')
sWordInfo = IniFormDialogInput('Input', 'Word', sWordInfo)
if not sWordInfo: Exit()
WriteValue('WordInfo', sWordInfo)
SayLine('Please wait')
# sAddress = 'http://api.wordnik.com/api/word.json/' + sWordInfo + '/definition... | e0158'
# sAddress = 'http://words.bighugelabs.com/api/2/' + sApiKey + '/' + sWordInfo + ' + '/json'
sAddress = 'http://words.bighugelabs.com/api/2/' + sApiKey + '/' + sWordInfo + '/'
sResponse = WebRequestGetToString(sAddress)
sResponse = sResponse.replace('|syn|', '|synonym|')
sResponse = sResponse.replace('|ant|... | esponse.replace('|usr|', '|user suggestion|')
sResponse = sResponse.strip()
lResults = sResponse.split('\n')
sText = Pluralize('Result', len(lResults)) + ' from BigHugeLabs.com\r\n\r\n'
for sResult in lResults:
lParts = sResult.split('|')
sText += lParts[0] + ', ' + lParts[1] + '\r\n' + lParts[2] + '\r\n\r\n'
... |
MichaelDoyle/Diamond | src/collectors/etcdstat/test/test_etcdstat.py | Python | mit | 4,410 | 0.000227 | #!/usr/bin/python
# coding=utf-8
##########################################################################
from diamond.collector import Collector
from test import CollectorTestCase
from test import get_collector_config
from test import unittest
from mock import patch
from mock import Mock
from etcdstat import EtcdC... | Mock(return_value=json.loads(
self.getFixture('store-metrics.json').getvalue())))
patch1_collector.start()
patch2_collector.start()
self.collector.collect()
patch2_collector.stop()
patch1_collector.stop()
metrics = {
'self.is_leader': 1,
... | 'self.sendBandwidthRate': 901.0908469747579,
'store.compareAndDeleteFail': 0,
'store.watchers': 51,
'store.setsFail': 123,
'store.createSuccess': 6468,
'store.compareAndSwapFail': 355,
'store.compareAndSwapSuccess': 9156,
'stor... |
elastacloud/libcloud | libcloud/test/compute/test_digitalocean.py | Python | apache-2.0 | 6,980 | 0.00043 | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use ... | )
self.assertTrue(len(locations) >= 1)
location = locations[0]
self.assertEqual(location.id, '1')
self.assertEqual(location.name, 'New York 1')
def test_list_nodes_success(self):
nodes = self.driver.list_nodes()
self.assertEqual(len(nodes), 1)
self.assertEqu... | image = NodeImage(id='invalid', name=None, driver=self.driver)
size = self.driver.list_sizes()[0]
location = self.driver.list_locations()[0]
DigitalOceanMockHttp.type = 'INVALID_IMAGE'
expected_msg = r'You specified an invalid image for Droplet creation. \(code: 404\)'
self.asse... |
bswartz/manila | manila/tests/cmd/test_api.py | Python | apache-2.0 | 1,877 | 0 | # Copyright 2015 Mirantis Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | manila import version
CONF = manila_api.CONF
class ManilaCmdApiTestCase(test.TestCase):
def setUp(self):
super(ManilaCmdApiTestCase, self).setUp()
sys.argv = ['manila-api']
def test_main(self):
self.mock_object(manila_api.log, 'setup')
self.mock_object(manila_api.log, 'regist... | IService')
manila_api.main()
process_launcher = manila_api.service.process_launcher
process_launcher.assert_called_once_with()
self.assertTrue(process_launcher.return_value.launch_service.called)
self.assertTrue(process_launcher.return_value.wait.called)
self.assertEqua... |
serprex/byteplay | sanitytest.py | Python | lgpl-2.1 | 640 | 0.023438 | #!/bin/python
#author: tobias mueller 13.6.13
#byteplay test
from sys import version_info
from dis import dis
if version_info.major == 3:
| if version_info.minor < 6:from byteplay import *
else:from wbyteplay import *
else:from byteplay2 import *
from pprint import pprint
def f(a, b):
res = a + b
return res
def g(a, b):
res = a + b if a < b else b + a
r = 0
for a in range(res):
r += 1
return r or 2
for x in (f, g):
... | )
print(x(3,5)) |
Varentsov/servo | tests/wpt/web-platform-tests/mixed-content/generic/tools/spec_validator.py | Python | mpl-2.0 | 5,868 | 0.001363 | #!/usr/bin/env python
from __future__ import print_function
import json, sys
from common_paths import *
def assert_non_empty_string(obj, field):
assert field in obj, 'Missing field "%s"' % field
assert isinstance(obj[field], basestring), \
'Field "%s" must be a string' % field
assert len(obj[fiel... | st_expansion_schema']
excluded_tests = spec_json['excluded_tests']
valid_test_expansion_fields = ['name'] + test_expansion_schema.keys()
# Validate each single spec.
for spec in specification:
details['object'] = spec
# Validate required fields for a single spec.
assert_contai... | cation_url',
'test_expansion'])
assert_non_empty_string(spec, 'name')
assert_non_empty_string(spec, 'title')
assert_non_empty_string(spec, 'description')
assert_non_empty_string(spec, 'specification_url')
assert_non_empty_list(spec, 'tes... |
exploreodoo/datStruct | odoo/addons/hw_proxy/controllers/main.py | Python | gpl-2.0 | 7,800 | 0.005769 | # -*- coding: utf-8 -*-
import logging
import commands
import simplejson
import os
import os.path
import openerp
import time
import random
import subprocess
import simplejson
import werkzeug
import werkzeug.wrappers
_logger = logging.getLogger(__name__)
from openerp import http
from openerp.http import request
# Tho... | none', cors='*')
def help_canceled(self):
"""
The user stops the help request
"""
print "help_canceled"
@http.route('/hw_proxy/payment_request', type='json', auth='none', cors='*')
def payment_request(self, price):
"""
The PoS will activate the method payment... | tr(price)
return 'ok'
@http.route('/hw_proxy/payment_status', type='json', auth='none', cors='*')
def payment_status(self):
print "payment_status"
return { 'status':'waiting' }
@http.route('/hw_proxy/payment_cancel', type='json', auth='none', cors='*')
def payment_cancel(self)... |
RydrDojo/Ridr_app | app/controllers/Users.py | Python | mit | 4,431 | 0.00316 | from system.core.controller import *
from rauth import OAuth2Service
from flask import redirect, request
import urllib2
import json
from time import strftime
facebook = OAuth2Service(
name='facebook',
base_url='https://graph.facebook.com/',
access_token_url='/oauth/access_token',
authorize_url='https:/... | ken?client_id=" +
app_id + "&redirect_uri=http://localhost:5000/oauth-authorized/&client_secret"
"=c5b9a2e1e25bfa25abc75a9cd2af450a&code=" + code).read()
token = json.loads(json_str)
token = token['access_token']
fb_session =... | st_name,email', params={'format': 'json'}).json()
user_picture = fb_session.get('/me?fields=picture', params={'format': 'json'}).json()
if register_data:
user = self.models['User'].add_user(register_data)
if user['status']:
# just registered
sessio... |
indictranstech/tele-erpnext | erpnext/config/hr.py | Python | agpl-3.0 | 4,677 | 0.044901 | from __future__ import unicode_literals
from frappe import _
def get_data():
return [
{
"label": _("Documents"),
"icon": "icon-star",
"items": [
{
"type": "doctype",
"name": "Employee",
"description": _("Employee records."),
},
{
"type": "doctype",
"name": "Leave Applic... |
"type": "report",
"is_query_report": True,
"name": "Employee Birthday",
"doctype": "Employee"
},
{
"type": | "report",
"name": "Employee Information",
"doctype": "Employee"
},
{
"type": "report",
"is_query_report": True,
"name": "Monthly Salary Register",
"doctype": "Salary Slip"
},
{
"type": "report",
"is_query_report": True,
"name": "Monthly Attendance Sheet",
... |
bitcraft/pyglet | contrib/experimental/mt_media/mt_app_win32.py | Python | bsd-3-clause | 2,590 | 0.001158 | #!/usr/bin/python
# $Id:$
import ctypes
import queue
import pyglet
from pyglet.window.win32 import kernel32, user32, constants, types
class MTWin32EventLoop(pyglet.app.win32.Win32EventLoop):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# Force immediate creation of an... | user32.GetMessageW(ctypes.byref(msg), 0, 0, 0)
user32.TranslateMessage(ctypes.byref(msg))
user32.DispatchMessageW(ctypes.byref(msg))
# Manual idle event
| msg_types = \
user32.GetQueueStatus(constants.QS_ALLINPUT) & 0xffff0000
if (msg.message != constants.WM_TIMER and
not msg_types & ~(constants.QS_TIMER << 16)):
self._timer_func(0, 0, timer, 0)
self._dispatch_posted_events()
... |
z1gm4/desarrollo_web_udp | desarrolloweb/apps.py | Python | gpl-3.0 | 101 | 0 | from django.apps import AppConfig
class DesarrollowebConfig(Ap | pConfig):
name = 'd | esarrolloweb'
|
pwmarcz/django | django/contrib/auth/models.py | Python | bsd-3-clause | 17,843 | 0.001121 | from __future__ import unicode_literals
from django.core.exceptions import PermissionDenied
from django.core.mail import send_mail
from django.core import validators
from django.db import models
from django.d | b.models.manager import EmptyManager
from django.utils.crypto import get_random_string, salted_hmac
from django.utils import six
from django.utils.translation import ugettext_lazy as _
from django.utils import timezone
from django.contrib import auth
from django.con | trib.auth.hashers import (
check_password, make_password, is_password_usable)
from django.contrib.auth.signals import user_logged_in
from django.contrib.contenttypes.models import ContentType
from django.utils.encoding import python_2_unicode_compatible
def update_last_login(sender, user, **kwargs):
"""
A... |
LPgenerator/django-db-mailer | dbmail/providers/microsoft/raw.py | Python | gpl-2.0 | 250 | 0 | from dbmail.providers.microsoft.base import MPNSBase
class MPNSR | aw(MPNSBase):
NOTIFICATION_CLS = 3
TARGET = ' | raw'
def payload(self, payload):
return payload
def send(uri, *_, **kwargs):
return MPNSRaw().send(uri, kwargs)
|
dl1ksv/gr-display | docs/doxygen/doxyxml/text.py | Python | gpl-3.0 | 1,297 | 0.003084 | #
# Copyright 2010 Free Software Foundation, Inc.
#
# This file was generated by gr_modtool, a tool from the GNU Radio framework
# This file is a part of gr-display
#
# SPDX-License-Identifier: GPL-3.0-or-later
#
#
"""
Utilities for extracting text | from generated classes.
"""
from __future__ import unicode_literals
def is_string(txt):
if isinstance(txt, str):
return True
try:
if isinstance(txt, str):
return True
except NameError:
pass
return False
def description(obj):
if obj is None:
return None
... | n_bit(obj):
if hasattr(obj, 'content'):
contents = [description_bit(item) for item in obj.content]
result = ''.join(contents)
elif hasattr(obj, 'content_'):
contents = [description_bit(item) for item in obj.content_]
result = ''.join(contents)
elif hasattr(obj, 'value'):
... |
IndicoDataSolutions/IndicoIo-python | indicoio/text/sentiment.py | Python | mit | 1,009 | 0.003964 | from ..utils.api import a | pi_handler
from ..utils.decorators import detect_batch_decorator
@detect_batch_decorator
def sentiment(text, cloud=None, batch=False, api_key=None, version=None, **kwargs):
"""
Given input text, returns a scalar estimate of the sentiment of that text.
Values are roughly in the range 0 to 1 with 0.5 indica... | . code-block:: python
>>> from indicoio import sentiment
>>> text = 'Thanks everyone for the birthday wishes!! It was a crazy few days ><'
>>> sentiment = sentiment(text)
>>> sentiment
0.6946439339979863
:param text: The text to be analyzed.
:type text: str or unicode
:r... |
sgarrad/hicks | config/urls.py | Python | gpl-3.0 | 1,959 | 0.001021 | """hicks URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/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')
Class-based... | log_urls))
"""
from django.conf import settings
from django.conf.urls import include, url
from django.contrib import | admin
from django.views.generic import TemplateView
urlpatterns = [
# Toolbar static pages
url( # /
regex=r'^$',
view=TemplateView.as_view(template_name='pages/home.html'),
name='home'),
url( # /about/
regex=r'^about/$',
view=TemplateView.as_view(template... |
dawran6/flask | tests/test_regression.py | Python | bsd-3-clause | 2,409 | 0 | # -*- coding: utf-8 -*-
"""
tests.regression
~~~~~~~~~~~~~~~~~~~~~~~~~~
Tests regressions.
:copyright: (c) 2015 by Armin Ronacher.
:license: BSD, see LICENSE for more details.
"""
import gc
import sys
import threading
import pytest
from werkzeug.exceptions import NotFound
import flask
_gc_lock... |
# This is necessary since Python only starts tracking
# dicts if they contain mutable objects. It's a horr | ible,
# horrible hack but makes this kinda testable.
loc.__storage__['FOOO'] = [1, 2, 3]
gc.collect()
self.old_objects = len(gc.get_objects())
def __exit__(self, exc_type, exc_value, tb):
gc.collect()
new_objects = len(gc.get_objects())
if new_objects > self... |
mpw1337/RocketMap | pogom/search.py | Python | agpl-3.0 | 56,889 | 0 | #!/usr/bin/python
# -*- coding: utf-8 -*-
'''
Search Architecture:
- Have a list of accounts
- Create an "overseer" thread
- Search Overseer:
- Tracks incoming new location values
- Tracks "paused state"
- During pause or new location will clears current search queue
- Starts search_worker threads
- Se... | RITICAL)
display_type[0] = 'failedaccounts'
elif command.lower() == 'h':
mainlog.handlers[0].setLevel(logging.CRITICAL)
display_type[0] = 'hashstatus'
# Thread to print out the status of each wo | rker.
def status_printer(threadStatus, search_items_queue_array, db_updates_queue,
wh_queue, account_queue, account_failures, account_captchas,
logmode, hash_key, key_scheduler):
if (logmode == 'logs'):
display_type = ['logs']
else:
display_type = ['workers... |
ftrader-bitcoinabc/bitcoin-abc | share/qt/extract_strings_qt.py | Python | mit | 2,747 | 0.001456 | #!/usr/bin/env python3
# Copyright (c) 2012-2017 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
'''
Extract _("...") strings for translation and convert to Qt stringdefs so that
they can be picked up by... | d, msgstr))
in_msgstr = False
# message start
in_msgid = True
msgid = [line[6:]]
elif line.startswith('msgstr '):
in_msgid = False
in_msgstr = True
msgstr = [line[7:]]
elif line.startswith('"'):
if in_ms... | msgid.append(line)
if in_msgstr:
msgstr.append(line)
if in_msgstr:
messages.append((msgid, msgstr))
return messages
files = sys.argv[1:]
# xgettext -n --keyword=_ $FILES
XGETTEXT = os.getenv('XGETTEXT', 'xgettext')
if not XGETTEXT:
print(
'Cannot extra... |
phoebe-project/phoebe2-docs | 2.2/examples/binary_spots.py | Python | gpl-3.0 | 1,686 | 0.008304 | #!/usr/bin/env python
# coding: utf-8
# Binary with Spots
# ============================
#
# Setup
# -----------------------------
# Let's first make sure we have the latest version of PHOEBE 2.2 installed. (You c | an comment out this line if you don't use pip for your installation or don't want to update to the latest release).
# In[ ]:
get_ipython().system('pip install -I "phoebe>=2.2,<2.3"')
# As always, let's do imports and initialize a logger and a new bundle. See [Building a System](../tutorials/b | uilding_a_system.ipynb) for more details.
# In[1]:
get_ipython().run_line_magic('matplotlib', 'inline')
# In[2]:
import phoebe
from phoebe import u # units
import numpy as np
import matplotlib.pyplot as plt
logger = phoebe.logger()
b = phoebe.default_binary()
# Model without Spots
# -------------------------... |
uber/ludwig | ludwig/data/dataset/pandas.py | Python | apache-2.0 | 3,028 | 0 | #! /usr/bin/env python
# coding=utf-8
# Copyright (c) 2019 Uber Technologies, 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
#
# Unles... | with h5py.File(self.data_hdf5_fp, 'r') as h5_file:
im_data = h5_file[proc_column + '_data'][indices[0, :], :, :]
indices[2, :] = np.arange(len(sub_batch))
| indices = indices[:, np.argsort(indices[1])]
return im_data[indices[2, :]]
def get_dataset(self):
return self.dataset
def __len__(self):
return self.size
def initialize_batcher(self, batch_size=128,
should_shuffle=True,
see... |
dudanogueira/microerp | microerp/comercial/migrations/0047_itemgrupodocumento_titulo_centralizado.py | Python | lgpl-3.0 | 430 | 0 | # -*- coding: utf-8 -*-
from __fut | ure__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('comercial', '0046_auto_20151004_1747'),
]
operations = [
migrations.AddField(
model_name='itemgrupodocumento', |
name='titulo_centralizado',
field=models.BooleanField(default=False),
),
]
|
tim-clifford/py-cipher | src/test1.py | Python | mit | 569 | 0.038664 | import file
ciphertext = str(f | ile.openAsAscii("cipher.txt"),"utf-8").replace(" ","")
matches = 0
diffs = set()
N=5
print(len(ciphertext)/N)
for wordlen in range(N*5,N*8,N):
print("Wordlen: {0}".format(wordlen))
for wordIndex in range(len(ciphertext)-wordlen):
for word2Index in range(wordIndex+wordlen,len(ciphertext) - wordlen,N):
word,word2 ... | diffs.add(word2Index - wordIndex)
print(diffs) |
alexherns/biotite-scripts | compare_blasts.py | Python | mit | 1,490 | 0.015436 | #!/usr/bin/env python2.7
import sys, getopt
if len(sys.argv) < 3:
print """
Usage: compare_blast.py <input1.b6> <input2.b6>
"""
blast1= sys.argv[1]
blast2= sys.argv[2]
dict1= {}
for line in open(blast1):
line= line.strip().split("\t")
query= line[0].split()[0]
dict1[query]= line
dict2= {}
for line ... | t(".b6")[0] + "_bad.b6"
blast2better= blast2.split(".b6")[0] + "_good.b6"
blast2worse= blast2.split(".b6")[0] + "_bad.b6"
b1b_handle= open(blast1better, 'w')
b1w_handle= open(blast1worse, 'w')
b2b_handle= open(blast2better, 'w')
b2w_handle= open(blast2worse, 'w')
for query in dict1:
line1= dict1[query]
if que... | 2[-1]):
b1b_handle.write("\t".join(line1)+"\n")
else:
b1w_handle.write("\t".join(line1)+"\n")
for query in dict2:
line2= dict2[query]
if query not in dict1:
b2b_handle.write("\t".join(line2)+"\n")
else:
line1= dict1[query]
if float(line2[-1]) > float(... |
muhleder/timestrap | core/models.py | Python | bsd-2-clause | 6,476 | 0.000463 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from datetime import date
from decimal import Decimal, ROUND_DOWN
from django.contrib.sites.models import Site
from django.db import models
from django.db.models import Sum
from django.db.models.signals import post_save
from django.dispatch import receiv... | model's sites property after a save. This is
required in post save because ManyToManyField fiel | ds require an existing
key.
TODO: Don't run this on *every* post_save.
"""
if hasattr(instance, 'sites'):
if not instance.sites.all():
instance.sites = Site.objects.filter(id=current_site_id())
instance.save()
class Client(models.Model):
name = models.CharField(max... |
assertnotnull/servicebusmtl | servicebusmtl/servicebusmtl/settings/local.py | Python | mit | 1,780 | 0.007865 | """Development settings and globals."""
from os.path import join, normpath
from base import *
########## DEBUG CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#debug
DEBUG = True
# See: https://docs.djangoproject.com/en/dev/ref/settings/#template-debug
TEMPLATE_DEBUG = DEBUG
########## END... | /github.com/django-debug-toolbar/django-debug-toolbar#installation
INTERNAL_IPS = ('127.0.0.1',)
# See: https://github.com/django-debug-toolbar/django-debug-toolbar#installation
MIDDLEWARE_CLASSES += (
'debug_toolbar.middleware.DebugToolbarMiddleware',
)
# See: https://github.com/django-debug-toolbar/django-debug... | #installation
DEBUG_TOOLBAR_CONFIG = {
'INTERCEPT_REDIRECTS': False,
'SHOW_TEMPLATE_CONTEXT': True,
}
########## END TOOLBAR CONFIGURATION
|
starrify/scrapy | scrapy/utils/sitemap.py | Python | bsd-3-clause | 1,501 | 0.000666 | """
Module for processing Sitemaps.
Note: The main purpose of this module is to provide support for the
SitemapSpider, its API is subject to change without notice.
"""
from urllib.parse import urljoin
import lxml.etree
class Sitemap:
"""Class to parse Sitemap (type=urlset) and Sitemap Index
(type=sitemapin... | ve_comments=True, resolve_entities=False)
self._root = lxml.etree.fromstring(xmltext, parser=xmlp)
rt = self._root.tag
self.type = self._root.tag.split('}', 1)[1] if '}' in rt else rt
def __iter__(self):
for elem in self._root.getchildren():
d = {}
| for el in elem.getchildren():
tag = el.tag
name = tag.split('}', 1)[1] if '}' in tag else tag
if name == 'link':
if 'href' in el.attrib:
d.setdefault('alternate', []).append(el.get('href'))
else:
... |
philiptzou/taxonwiki | taxonwiki/models/author.py | Python | mit | 331 | 0 | # -*- c | oding: utf-8 -*-
from flask import current_app as app
from sqlalchemy_utils import TSVectorType
db = app.db
class Author(db.Model):
id = db.Column(db.Integer(), primary_key=True, nullable=False)
name = db.Column(db.Unicode(1024), nullable=False, unique=True)
name_vector = db.Column(TSVectorType('name... | |
jimperio/pelican | pelican/server.py | Python | agpl-3.0 | 2,272 | 0 | # -*- coding: utf-8 -*-
from __future__ import print_function, unicode_literals
import logging
import os
import sys
try:
| from magic import from_file as magic_from_file
except ImportError:
magic_from_file = None
from six.moves import SimpleHTTPServer as srvmod
from six.moves import socketserver
class ComplexHTTPRequestHandler(srvmod.SimpleHTTPRequestHandler):
SUFFIXES = ['', '.html', '/index.html']
def do_GET(self):
| # Try to detect file by applying various suffixes
for suffix in self.SUFFIXES:
if not hasattr(self, 'original_path'):
self.original_path = self.path
self.path = self.original_path + suffix
path = self.translate_path(self.path)
if os.path.ex... |
scott-maddox/simplepl | src/simplepl/instruments/drivers/thorlabs_fw102c_sim.py | Python | agpl-3.0 | 3,169 | 0.005364 | #
# Copyright (c) 2013-2014, Scott J Maddox
#
# This file is part of SimplePL.
#
# SimplePL 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 opt... | You should have received a copy of the GNU Affero General Public
# License along with SimplePL. If not, see
# <http://www.gnu.org/licenses/>.
#
#######################################################################
# std lib imports
im | port logging
log = logging.getLogger(__name__)
import time
import string
# third party imports
#import serial
# local imports
SLEEP_TIME = 0.01
#TODO: make sure the asked for nm is available on the given grating?
class FW102C(object):
'''
Device driver for ThorLabs FW102C Motorized Filter Wheel.
'''
... |
closeio/nylas | migrations/versions/239_server_default_created_at.py | Python | agpl-3.0 | 1,186 | 0.006745 | """switch to server-side creation timestamps
Revision ID: 1dfc65e583bf
Revises: 1b0b4e6fdf96
Create Date: 2018-02-08 23:06:09.384416
"""
# revision identifiers, used by Alembic.
revision = '1dfc65e583bf'
down_revision = '1b0b4e6fdf96'
from alembic import op
from sqlalchemy.sql import text
# SELECT table_name FROM ... | d', 'label', 'labelitem', 'message', 'messagecategory', 'messagecontactassociation', 'metadata', 'namespace', | 'part', 'phonenumber', 'secret', 'thread', 'transaction']
def upgrade():
conn = op.get_bind()
for table in TABLES:
conn.execute(text('ALTER TABLE `{}` MODIFY COLUMN `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP'.format(table)))
def downgrade():
conn = op.get_bind()
for table in TAB... |
dparks1134/DrawM | drawm/__init__.py | Python | gpl-3.0 | 1,491 | 0.000671 | ###############################################################################
# #
# 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 ... |
# You should have received a copy of the GNU General Public License #
# along with this program. If not, see <http://www.gnu.org/licenses/>. #
# #
############################################################################... | rsion_file.read().strip()
|
cwrucutter/snowmower_obstacles | test/test_obstacle_avoidance.py | Python | mit | 3,038 | 0.004937 | import sys
sys.path.insert(0,'../src/')
# Begin From obstacle_avoidance
import rospy
import math
from math import sin, cos
from geometry_msgs.msg import Twist
from sensor_msgs.msg import LaserScan
from collections import namedtuple
Obstacle = namedtuple('Obstacle', ['r', 'theta'])
# End From obstacle_avoidance
from ... | 8))<0.001)
if __name__ == | '__main__':
unittest.main()
|
aturley/spaceshooter | server-demogame.py | Python | gpl-3.0 | 4,932 | 0.006894 | from os import curdir, sep
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
from urlparse import urlparse, parse_qs
from subprocess import call
import SocketServer
import osc
import random
import json
import socket
import sys
class Drummers(object):
def __init__(self):
self.drummer_map = {}
... | /demo-game.html", "/demo-drum.html", "/touchlib.js", "/"]):
try:
if (self.path == "/"):
self.path = "/demo-game.html"
f = open(curdir + sep + self.path) #self.path has /test.html
self.send_response(200)
self.send_header('Con... | e()
except IOError:
self.send_error(404,'File Not Found: %s' % self.path)
else:
self.send_error(404,'File Not Found: %s' % self.path)
def main():
try:
# server = HTTPServer(('', PORT), MyHandler)
server = ThreadedHTTPServer(('', PORT), MyHandler)
... |
arnaudsj/restkit | restkit/contrib/webob_api.py | Python | mit | 2,457 | 0.003256 | #!/usr/bin/env python
# -*- coding: utf-8 -
#
# This file is part of restkit released under the MIT license.
# See the NOTICE for more information.
from StringIO import StringIO
import urlparse
import urllib
try:
from webob import Request as BaseRequest
except ImportError:
raise ImportError('WebOb (http://py... | __call__ = get_response
def set_url(self, url_or_path):
path = url_or_path.lstrip('/')
if '?' in path:
path, self.query_string = pat | h.split('?', 1)
if path.startswith('http'):
url = path
else:
self.path_info = '/'+path
url = self.url
self.scheme, self.host, self.path_info = urlparse.urlparse(url)[0:3]
|
hlzz/dotfiles | graphics/VTK-7.0.0/ThirdParty/Twisted/twisted/python/threadpool.py | Python | bsd-3-clause | 8,392 | 0.002026 | # -*- test-case-name: twisted.test.test_threadpool -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
twisted.python.threadpool: a pool of threads to which we dispatch tasks.
In most cases you can just use C{reactor.callInThread} and friends
instead of creating a thread pool direc... | onResult, func, *args, **kw):
"""
Call a callable object in a separate thread and call C{onResult}
with the return value, or a L{twisted.python.failure.Failure}
if the callable raises an exception.
| The callable is allowed to block, but the C{onResult} function
must not block and should perform as little work as possible.
A typical action for C{onResult} for a threadpool used with a
Twisted reactor would be to schedule a
L{twisted.internet.defer.Deferred} to fire in th... |
seckcoder/lang-learn | python/sklearn/examples/svm/plot_weighted_samples.py | Python | unlicense | 999 | 0.003003 | """
=====================
SVM: Weighted samples
=====================
Plot decision function of a weighted dataset, where the size of points
is proportional to its weight.
"""
print __doc__
import numpy as np
import pylab as pl
from sklearn import svm
# we create 20 points
np.random.seed(0)
X = np.r_[np.random.randn... | y = np.meshgrid(np.linspace(-4, 5, 500), np.linspace(-4, 5, 500))
Z = clf.decision_function(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)
# plot the line, the points, and the nearest vectors to the plane
pl.contourf(xx, yy, Z, alpha=0.75, cmap=pl.cm.bone)
pl.scatter(X[:, | 0], X[:, 1], c=Y, s=sample_weight, alpha=0.9, cmap=pl.cm.bone)
pl.axis('off')
pl.show()
|
jendrikseipp/rednotebook-elementary | win/build-translations.py | Python | gpl-2.0 | 569 | 0.005272 | #! /usr/bin/env python3
from __future__ import print_function
import argparse
import os
impor | t sys
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('locale_dir')
return parser.parse_args()
args = parse_args()
basedir = os.path.abspath(os.path.join(os.path.abspath(__file__), '..', '..'))
sys.path.insert(0, basedir)
import setup
po_dir = os | .path.join(basedir, 'po')
locale_dir = os.path.abspath(args.locale_dir)
print('Building translations')
print(po_dir, '-->', locale_dir)
setup.build_translation_files(po_dir, locale_dir)
|
clinton-hall/nzbToMedia | libs/common/beets/vfs.py | Python | gpl-3.0 | 1,839 | 0 | # -*- coding: utf-8 -*-
# This file is part of beets.
# Copyright 2016, Adrian Sampson.
#
# 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 t... | # permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
"""A simple utility for constructing filesystem-like trees from beets
libraries.
"""
f... | ure__ import division, absolute_import, print_function
from collections import namedtuple
from beets import util
Node = namedtuple('Node', ['files', 'dirs'])
def _insert(node, path, itemid):
"""Insert an item into a virtual filesystem node."""
if len(path) == 1:
# Last component. Insert file.
... |
masschallenge/django-accelerator | simpleuser/models.py | Python | mit | 6,632 | 0 | import uuid
from django.db import models
from django.conf import settings
from django.contrib.auth.models import AbstractUser
from django.contrib.auth.models import BaseUserManager
from django.utils import timezone
from accelerator_abstract.models import BaseUserRole
from accelerator_abstract.models.base_base_profile... | __init__(self, *args, **kwargs):
super(User, | self).__init__(*args, **kwargs)
self.startup = None
self.team_member = None
self.profile = None
self.user_finalist_roles = None
class AuthenticationException(Exception):
pass
def __str__(self):
return self.email
def full_name(self):
fn = self.first... |
megalut/sewpy | setup.py | Python | gpl-3.0 | 310 | 0.029032 | #!/usr/bin/env py | thon
from distutils.core import setup
setup(
name='sewpy',
versi | on='1.0dev',
packages=['sewpy'],
description='Source Extractor Wrapper for Python',
long_description=open('README.rst').read(),
author='The MegaLUT developers',
license='GPLv3',
url='http://github.com/megalut/sewpy'
)
|
jordanemedlock/psychtruths | temboo/core/Library/SunlightLabs/Congress/Legislator/Search.py | Python | apache-2.0 | 5,201 | 0.005768 | # -*- coding: utf-8 -*-
###############################################################################
#
# Search
# Returns current committees, subcommittees, and their membership.
#
# Python versions 2.6, 2.7, 3.x
#
# Copyright 2014, Temboo Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# y... | ber of results to return per page.)
"""
super(SearchInputSet, self)._set_input('PerPage', value)
de | f set_Query(self, value):
"""
Set the value of the Query input for this Choreo. ((conditional, string) A search term.)
"""
super(SearchInputSet, self)._set_input('Query', value)
def set_ResponseFormat(self, value):
"""
Set the value of the ResponseFormat input for thi... |
obi-two/Rebelion | data/scripts/templates/object/tangible/painting/shared_painting_leia_wanted.py | Python | mit | 450 | 0.046667 | #### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Tangible()
result.template = "object/tangible/painting/shared_painting_leia_wanted.iff"
result.attribute_template... | result | |
jonfoster/pyxb-upstream-mirror | tests/datatypes/test-QName.py | Python | apache-2.0 | 848 | 0.01533 | # -*- coding: utf-8 -*-
from __future__ import print_function
import logging
if __name__ == '__main__':
logging.basicConfig()
_log = logging.getLogger(__name__)
from pyxb.exceptions_ import *
import unittest
import pyxb.binding.datatypes as xsd
class Test_QName (unittest.TestCase):
def testValid (self):
... | onName', '-also:-not', 'and:-not', 'too:many:colons', ' whitespace ' ]
for f in invalid:
try:
| xsd.QName(f)
print('Unexpected pass with %s' % (f,))
except:
pass
self.assertRaises(SimpleTypeValueError, xsd.QName, f)
if __name__ == '__main__':
unittest.main()
|
totorigolo/WiiQuizz | ListDialog.py | Python | gpl-2.0 | 1,552 | 0.001935 | # coding=utf-8
from WindowHelper import WindowHelper
from constants import *
class ListDialog:
def __init__(self):
self.win = WindowHelper.Instance()
self.win.new_color((5, 51, 90), 'dark_blue')
| self.win.new_color((176, 194, 238), 'light_blue')
self.win.new_font('Arial', 40, 'title')
self.win.new_font('Arial', 20, 'sub_title')
self.win.new_font('Arial', 25, 'options')
def get_answer(self, choices, question=None, sub_text=None):
page_label = self.win.go_to(self.win.new_pa... | alog', question)
else:
self.win.edit_text('title_list_dialog', " ") # TODO: Permettre de supprimer des éléments des templates
if sub_text is not None:
self.win.edit_text('sub_title_list_dialog', sub_text)
else:
self.win.edit_text('sub_title_list_dialog', " ")... |
Hexadorsimal/pynes | nes/processors/registers/register.py | Python | mit | 166 | 0 | class Register:
@property
def | value(self):
raise NotImplementedError
@value.setter
def v | alue(self, value):
raise NotImplementedError
|
uHappyLogic/lost-wumpus | agents/snake_agent.py | Python | mit | 1,993 | 0.005018 | # Przykladowy agent do zadania 'zagubiony Wumpus'. Agent porusza sie wezykiem.
import random
from action import Action
# nie zmieniac nazwy klasy
class Agent:
# nie zmieniac naglowka konstruktora, tutaj agent dostaje wszystkie informacje o srodowisku
def __init__(self, p, pj, pn, height, width, areaMap):
... | mietac zmienne obiektu
self.p = p
self.pj = pj
self.pn = pn
self.height = height
self.width = width
self.map = areaMap
# w tym przykladzie histogram wypelniany jest tak aby na planszy wyszedl gradient
self.hist = []
for y in range(self.height):
... | x in range(self.width):
self.hist[y].append(float(y + x) / (self.width + self.height - 2))
# dopisac reszte inicjalizacji agenta
return
# nie zmieniac naglowka metody, tutaj agent dokonuje obserwacji swiata
# sensor przyjmuje wartosc True gdy agent ma uczucie stania w jamie
... |
DataMonster/Python | web/MyShop/myshop/models.py | Python | unlicense | 2,927 | 0.022549 | from datetime import datetime
from sqlalchemy import (
Column,
ForeignKey,
Integer,
Text,
Unicode,
)
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import (
scoped_session,
sessionmaker,
relationship
)
from zope.sqlalchemy import ZopeTransactionExtension
DBSession = scoped_ses... | class ItemImage(Base):
__tablename__ = 'images'
id = Column(Integer, primary_key=True)
path = Column(Unicode(255), nullable=False)
item_id = Column(Integer, ForeignKey('items.id'), nullable=False)
item = relationship('Item', backref='images')
class Comment(Base):
__tablename__ = 'comments'
id = Column(Intege... | backref='comments')
item_id = Column(Item, ForeignKey('items.id'), nullable=False)
item = relationship('Item', backref='comments')
rank = Column(Integer, nullable=False, default=3);
content = Column(Text)
class Cart(Base):
__tablename__ = 'carts'
id = Column(Integer, primary_key=True)
# TODO: Many-to-many
... |
akrherz/idep | scripts/convergence/dump_results.py | Python | mit | 656 | 0 | """blah."""
from pyiem.util import get_dbconn
pgconn = get_dbconn("idep")
cursor = pgconn.cursor()
cursor.execute(
"""
SELECT r.hs | _id, r.huc_12, p.fpath, extract(year from valid) as yr,
sum(runoff) as sum_runoff,
sum(loss) as sum_loss, sum(delivery) as sum_delivery from
results r JOIN flowpaths p on (r.hs_id = p.fid)
WHERE r.scenario = 5
GROUP by r.hs_id, r.huc_12, fpath, yr
"""
)
print("CATCHMENT,HUC12,FPATH,YEAR,RUNOFF,LOSS,DELIVERY"... | ow[0]
if fpath < 100:
catchment = 0
else:
catchment = int(str(fpath)[:-2])
print(str(catchment) + ",%s,%s,%s,%.4f,%.4f,%.4f" % row[1:])
|
lixt/lily2-gem5 | src/arch/lily2/Lily2System.py | Python | bsd-3-clause | 2,762 | 0.003259 | # -*- mode:python -*-
# Copyright (c) 2007 MIPS Technologies, 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 ... | t64("Revision of system we are emulating")
loa | d_addr_mask = 0xffffffffff
class LinuxLily2System(Lily2System):
type = 'LinuxLily2System'
cxx_header = 'arch/lily2/linux/system.hh'
system_type = 34
system_rev = 1 << 10
boot_cpu_frequency = Param.Frequency(Self.cpu[0].clk_domain.clock.frequency,
"boot proc... |
conversis/varstack | setup.py | Python | mit | 697 | 0.010043 | import os, sys
from setuptools import setup, find_packages
version = '0.4'
install_requires = ['setuptools', 'PyYAML']
| if sys.version_info < (2, 7):
install_requires.append('simplejson')
install_requires.append('argparse')
def read(fname):
return open(os.path.join(os.path.dir | name(__file__), fname)).read()
setup(
name='varstack',
version=version,
description='A tool to create stacked configuration structures',
url = 'https://github.com/conversis/varstack',
license = 'MIT',
author='Dennis Jacobfeuerborn',
author_email='d.jacobfeuerborn@conversis.de',
packages... |
sunqm/pyscf | pyscf/pbc/lib/arnoldi.py | Python | apache-2.0 | 10,549 | 0.010522 | # Copyright 2014-2021 The PySCF Developers. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... | ]
w = w[idx].real
self.sol[:self.currentSize] = v[:,self.ciEig]
self.evecs[:self.currentSize,:self.currentSize] = v
self.eigs[:self.currentSize] = w[:self.currentSize]
| self.outeigs[:self.nEigen] = w[:self.nEigen]
self.cvEig = self.eigs[self.ciEig]
def constructAllSolV(self):
for i in range(self.nEigen):
self.sol[:] = self.evecs[:,i]
self.cv = np.dot(self.vlist[:self.currentSize].transpose(),self.sol[:self.currentSize])
self.... |
Achint08/open-event-orga-server | tests/unittests/views/guest/test_guest_event_page.py | Python | gpl-3.0 | 7,240 | 0.001657 | import unittest
from datetime import datetime
from flask import url_for
from app import current_app as app
from app.helpers.data import save_to_db
from app.models.call_for_papers import CallForPaper
from tests.unittests.object_mother import ObjectMother
from tests.unittests.utils import OpenEventTestCase
class Test... | display_event_schedule', identifier=event.identifier),
follow_redirects=True)
self.assertEqual(rv.status_code, 404)
def test_published_event_cfs_view(self):
with app.test_request_context():
event = ObjectMother.get_event()
event.state = 'Pub... | t Saved")
custom_form = ObjectMother.get_custom_form()
custom_form.event_id = event.id
save_to_db(custom_form, "Custom form saved")
call_for_papers = CallForPaper(announcement="Announce",
start_date=datetime(2003, 8, 4, 12, 30,... |
sinraf96/electrum | qa/rpc-tests/replace-by-fee.py | Python | mit | 21,883 | 0.001188 | #!/usr/bin/env python3
# Copyright (c) 2014-2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
# Test replace by fee code
#
from test_framework.test_framework import ElectrumTestFramework
from test... | unning test spends of conflicting outputs...")
self.test_spends_of_conflicting_outputs()
print("Running test new unconfirmed inputs...")
self.test_new_unconfirmed_inputs()
print("Running test too many replacements...")
self.test_too_many_replacements()
p | rint("Running test opt-in...")
self.test_opt_in()
print("Running test prioritised transactions...")
self.test_prioritised_transactions()
print("Passed\n")
def test_simple_doublespend(self):
"""Simple doublespend"""
tx0_outpoint = make_utxo(self.nodes[0], int(1.1*CO... |
mikemike/SkypeBot | unused-modules/stateful.py | Python | gpl-2.0 | 2,755 | 0.004356 | """
Stateful module base class and interface description.
All stateful Python modules
- Get Skype4Py Skype instance on init - have full control over Skype and
thus are not limited to !command handlers
- Reside in the some modules/ folder as UNIX script modules
- Have .py extension and be ... | UnregisterEventHandler(event, | callback)
|
MarcosCommunity/odoo | comunity_modules/purchase_landed_cost/models/purchase_cost_distribution.py | Python | agpl-3.0 | 22,280 | 0.00009 | # -*- coding: utf-8 -*-
##############################################################################
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
#... | a confirmed cost distribution"))
return super(PurchaseCostDistribution, self).unlink()
@api.model
def create(self, vals):
if vals.get('name', '/') == '/':
vals['name'] = self.env['ir.sequence'].next_by_code(
'purchase.cost.distribution')
return super(Purchas... | n, self).create(vals)
@api.multi
def action_calculate(self):
for distribution in self:
# Check expense lines for amount 0
if any([not x.expense_amount for x in distribution.expense_lines]):
raise exceptions.Warning(
_('Please enter an amount f... |
groupe-sii/ogham | .tools/showcase-recorder/showcase-launcher/play_showcase.py | Python | apache-2.0 | 2,008 | 0.005976 | import argparse
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as ec
from selenium.webdriver.common.by import By
import time
import socket
import os
import os.path
from pathlib import Path
def clean(file):
try:
... | t(chrome, wait_timeout).until(ec.visibility_of_element_located((By.CSS_SELECTOR, '.the-end')))
chrome.quit()
def wait_until_video_is_exported(fil | e, timeout):
time_counter = 0
while not os.path.exists(file):
time.sleep(1)
time_counter += 1
if time_counter > timeout:break
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Run chrome browser on provided url.')
parser.add_argument('url')
parser.... |
caithess/taskbuster | taskbuster/views.py | Python | mit | 451 | 0 | # -*- coding: utf | -8 -*-
import datetime
from django.shortcuts import render
from django.utils.timezone import now
from django.utils.translation import ugettext_lazy as _
def home(request):
today = datetime.date.today()
return render(request, "taskbuster/index.html",
{'today': today,
'now':... | me, {}, content_type="text/plain")
|
tensorflow/tensor2tensor | tensor2tensor/utils/misc_utils.py | Python | apache-2.0 | 1,305 | 0.003831 | # coding=utf-8
# Copyright 2022 The Tensor2Tensor 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... | scellaneous utilities."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import pprint
import re
# Camel case to snake case utils
_first_cap_re = re | .compile("(.)([A-Z][a-z0-9]+)")
_all_cap_re = re.compile("([a-z0-9])([A-Z])")
def camelcase_to_snakecase(name):
s1 = _first_cap_re.sub(r"\1_\2", name)
return _all_cap_re.sub(r"\1_\2", s1).lower()
def snakecase_to_camelcase(name):
return "".join([w[0].upper() + w[1:] for w in name.split("_")])
def pprint_hpa... |
mpillar/codeeval | 2-hard/ray-of-light/main.py | Python | unlicense | 8,179 | 0.005502 | import sys
import copy
DEBUG = False
ROOM_SIZE = 10
LIGHT_DISTRIBUTION = 20
class Point(object):
def __init__(self, row, col):
self.row = row
self.col = col
def __eq__(self, other):
return self.row == other.row and self.col == other.col
def __str__(self):
return "(%i,%i)"... | n.row+1, current_position.col+1)
} [trajectory]
@staticmethod
def _is_corner(point):
corners = [Point(0, 0) | , Point(0, ROOM_SIZE-1), Point(ROOM_SIZE-1, 0), Point(ROOM_SIZE-1, ROOM_SIZE-1)]
return point in corners
@staticmethod
def _is_in_room(point):
return 0 <= point.col < ROOM_SIZE and 0 <= point.row < ROOM_SIZE
@staticmethod
def _is_on_wall(point):
return point.row == 0 or point.r... |
HackBulgaria/Odin | applications/migrations/0004_auto_20150115_1340.py | Python | agpl-3.0 | 398 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migr | ations
class Migration(migrations.Migration):
dependencies = [
('applications', '0003_auto_20150115_1330'),
]
operations = [
migrations.RenameField(
model_name='applicationtask',
old_name='title',
new_ | name='name',
),
]
|
tiangolo/fastapi | docs_src/custom_response/tutorial006.py | Python | mit | 199 | 0 | from fastapi import FastAPI
from fastapi.responses import RedirectResponse
app = Fast | API()
@app.get("/typer" | )
async def redirect_typer():
return RedirectResponse("https://typer.tiangolo.com")
|
tokenly/counterparty-lib | counterpartylib/lib/script.py | Python | mit | 10,947 | 0.00513 | """
None of the functions/objects in this module need be passed `db`.
Naming convention: a `pub` is either a pubkey or a pubkeyhash
"""
import hashlib
import bitcoin as bitcoinlib
import binascii
from bitcoin.core.key import CPubKey
from counterpartylib.lib import util
from counterpartylib.lib import config
from co... | "
if is_multisig(address):
signatures_required, pubkeyhashes, signatures_possible = extract_array(address)
try:
[base58_check_decode(pubkeyhash, config.ADDRESSVE | RSION) for pubkeyhash in pubkeyhashes]
except Base58Error:
raise MultiSigAddressError('Multi‐signature address must use PubKeyHashes, not public keys.')
return construct_array(signatures_required, pubkeyhashes, signatures_possible)
else:
return address
def test_array(signatures_... |
lancezlin/ml_template_py | lib/python2.7/site-packages/ipywidgets/widgets/widget_image.py | Python | mit | 1,267 | 0 | """Image class.
Represents an image in the frontend using a widget.
"""
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BS | D License.
import base64
from .domwidget import DOMWidget
from .widget import register
from traitlets import Unicode, CUnicode, Bytes, observe
@register('Jupyter.Image')
class Image(DOMWidget):
"""Displays an image as a widget.
The `value` of this widget accepts a byte string. The byte string is the
r... | te string using the `format` trait (which
defaults to "png").
"""
_view_name = Unicode('ImageView').tag(sync=True)
_model_name = Unicode('ImageModel').tag(sync=True)
_model_module = Unicode('jupyter-js-widgets').tag(sync=True)
_view_module = Unicode('jupyter-js-widgets').tag(sync=True)
# De... |
openqt/algorithms | leetcode/python/lc826-most-profit-assigning-work.py | Python | gpl-3.0 | 1,478 | 0.004736 | # coding=utf-8
import unittest
"""826. Most Profit Assigning Work
https://leetcode.com/problems/most-prof | it-assigning-work/description/
We have jobs: `difficulty[i]` is the difficulty of the `i`th job, and
`profit[i]` is the profit of the `i`th job.
Now we have some workers. `worker[i]` is the ability of the `i`th worker,
which means that this worker can only complete a job with difficulty at most
`worke | r[i]`.
Every worker can be assigned at most one job, but one job can be completed
multiple times.
For example, if 3 people attempt the same job that pays $1, then the total
profit will be $3. If a worker cannot complete any job, his profit is $0.
What is the most profit we can make?
**Example 1:**
... |
cycoe/class_robber | modules/MisUtils.py | Python | mit | 3,375 | 0.000924 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import random
import os
def getRandomTime(sleepTime):
def wrapper():
return sleepTime * random.random()
return wrapper
class MisUtils(object):
"""
管理配置的类
"""
refreshSleep = getRandomTime(10) # 刷新的间隔时间
wechatPushSleep = getRandomTime(1... | iver email: ')
@staticmethod
def initAttempt():
MisUtils.attempt = MisUtils.maxAttempt
@staticmethod
def descAttempt():
MisUtils.attempt -= 1
if MisUtils.attempt > 0:
return True
else:
# if Mail.connectedToMail:
# threading.Thread... | Logger.log(
# 'Class robber halted because of up to max attempts',
# ['Check your login status', 'Check the response of server']
# ),)).start()
return False
@staticmethod
def getSelected():
if os.path.exists(MisUtils.blackList):
... |
takluyver/readthedocs.org | readthedocs/rtd_tests/factories/comments_factories.py | Python | mit | 2,656 | 0.00113 | from bamboo_boy.materials import Clump
import random
import factory
from comments.models import DocumentComment, DocumentNode, NodeSnapshot
from rtd_tests.factories.general_factories import UserFactory
from rtd_tests.factories.projects_factories import ProjectFactory
class SnapshotFactory(factory.DjangoModelFactory... | .include_factory(
DocumentNodeFactory, 1, project=self.moderated_project)[0]
self.first_moderated_comment, self.second_moderated_comment = self.include_factory(
DocumentCommentFactory, 2, node=self.moderated_node)
self.unmoderated_project = self.include_factory(ProjectFactory,
... | comment_moderation=False
)[0]
self.unmoderated_node = self.include_factory(
DocumentNodeFactory, 1, project=self.unmoderated_project)[0]
self.first_unmoderated_comment, self.second_unmoderated_comment = self.include_facto... |
Ramyak/CodingPractice | algo_practice/coursera-algo-1/min_cuts/minimum_cuts_1_pre.py | Python | gpl-2.0 | 2,942 | 0.008838 | #!/usr/bin/env python
from random import randint, choice
from copy import deepcopy
from math import log
import sys
import cProfile
def fuse(m, x, adj_list):
#print 'Fusing ({}) and ({})'.format(self.x, x.x)
#for i in self.edges:
# print '({})'.format(i.x),
#print ''
new_edge_list = []
for i... | sed_tmp = fused_tmp)
'''
def print_adj_list(adj_list):
for node in adj_list:
print adj_list[node]
def random_contraction(adj_list):
if len(adj_list) <= 2:
return
pivot = choice(adj_list.keys())
| x = choice(adj_list[pivot])
#print '--------'
#print 'Contracting {} and {}'.format(adj_list[pivot], adj_list[x.x])
fuse(pivot, x, adj_list)
del adj_list[x]
#print 'After Contraction'
#print_adj_list(adj_list)
#print '--------'
if len(adj_list) > 2:
random_contraction(adj_list)
... |
valtandor/easybuild-easyblocks | easybuild/easyblocks/a/advisor.py | Python | gpl-2.0 | 2,158 | 0.002317 | ##
# Copyright 2009-2015 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),
# the Hercules foundation (htt... | ep(self):
"""Custom sanity check paths for Advisor"""
custom_paths = {
'files': [],
'dirs': ['advisor_xe/bin64', 'advisor_xe/lib64']
}
super(EB_Advisor, s | elf).sanity_check_step(custom_paths=custom_paths)
def make_module_req_guess(self):
"""
A dictionary of possible directories to look for
"""
guesses = super(EB_Advisor, self).make_module_req_guess()
lib_path = 'advisor_xe/lib64'
include_path = 'advisor_xe/include'
... |
paulray/NICERsoft | nicer/sigmaz.py | Python | mit | 10,393 | 0.014529 | #!/usr/bin/env python
import sys
import numpy as np
import matplotlib.pyplot as plt
from scipy.special import gammaincinv
import pint.models, pint.toa
import astropy.units as u
from pint.residuals import Residuals
import traceback
#np.seterr(all='raise')
def sigmaz(t,y,err,nseg,diagplot=False):
"""Compute sigma_z... | nts the C3 coefficient has a negative variance in the covariance matrix
for jseg in range (0, iseg): # Now loop through each segment of this length
# for iseq > 1 there are multiple segments we need to analyze
segrange=(toas[0]+dur_oneseg*jseg, toas[0]+dur_oneseg*(jseg+1))
... | np.where((toas>(segrange[0]-wiggle)) & (toas<(segrange[1]+wiggle)))
if (np.size(desind))>polyorder+3: # if cov. matrix needed for error estimates on fitted params
#if (np.size(desind))>polyorder: # if cov. matrix not needed
dataspan = np.max(toas[desind]) - ... |
guori12321/todo | todo/parser.py | Python | mit | 2,473 | 0 | # coding=utf8
"""
Parser for todo format string.
from todo.parser import parser
parser.parse(string) # return an Todo instance
"""
from models import Task
from models import Todo
from ply import lex
from ply import yacc
class TodoLexer(object):
"""
Lexer for Todo format string.
Tokens
ID ... | e.g. '(x)'
TASK e.g. 'This is a task'
"""
tokens = (
| "ID",
"DONE",
"TASK",
)
t_ignore = "\x20\x09" # ignore spaces and tabs
def t_ID(self, t):
r'\d+\.([uU]|[lL]|[uU][lL]|[lL][uU])?'
t.value = int(t.value[:-1])
return t
def t_DONE(self, t):
r'(\(x\))'
return t
def t_TASK(self, t):
... |
jacebrowning/gdm | gitman/__main__.py | Python | mit | 590 | 0.001695 | """Package entry point."""
import importlib
import os
im | port sys
from gitman.cli import main
# Declare itself as package if needed for better debugging support
# pylint: disable=multiple-imports,wrong-import-position,redefined-builtin,used-before-assignment
if __name__ == '__main__' and __package__ is None: # pragma: no cover
parent_dir = os.path.abspath(os.path.dir... | a: no cover
main()
|
NeCTAR-RC/ceilometer | ceilometer/openstack/common/rpc/proxy.py | Python | apache-2.0 | 9,459 | 0 | # Copyright 2012-2013 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | :param version_cap: Optionally cap the maximum version used for sent
messages.
:param serializer: Optionaly (de-)serialize entities with a
provided helper.
"""
self.topic = topic
self.default_version = default_version
self.version_cap = version_cap
... |
def _set_version(self, msg, vers):
"""Helper method to set the version in a message.
:param msg: The message having a version added to it.
:param vers: The version number to add to the message.
"""
v = vers if vers else self.default_version
if (self.version_cap and ... |
mlafeldt/rdd.py | rdd/exceptions.py | Python | mit | 407 | 0 | # -*- coding: utf-8 -*-
"""
rdd.exceptions
~~~~~~~~~~~~~~
This module contains the exceptions raised by rdd.
"""
from requests.exceptions import *
class ReadabilityException(RuntimeError):
""" | Base class for Readability exceptions."""
class ShortenerError(ReadabilityException):
" | ""Failed to shorten URL."""
class MetadataError(ReadabilityException):
"""Failed to retrieve metadata."""
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.